es6.js 5.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  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 if (otherMesh.subMeshes) {
  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. /** @hidden */
  159. this._bonesComputationForcedToCPU = false;
  160. this._uniformBuffersNames = {};
  161. this._isReady = false;
  162. this._compilationError = "";
  163. this.name = baseName;
  164. if (attributesNamesOrOptions.attributes) {
  165. var options = attributesNamesOrOptions;
  166. this._engine = uniformsNamesOrEngine;
  167. this._attributesNames = options.attributes;
  168. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  169. this._samplers = options.samplers.slice();
  170. this.defines = options.defines;
  171. this.onError = options.onError;
  172. this.onCompiled = options.onCompiled;
  173. this._fallbacks = options.fallbacks;
  174. this._indexParameters = options.indexParameters;
  175. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  176. if (options.uniformBuffersNames) {
  177. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  178. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  179. }
  180. }
  181. }
  182. else {
  183. this._engine = engine;
  184. this.defines = defines;
  185. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  186. this._samplers = samplers ? samplers.slice() : [];
  187. this._attributesNames = attributesNamesOrOptions;
  188. this.onError = onError;
  189. this.onCompiled = onCompiled;
  190. this._indexParameters = indexParameters;
  191. this._fallbacks = fallbacks;
  192. }
  193. this.uniqueId = Effect._uniqueIdSeed++;
  194. var vertexSource;
  195. var fragmentSource;
  196. if (baseName.vertexElement) {
  197. vertexSource = document.getElementById(baseName.vertexElement);
  198. if (!vertexSource) {
  199. vertexSource = baseName.vertexElement;
  200. }
  201. }
  202. else {
  203. vertexSource = baseName.vertex || baseName;
  204. }
  205. if (baseName.fragmentElement) {
  206. fragmentSource = document.getElementById(baseName.fragmentElement);
  207. if (!fragmentSource) {
  208. fragmentSource = baseName.fragmentElement;
  209. }
  210. }
  211. else {
  212. fragmentSource = baseName.fragment || baseName;
  213. }
  214. this._loadVertexShader(vertexSource, function (vertexCode) {
  215. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  216. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  217. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  218. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  219. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  220. if (baseName) {
  221. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  222. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  223. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  224. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  225. }
  226. else {
  227. _this._vertexSourceCode = migratedVertexCode;
  228. _this._fragmentSourceCode = migratedFragmentCode;
  229. }
  230. _this._prepareEffect();
  231. });
  232. });
  233. });
  234. });
  235. });
  236. });
  237. }
  238. Object.defineProperty(Effect.prototype, "onBindObservable", {
  239. /**
  240. * Observable that will be called when effect is bound.
  241. */
  242. get: function () {
  243. if (!this._onBindObservable) {
  244. this._onBindObservable = new BABYLON.Observable();
  245. }
  246. return this._onBindObservable;
  247. },
  248. enumerable: true,
  249. configurable: true
  250. });
  251. Object.defineProperty(Effect.prototype, "key", {
  252. /**
  253. * Unique key for this effect
  254. */
  255. get: function () {
  256. return this._key;
  257. },
  258. enumerable: true,
  259. configurable: true
  260. });
  261. /**
  262. * If the effect has been compiled and prepared.
  263. * @returns if the effect is compiled and prepared.
  264. */
  265. Effect.prototype.isReady = function () {
  266. return this._isReady;
  267. };
  268. /**
  269. * The engine the effect was initialized with.
  270. * @returns the engine.
  271. */
  272. Effect.prototype.getEngine = function () {
  273. return this._engine;
  274. };
  275. /**
  276. * The compiled webGL program for the effect
  277. * @returns the webGL program.
  278. */
  279. Effect.prototype.getProgram = function () {
  280. return this._program;
  281. };
  282. /**
  283. * The set of names of attribute variables for the shader.
  284. * @returns An array of attribute names.
  285. */
  286. Effect.prototype.getAttributesNames = function () {
  287. return this._attributesNames;
  288. };
  289. /**
  290. * Returns the attribute at the given index.
  291. * @param index The index of the attribute.
  292. * @returns The location of the attribute.
  293. */
  294. Effect.prototype.getAttributeLocation = function (index) {
  295. return this._attributes[index];
  296. };
  297. /**
  298. * Returns the attribute based on the name of the variable.
  299. * @param name of the attribute to look up.
  300. * @returns the attribute location.
  301. */
  302. Effect.prototype.getAttributeLocationByName = function (name) {
  303. var index = this._attributesNames.indexOf(name);
  304. return this._attributes[index];
  305. };
  306. /**
  307. * The number of attributes.
  308. * @returns the numnber of attributes.
  309. */
  310. Effect.prototype.getAttributesCount = function () {
  311. return this._attributes.length;
  312. };
  313. /**
  314. * Gets the index of a uniform variable.
  315. * @param uniformName of the uniform to look up.
  316. * @returns the index.
  317. */
  318. Effect.prototype.getUniformIndex = function (uniformName) {
  319. return this._uniformsNames.indexOf(uniformName);
  320. };
  321. /**
  322. * Returns the attribute based on the name of the variable.
  323. * @param uniformName of the uniform to look up.
  324. * @returns the location of the uniform.
  325. */
  326. Effect.prototype.getUniform = function (uniformName) {
  327. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  328. };
  329. /**
  330. * Returns an array of sampler variable names
  331. * @returns The array of sampler variable neames.
  332. */
  333. Effect.prototype.getSamplers = function () {
  334. return this._samplers;
  335. };
  336. /**
  337. * The error from the last compilation.
  338. * @returns the error string.
  339. */
  340. Effect.prototype.getCompilationError = function () {
  341. return this._compilationError;
  342. };
  343. /**
  344. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  345. * @param func The callback to be used.
  346. */
  347. Effect.prototype.executeWhenCompiled = function (func) {
  348. if (this.isReady()) {
  349. func(this);
  350. return;
  351. }
  352. this.onCompileObservable.add(function (effect) {
  353. func(effect);
  354. });
  355. };
  356. /** @hidden */
  357. Effect.prototype._loadVertexShader = function (vertex, callback) {
  358. if (BABYLON.Tools.IsWindowObjectExist()) {
  359. // DOM element ?
  360. if (vertex instanceof HTMLElement) {
  361. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  362. callback(vertexCode);
  363. return;
  364. }
  365. }
  366. // Base64 encoded ?
  367. if (vertex.substr(0, 7) === "base64:") {
  368. var vertexBinary = window.atob(vertex.substr(7));
  369. callback(vertexBinary);
  370. return;
  371. }
  372. // Is in local store ?
  373. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  374. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  375. return;
  376. }
  377. var vertexShaderUrl;
  378. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  379. vertexShaderUrl = vertex;
  380. }
  381. else {
  382. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  383. }
  384. // Vertex shader
  385. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  386. };
  387. /** @hidden */
  388. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  389. if (BABYLON.Tools.IsWindowObjectExist()) {
  390. // DOM element ?
  391. if (fragment instanceof HTMLElement) {
  392. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  393. callback(fragmentCode);
  394. return;
  395. }
  396. }
  397. // Base64 encoded ?
  398. if (fragment.substr(0, 7) === "base64:") {
  399. var fragmentBinary = window.atob(fragment.substr(7));
  400. callback(fragmentBinary);
  401. return;
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  405. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  406. return;
  407. }
  408. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  409. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  410. return;
  411. }
  412. var fragmentShaderUrl;
  413. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  414. fragmentShaderUrl = fragment;
  415. }
  416. else {
  417. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  418. }
  419. // Fragment shader
  420. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  421. };
  422. /** @hidden */
  423. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  424. // Rebuild shaders source code
  425. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  426. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  427. vertexCode = prefix + vertexCode;
  428. fragmentCode = prefix + fragmentCode;
  429. // Number lines of shaders source code
  430. var i = 2;
  431. var regex = /\n/gm;
  432. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  433. i = 2;
  434. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  435. // Dump shaders name and formatted source code
  436. if (this.name.vertexElement) {
  437. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  438. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  439. }
  440. else if (this.name.vertex) {
  441. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  442. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  443. }
  444. else {
  445. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  446. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  447. }
  448. };
  449. ;
  450. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  451. var preparedSourceCode = this._processPrecision(sourceCode);
  452. if (this._engine.webGLVersion == 1) {
  453. callback(preparedSourceCode);
  454. return;
  455. }
  456. // Already converted
  457. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  458. callback(preparedSourceCode.replace("#version 300 es", ""));
  459. return;
  460. }
  461. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  462. // Remove extensions
  463. // #extension GL_OES_standard_derivatives : enable
  464. // #extension GL_EXT_shader_texture_lod : enable
  465. // #extension GL_EXT_frag_depth : enable
  466. // #extension GL_EXT_draw_buffers : require
  467. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  468. var result = preparedSourceCode.replace(regex, "");
  469. // Migrate to GLSL v300
  470. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  471. result = result.replace(/attribute[ \t]/g, "in ");
  472. result = result.replace(/[ \t]attribute/g, " in");
  473. if (isFragment) {
  474. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  475. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  476. result = result.replace(/texture2D\s*\(/g, "texture(");
  477. result = result.replace(/textureCube\s*\(/g, "texture(");
  478. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  479. result = result.replace(/gl_FragColor/g, "glFragColor");
  480. result = result.replace(/gl_FragData/g, "glFragData");
  481. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  482. }
  483. callback(result);
  484. };
  485. Effect.prototype._processIncludes = function (sourceCode, callback) {
  486. var _this = this;
  487. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  488. var match = regex.exec(sourceCode);
  489. var returnValue = new String(sourceCode);
  490. while (match != null) {
  491. var includeFile = match[1];
  492. // Uniform declaration
  493. if (includeFile.indexOf("__decl__") !== -1) {
  494. includeFile = includeFile.replace(/__decl__/, "");
  495. if (this._engine.supportsUniformBuffers) {
  496. includeFile = includeFile.replace(/Vertex/, "Ubo");
  497. includeFile = includeFile.replace(/Fragment/, "Ubo");
  498. }
  499. includeFile = includeFile + "Declaration";
  500. }
  501. if (Effect.IncludesShadersStore[includeFile]) {
  502. // Substitution
  503. var includeContent = Effect.IncludesShadersStore[includeFile];
  504. if (match[2]) {
  505. var splits = match[3].split(",");
  506. for (var index = 0; index < splits.length; index += 2) {
  507. var source = new RegExp(splits[index], "g");
  508. var dest = splits[index + 1];
  509. includeContent = includeContent.replace(source, dest);
  510. }
  511. }
  512. if (match[4]) {
  513. var indexString = match[5];
  514. if (indexString.indexOf("..") !== -1) {
  515. var indexSplits = indexString.split("..");
  516. var minIndex = parseInt(indexSplits[0]);
  517. var maxIndex = parseInt(indexSplits[1]);
  518. var sourceIncludeContent = includeContent.slice(0);
  519. includeContent = "";
  520. if (isNaN(maxIndex)) {
  521. maxIndex = this._indexParameters[indexSplits[1]];
  522. }
  523. for (var i = minIndex; i < maxIndex; i++) {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  531. }
  532. }
  533. else {
  534. if (!this._engine.supportsUniformBuffers) {
  535. // Ubo replacement
  536. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  537. return p1 + "{X}";
  538. });
  539. }
  540. includeContent = includeContent.replace(/\{X\}/g, indexString);
  541. }
  542. }
  543. // Replace
  544. returnValue = returnValue.replace(match[0], includeContent);
  545. }
  546. else {
  547. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  548. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  549. Effect.IncludesShadersStore[includeFile] = fileContent;
  550. _this._processIncludes(returnValue, callback);
  551. });
  552. return;
  553. }
  554. match = regex.exec(sourceCode);
  555. }
  556. callback(returnValue);
  557. };
  558. Effect.prototype._processPrecision = function (source) {
  559. if (source.indexOf("precision highp float") === -1) {
  560. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  561. source = "precision mediump float;\n" + source;
  562. }
  563. else {
  564. source = "precision highp float;\n" + source;
  565. }
  566. }
  567. else {
  568. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  569. source = source.replace("precision highp float", "precision mediump float");
  570. }
  571. }
  572. return source;
  573. };
  574. /**
  575. * Recompiles the webGL program
  576. * @param vertexSourceCode The source code for the vertex shader.
  577. * @param fragmentSourceCode The source code for the fragment shader.
  578. * @param onCompiled Callback called when completed.
  579. * @param onError Callback called on error.
  580. * @hidden
  581. */
  582. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  583. var _this = this;
  584. this._isReady = false;
  585. this._vertexSourceCodeOverride = vertexSourceCode;
  586. this._fragmentSourceCodeOverride = fragmentSourceCode;
  587. this.onError = function (effect, error) {
  588. if (onError) {
  589. onError(error);
  590. }
  591. };
  592. this.onCompiled = function () {
  593. var scenes = _this.getEngine().scenes;
  594. for (var i = 0; i < scenes.length; i++) {
  595. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  596. }
  597. if (onCompiled) {
  598. onCompiled(_this._program);
  599. }
  600. };
  601. this._fallbacks = null;
  602. this._prepareEffect();
  603. };
  604. /**
  605. * Gets the uniform locations of the the specified variable names
  606. * @param names THe names of the variables to lookup.
  607. * @returns Array of locations in the same order as variable names.
  608. */
  609. Effect.prototype.getSpecificUniformLocations = function (names) {
  610. var engine = this._engine;
  611. return engine.getUniforms(this._program, names);
  612. };
  613. /**
  614. * Prepares the effect
  615. * @hidden
  616. */
  617. Effect.prototype._prepareEffect = function () {
  618. var attributesNames = this._attributesNames;
  619. var defines = this.defines;
  620. var fallbacks = this._fallbacks;
  621. this._valueCache = {};
  622. var previousProgram = this._program;
  623. try {
  624. var engine = this._engine;
  625. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  626. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  627. }
  628. else {
  629. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  630. }
  631. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  632. if (engine.supportsUniformBuffers) {
  633. for (var name in this._uniformBuffersNames) {
  634. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  635. }
  636. }
  637. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  638. this._attributes = engine.getAttributes(this._program, attributesNames);
  639. var index;
  640. for (index = 0; index < this._samplers.length; index++) {
  641. var sampler = this.getUniform(this._samplers[index]);
  642. if (sampler == null) {
  643. this._samplers.splice(index, 1);
  644. index--;
  645. }
  646. }
  647. engine.bindSamplers(this);
  648. this._compilationError = "";
  649. this._isReady = true;
  650. if (this.onCompiled) {
  651. this.onCompiled(this);
  652. }
  653. this.onCompileObservable.notifyObservers(this);
  654. this.onCompileObservable.clear();
  655. // Unbind mesh reference in fallbacks
  656. if (this._fallbacks) {
  657. this._fallbacks.unBindMesh();
  658. }
  659. if (previousProgram) {
  660. this.getEngine()._deleteProgram(previousProgram);
  661. }
  662. }
  663. catch (e) {
  664. this._compilationError = e.message;
  665. // Let's go through fallbacks then
  666. BABYLON.Tools.Error("Unable to compile effect:");
  667. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  668. return " " + uniform;
  669. }));
  670. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  671. return " " + attribute;
  672. }));
  673. BABYLON.Tools.Error("Error: " + this._compilationError);
  674. if (previousProgram) {
  675. this._program = previousProgram;
  676. this._isReady = true;
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. }
  682. if (fallbacks && fallbacks.isMoreFallbacks) {
  683. BABYLON.Tools.Error("Trying next fallback.");
  684. this.defines = fallbacks.reduce(this.defines, this);
  685. this._prepareEffect();
  686. }
  687. else { // Sorry we did everything we can
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. this.onErrorObservable.clear();
  693. // Unbind mesh reference in fallbacks
  694. if (this._fallbacks) {
  695. this._fallbacks.unBindMesh();
  696. }
  697. }
  698. }
  699. };
  700. Object.defineProperty(Effect.prototype, "isSupported", {
  701. /**
  702. * Checks if the effect is supported. (Must be called after compilation)
  703. */
  704. get: function () {
  705. return this._compilationError === "";
  706. },
  707. enumerable: true,
  708. configurable: true
  709. });
  710. /**
  711. * Binds a texture to the engine to be used as output of the shader.
  712. * @param channel Name of the output variable.
  713. * @param texture Texture to bind.
  714. * @hidden
  715. */
  716. Effect.prototype._bindTexture = function (channel, texture) {
  717. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  718. };
  719. /**
  720. * Sets a texture on the engine to be used in the shader.
  721. * @param channel Name of the sampler variable.
  722. * @param texture Texture to set.
  723. */
  724. Effect.prototype.setTexture = function (channel, texture) {
  725. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  726. };
  727. /**
  728. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  729. * @param channel Name of the sampler variable.
  730. * @param texture Texture to set.
  731. */
  732. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  733. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  734. };
  735. /**
  736. * Sets an array of textures on the engine to be used in the shader.
  737. * @param channel Name of the variable.
  738. * @param textures Textures to set.
  739. */
  740. Effect.prototype.setTextureArray = function (channel, textures) {
  741. if (this._samplers.indexOf(channel + "Ex") === -1) {
  742. var initialPos = this._samplers.indexOf(channel);
  743. for (var index = 1; index < textures.length; index++) {
  744. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  745. }
  746. }
  747. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  748. };
  749. /**
  750. * 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)
  751. * @param channel Name of the sampler variable.
  752. * @param postProcess Post process to get the input texture from.
  753. */
  754. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  755. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  756. };
  757. /**
  758. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  759. * 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)
  760. * @param channel Name of the sampler variable.
  761. * @param postProcess Post process to get the output texture from.
  762. */
  763. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  764. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  765. };
  766. /** @hidden */
  767. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  768. var cache = this._valueCache[uniformName];
  769. var flag = matrix.updateFlag;
  770. if (cache !== undefined && cache === flag) {
  771. return false;
  772. }
  773. this._valueCache[uniformName] = flag;
  774. return true;
  775. };
  776. /** @hidden */
  777. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  778. var cache = this._valueCache[uniformName];
  779. if (!cache) {
  780. cache = [x, y];
  781. this._valueCache[uniformName] = cache;
  782. return true;
  783. }
  784. var changed = false;
  785. if (cache[0] !== x) {
  786. cache[0] = x;
  787. changed = true;
  788. }
  789. if (cache[1] !== y) {
  790. cache[1] = y;
  791. changed = true;
  792. }
  793. return changed;
  794. };
  795. /** @hidden */
  796. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  797. var cache = this._valueCache[uniformName];
  798. if (!cache) {
  799. cache = [x, y, z];
  800. this._valueCache[uniformName] = cache;
  801. return true;
  802. }
  803. var changed = false;
  804. if (cache[0] !== x) {
  805. cache[0] = x;
  806. changed = true;
  807. }
  808. if (cache[1] !== y) {
  809. cache[1] = y;
  810. changed = true;
  811. }
  812. if (cache[2] !== z) {
  813. cache[2] = z;
  814. changed = true;
  815. }
  816. return changed;
  817. };
  818. /** @hidden */
  819. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  820. var cache = this._valueCache[uniformName];
  821. if (!cache) {
  822. cache = [x, y, z, w];
  823. this._valueCache[uniformName] = cache;
  824. return true;
  825. }
  826. var changed = false;
  827. if (cache[0] !== x) {
  828. cache[0] = x;
  829. changed = true;
  830. }
  831. if (cache[1] !== y) {
  832. cache[1] = y;
  833. changed = true;
  834. }
  835. if (cache[2] !== z) {
  836. cache[2] = z;
  837. changed = true;
  838. }
  839. if (cache[3] !== w) {
  840. cache[3] = w;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /**
  846. * Binds a buffer to a uniform.
  847. * @param buffer Buffer to bind.
  848. * @param name Name of the uniform variable to bind to.
  849. */
  850. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  851. var bufferName = this._uniformBuffersNames[name];
  852. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  853. return;
  854. }
  855. Effect._baseCache[bufferName] = buffer;
  856. this._engine.bindUniformBufferBase(buffer, bufferName);
  857. };
  858. /**
  859. * Binds block to a uniform.
  860. * @param blockName Name of the block to bind.
  861. * @param index Index to bind.
  862. */
  863. Effect.prototype.bindUniformBlock = function (blockName, index) {
  864. this._engine.bindUniformBlock(this._program, blockName, index);
  865. };
  866. /**
  867. * Sets an interger value on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param value Value to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setInt = function (uniformName, value) {
  873. var cache = this._valueCache[uniformName];
  874. if (cache !== undefined && cache === value)
  875. return this;
  876. this._valueCache[uniformName] = value;
  877. this._engine.setInt(this.getUniform(uniformName), value);
  878. return this;
  879. };
  880. /**
  881. * Sets an int array on a uniform variable.
  882. * @param uniformName Name of the variable.
  883. * @param array array to be set.
  884. * @returns this effect.
  885. */
  886. Effect.prototype.setIntArray = function (uniformName, array) {
  887. this._valueCache[uniformName] = null;
  888. this._engine.setIntArray(this.getUniform(uniformName), array);
  889. return this;
  890. };
  891. /**
  892. * 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)
  893. * @param uniformName Name of the variable.
  894. * @param array array to be set.
  895. * @returns this effect.
  896. */
  897. Effect.prototype.setIntArray2 = function (uniformName, array) {
  898. this._valueCache[uniformName] = null;
  899. this._engine.setIntArray2(this.getUniform(uniformName), array);
  900. return this;
  901. };
  902. /**
  903. * 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)
  904. * @param uniformName Name of the variable.
  905. * @param array array to be set.
  906. * @returns this effect.
  907. */
  908. Effect.prototype.setIntArray3 = function (uniformName, array) {
  909. this._valueCache[uniformName] = null;
  910. this._engine.setIntArray3(this.getUniform(uniformName), array);
  911. return this;
  912. };
  913. /**
  914. * 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)
  915. * @param uniformName Name of the variable.
  916. * @param array array to be set.
  917. * @returns this effect.
  918. */
  919. Effect.prototype.setIntArray4 = function (uniformName, array) {
  920. this._valueCache[uniformName] = null;
  921. this._engine.setIntArray4(this.getUniform(uniformName), array);
  922. return this;
  923. };
  924. /**
  925. * Sets an float array on a uniform variable.
  926. * @param uniformName Name of the variable.
  927. * @param array array to be set.
  928. * @returns this effect.
  929. */
  930. Effect.prototype.setFloatArray = function (uniformName, array) {
  931. this._valueCache[uniformName] = null;
  932. this._engine.setFloatArray(this.getUniform(uniformName), array);
  933. return this;
  934. };
  935. /**
  936. * 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)
  937. * @param uniformName Name of the variable.
  938. * @param array array to be set.
  939. * @returns this effect.
  940. */
  941. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  942. this._valueCache[uniformName] = null;
  943. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  944. return this;
  945. };
  946. /**
  947. * 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)
  948. * @param uniformName Name of the variable.
  949. * @param array array to be set.
  950. * @returns this effect.
  951. */
  952. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  953. this._valueCache[uniformName] = null;
  954. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  955. return this;
  956. };
  957. /**
  958. * 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)
  959. * @param uniformName Name of the variable.
  960. * @param array array to be set.
  961. * @returns this effect.
  962. */
  963. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  964. this._valueCache[uniformName] = null;
  965. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  966. return this;
  967. };
  968. /**
  969. * Sets an array on a uniform variable.
  970. * @param uniformName Name of the variable.
  971. * @param array array to be set.
  972. * @returns this effect.
  973. */
  974. Effect.prototype.setArray = function (uniformName, array) {
  975. this._valueCache[uniformName] = null;
  976. this._engine.setArray(this.getUniform(uniformName), array);
  977. return this;
  978. };
  979. /**
  980. * 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)
  981. * @param uniformName Name of the variable.
  982. * @param array array to be set.
  983. * @returns this effect.
  984. */
  985. Effect.prototype.setArray2 = function (uniformName, array) {
  986. this._valueCache[uniformName] = null;
  987. this._engine.setArray2(this.getUniform(uniformName), array);
  988. return this;
  989. };
  990. /**
  991. * 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)
  992. * @param uniformName Name of the variable.
  993. * @param array array to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setArray3 = function (uniformName, array) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setArray3(this.getUniform(uniformName), array);
  999. return this;
  1000. };
  1001. /**
  1002. * 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)
  1003. * @param uniformName Name of the variable.
  1004. * @param array array to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setArray4 = function (uniformName, array) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setArray4(this.getUniform(uniformName), array);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrices on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrices matrices to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1019. if (!matrices) {
  1020. return this;
  1021. }
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets matrix on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1033. if (this._cacheMatrix(uniformName, matrix)) {
  1034. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1035. }
  1036. return this;
  1037. };
  1038. /**
  1039. * 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)
  1040. * @param uniformName Name of the variable.
  1041. * @param matrix matrix to be set.
  1042. * @returns this effect.
  1043. */
  1044. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1045. this._valueCache[uniformName] = null;
  1046. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1047. return this;
  1048. };
  1049. /**
  1050. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1051. * @param uniformName Name of the variable.
  1052. * @param matrix matrix to be set.
  1053. * @returns this effect.
  1054. */
  1055. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1056. this._valueCache[uniformName] = null;
  1057. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a float on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param value value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setFloat = function (uniformName, value) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === value)
  1069. return this;
  1070. this._valueCache[uniformName] = value;
  1071. this._engine.setFloat(this.getUniform(uniformName), value);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a boolean on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param bool value to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setBool = function (uniformName, bool) {
  1081. var cache = this._valueCache[uniformName];
  1082. if (cache !== undefined && cache === bool)
  1083. return this;
  1084. this._valueCache[uniformName] = bool;
  1085. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a Vector2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param vector2 vector2 to be set.
  1092. * @returns this effect.
  1093. */
  1094. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1095. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1096. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1097. }
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a float2 on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param x First float in float2.
  1104. * @param y Second float in float2.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1108. if (this._cacheFloat2(uniformName, x, y)) {
  1109. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a Vector3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param vector3 Value to be set.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1120. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a float3 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param x First float in float3.
  1129. * @param y Second float in float3.
  1130. * @param z Third float in float3.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1134. if (this._cacheFloat3(uniformName, x, y, z)) {
  1135. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a Vector4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param vector4 Value to be set.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1146. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a float4 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param x First float in float4.
  1155. * @param y Second float in float4.
  1156. * @param z Third float in float4.
  1157. * @param w Fourth float in float4.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1161. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color3 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setColor3 = function (uniformName, color3) {
  1173. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1174. this._engine.setColor3(this.getUniform(uniformName), color3);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a Color4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param color3 Value to be set.
  1182. * @param alpha Alpha value to be set.
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1186. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1187. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Sets a Color4 on a uniform variable
  1193. * @param uniformName defines the name of the variable
  1194. * @param color4 defines the value to be set
  1195. * @returns this effect.
  1196. */
  1197. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1198. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1199. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1200. }
  1201. return this;
  1202. };
  1203. /**
  1204. * This function will add a new shader to the shader store
  1205. * @param name the name of the shader
  1206. * @param pixelShader optional pixel shader content
  1207. * @param vertexShader optional vertex shader content
  1208. */
  1209. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1210. if (pixelShader) {
  1211. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1212. }
  1213. if (vertexShader) {
  1214. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1215. }
  1216. };
  1217. /**
  1218. * Resets the cache of effects.
  1219. */
  1220. Effect.ResetCache = function () {
  1221. Effect._baseCache = {};
  1222. };
  1223. Effect._uniqueIdSeed = 0;
  1224. Effect._baseCache = {};
  1225. /**
  1226. * Store of each shader (The can be looked up using effect.key)
  1227. */
  1228. Effect.ShadersStore = {};
  1229. /**
  1230. * Store of each included file for a shader (The can be looked up using effect.key)
  1231. */
  1232. Effect.IncludesShadersStore = {};
  1233. return Effect;
  1234. }());
  1235. BABYLON.Effect = Effect;
  1236. })(BABYLON || (BABYLON = {}));
  1237. //# sourceMappingURL=babylon.effect.js.map
  1238. //# sourceMappingURL=babylon.types.js.map
  1239. var BABYLON;
  1240. (function (BABYLON) {
  1241. var KeyboardEventTypes = /** @class */ (function () {
  1242. function KeyboardEventTypes() {
  1243. }
  1244. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1245. get: function () {
  1246. return KeyboardEventTypes._KEYDOWN;
  1247. },
  1248. enumerable: true,
  1249. configurable: true
  1250. });
  1251. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1252. get: function () {
  1253. return KeyboardEventTypes._KEYUP;
  1254. },
  1255. enumerable: true,
  1256. configurable: true
  1257. });
  1258. KeyboardEventTypes._KEYDOWN = 0x01;
  1259. KeyboardEventTypes._KEYUP = 0x02;
  1260. return KeyboardEventTypes;
  1261. }());
  1262. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1263. var KeyboardInfo = /** @class */ (function () {
  1264. function KeyboardInfo(type, event) {
  1265. this.type = type;
  1266. this.event = event;
  1267. }
  1268. return KeyboardInfo;
  1269. }());
  1270. BABYLON.KeyboardInfo = KeyboardInfo;
  1271. /**
  1272. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1273. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1274. */
  1275. var KeyboardInfoPre = /** @class */ (function (_super) {
  1276. __extends(KeyboardInfoPre, _super);
  1277. function KeyboardInfoPre(type, event) {
  1278. var _this = _super.call(this, type, event) || this;
  1279. _this.skipOnPointerObservable = false;
  1280. return _this;
  1281. }
  1282. return KeyboardInfoPre;
  1283. }(KeyboardInfo));
  1284. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1285. })(BABYLON || (BABYLON = {}));
  1286. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1287. var BABYLON;
  1288. (function (BABYLON) {
  1289. var PointerEventTypes = /** @class */ (function () {
  1290. function PointerEventTypes() {
  1291. }
  1292. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1293. get: function () {
  1294. return PointerEventTypes._POINTERDOWN;
  1295. },
  1296. enumerable: true,
  1297. configurable: true
  1298. });
  1299. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1300. get: function () {
  1301. return PointerEventTypes._POINTERUP;
  1302. },
  1303. enumerable: true,
  1304. configurable: true
  1305. });
  1306. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1307. get: function () {
  1308. return PointerEventTypes._POINTERMOVE;
  1309. },
  1310. enumerable: true,
  1311. configurable: true
  1312. });
  1313. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1314. get: function () {
  1315. return PointerEventTypes._POINTERWHEEL;
  1316. },
  1317. enumerable: true,
  1318. configurable: true
  1319. });
  1320. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1321. get: function () {
  1322. return PointerEventTypes._POINTERPICK;
  1323. },
  1324. enumerable: true,
  1325. configurable: true
  1326. });
  1327. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1328. get: function () {
  1329. return PointerEventTypes._POINTERTAP;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1335. get: function () {
  1336. return PointerEventTypes._POINTERDOUBLETAP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. PointerEventTypes._POINTERDOWN = 0x01;
  1342. PointerEventTypes._POINTERUP = 0x02;
  1343. PointerEventTypes._POINTERMOVE = 0x04;
  1344. PointerEventTypes._POINTERWHEEL = 0x08;
  1345. PointerEventTypes._POINTERPICK = 0x10;
  1346. PointerEventTypes._POINTERTAP = 0x20;
  1347. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1348. return PointerEventTypes;
  1349. }());
  1350. BABYLON.PointerEventTypes = PointerEventTypes;
  1351. var PointerInfoBase = /** @class */ (function () {
  1352. function PointerInfoBase(type, event) {
  1353. this.type = type;
  1354. this.event = event;
  1355. }
  1356. return PointerInfoBase;
  1357. }());
  1358. BABYLON.PointerInfoBase = PointerInfoBase;
  1359. /**
  1360. * This class is used to store pointer related info for the onPrePointerObservable event.
  1361. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1362. */
  1363. var PointerInfoPre = /** @class */ (function (_super) {
  1364. __extends(PointerInfoPre, _super);
  1365. function PointerInfoPre(type, event, localX, localY) {
  1366. var _this = _super.call(this, type, event) || this;
  1367. /**
  1368. * Ray from a pointer if availible (eg. 6dof controller)
  1369. */
  1370. _this.ray = null;
  1371. _this.skipOnPointerObservable = false;
  1372. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1373. return _this;
  1374. }
  1375. return PointerInfoPre;
  1376. }(PointerInfoBase));
  1377. BABYLON.PointerInfoPre = PointerInfoPre;
  1378. /**
  1379. * This type contains all the data related to a pointer event in Babylon.js.
  1380. * 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.
  1381. */
  1382. var PointerInfo = /** @class */ (function (_super) {
  1383. __extends(PointerInfo, _super);
  1384. function PointerInfo(type, event, pickInfo) {
  1385. var _this = _super.call(this, type, event) || this;
  1386. _this.pickInfo = pickInfo;
  1387. return _this;
  1388. }
  1389. return PointerInfo;
  1390. }(PointerInfoBase));
  1391. BABYLON.PointerInfo = PointerInfo;
  1392. })(BABYLON || (BABYLON = {}));
  1393. //# sourceMappingURL=babylon.pointerEvents.js.map
  1394. var BABYLON;
  1395. (function (BABYLON) {
  1396. BABYLON.ToGammaSpace = 1 / 2.2;
  1397. BABYLON.ToLinearSpace = 2.2;
  1398. BABYLON.Epsilon = 0.001;
  1399. /**
  1400. * Class used to hold a RBG color
  1401. */
  1402. var Color3 = /** @class */ (function () {
  1403. /**
  1404. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1405. * @param r defines the red component (between 0 and 1, default is 0)
  1406. * @param g defines the green component (between 0 and 1, default is 0)
  1407. * @param b defines the blue component (between 0 and 1, default is 0)
  1408. */
  1409. function Color3(
  1410. /**
  1411. * Defines the red component (between 0 and 1, default is 0)
  1412. */
  1413. r,
  1414. /**
  1415. * Defines the green component (between 0 and 1, default is 0)
  1416. */
  1417. g,
  1418. /**
  1419. * Defines the blue component (between 0 and 1, default is 0)
  1420. */
  1421. b) {
  1422. if (r === void 0) { r = 0; }
  1423. if (g === void 0) { g = 0; }
  1424. if (b === void 0) { b = 0; }
  1425. this.r = r;
  1426. this.g = g;
  1427. this.b = b;
  1428. }
  1429. /**
  1430. * Creates a string with the Color3 current values
  1431. * @returns the string representation of the Color3 object
  1432. */
  1433. Color3.prototype.toString = function () {
  1434. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1435. };
  1436. /**
  1437. * Returns the string "Color3"
  1438. * @returns "Color3"
  1439. */
  1440. Color3.prototype.getClassName = function () {
  1441. return "Color3";
  1442. };
  1443. /**
  1444. * Compute the Color3 hash code
  1445. * @returns an unique number that can be used to hash Color3 objects
  1446. */
  1447. Color3.prototype.getHashCode = function () {
  1448. var hash = this.r || 0;
  1449. hash = (hash * 397) ^ (this.g || 0);
  1450. hash = (hash * 397) ^ (this.b || 0);
  1451. return hash;
  1452. };
  1453. // Operators
  1454. /**
  1455. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1456. * @param array defines the array where to store the r,g,b components
  1457. * @param index defines an optional index in the target array to define where to start storing values
  1458. * @returns the current Color3 object
  1459. */
  1460. Color3.prototype.toArray = function (array, index) {
  1461. if (index === undefined) {
  1462. index = 0;
  1463. }
  1464. array[index] = this.r;
  1465. array[index + 1] = this.g;
  1466. array[index + 2] = this.b;
  1467. return this;
  1468. };
  1469. /**
  1470. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1471. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1472. * @returns a new {BABYLON.Color4} object
  1473. */
  1474. Color3.prototype.toColor4 = function (alpha) {
  1475. if (alpha === void 0) { alpha = 1; }
  1476. return new Color4(this.r, this.g, this.b, alpha);
  1477. };
  1478. /**
  1479. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1480. * @returns the new array
  1481. */
  1482. Color3.prototype.asArray = function () {
  1483. var result = new Array();
  1484. this.toArray(result, 0);
  1485. return result;
  1486. };
  1487. /**
  1488. * Returns the luminance value
  1489. * @returns a float value
  1490. */
  1491. Color3.prototype.toLuminance = function () {
  1492. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1493. };
  1494. /**
  1495. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1496. * @param otherColor defines the second operand
  1497. * @returns the new Color3 object
  1498. */
  1499. Color3.prototype.multiply = function (otherColor) {
  1500. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1501. };
  1502. /**
  1503. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1504. * @param otherColor defines the second operand
  1505. * @param result defines the Color3 object where to store the result
  1506. * @returns the current Color3
  1507. */
  1508. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1509. result.r = this.r * otherColor.r;
  1510. result.g = this.g * otherColor.g;
  1511. result.b = this.b * otherColor.b;
  1512. return this;
  1513. };
  1514. /**
  1515. * Determines equality between Color3 objects
  1516. * @param otherColor defines the second operand
  1517. * @returns true if the rgb values are equal to the given ones
  1518. */
  1519. Color3.prototype.equals = function (otherColor) {
  1520. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1521. };
  1522. /**
  1523. * Determines equality between the current Color3 object and a set of r,b,g values
  1524. * @param r defines the red component to check
  1525. * @param g defines the green component to check
  1526. * @param b defines the blue component to check
  1527. * @returns true if the rgb values are equal to the given ones
  1528. */
  1529. Color3.prototype.equalsFloats = function (r, g, b) {
  1530. return this.r === r && this.g === g && this.b === b;
  1531. };
  1532. /**
  1533. * Multiplies in place each rgb value by scale
  1534. * @param scale defines the scaling factor
  1535. * @returns the updated Color3
  1536. */
  1537. Color3.prototype.scale = function (scale) {
  1538. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1539. };
  1540. /**
  1541. * Multiplies the rgb values by scale and stores the result into "result"
  1542. * @param scale defines the scaling factor
  1543. * @param result defines the Color3 object where to store the result
  1544. * @returns the unmodified current Color3
  1545. */
  1546. Color3.prototype.scaleToRef = function (scale, result) {
  1547. result.r = this.r * scale;
  1548. result.g = this.g * scale;
  1549. result.b = this.b * scale;
  1550. return this;
  1551. };
  1552. /**
  1553. * Scale the current Color3 values by a factor and add the result to a given Color3
  1554. * @param scale defines the scale factor
  1555. * @param result defines color to store the result into
  1556. * @returns the unmodified current Color3
  1557. */
  1558. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1559. result.r += this.r * scale;
  1560. result.g += this.g * scale;
  1561. result.b += this.b * scale;
  1562. return this;
  1563. };
  1564. /**
  1565. * Clamps the rgb values by the min and max values and stores the result into "result"
  1566. * @param min defines minimum clamping value (default is 0)
  1567. * @param max defines maximum clamping value (default is 1)
  1568. * @param result defines color to store the result into
  1569. * @returns the original Color3
  1570. */
  1571. Color3.prototype.clampToRef = function (min, max, result) {
  1572. if (min === void 0) { min = 0; }
  1573. if (max === void 0) { max = 1; }
  1574. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1575. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1576. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1577. return this;
  1578. };
  1579. /**
  1580. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1581. * @param otherColor defines the second operand
  1582. * @returns the new Color3
  1583. */
  1584. Color3.prototype.add = function (otherColor) {
  1585. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1586. };
  1587. /**
  1588. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1589. * @param otherColor defines the second operand
  1590. * @param result defines Color3 object to store the result into
  1591. * @returns the unmodified current Color3
  1592. */
  1593. Color3.prototype.addToRef = function (otherColor, result) {
  1594. result.r = this.r + otherColor.r;
  1595. result.g = this.g + otherColor.g;
  1596. result.b = this.b + otherColor.b;
  1597. return this;
  1598. };
  1599. /**
  1600. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1601. * @param otherColor defines the second operand
  1602. * @returns the new Color3
  1603. */
  1604. Color3.prototype.subtract = function (otherColor) {
  1605. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1606. };
  1607. /**
  1608. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1609. * @param otherColor defines the second operand
  1610. * @param result defines Color3 object to store the result into
  1611. * @returns the unmodified current Color3
  1612. */
  1613. Color3.prototype.subtractToRef = function (otherColor, result) {
  1614. result.r = this.r - otherColor.r;
  1615. result.g = this.g - otherColor.g;
  1616. result.b = this.b - otherColor.b;
  1617. return this;
  1618. };
  1619. /**
  1620. * Copy the current object
  1621. * @returns a new Color3 copied the current one
  1622. */
  1623. Color3.prototype.clone = function () {
  1624. return new Color3(this.r, this.g, this.b);
  1625. };
  1626. /**
  1627. * Copies the rgb values from the source in the current Color3
  1628. * @param source defines the source Color3 object
  1629. * @returns the updated Color3 object
  1630. */
  1631. Color3.prototype.copyFrom = function (source) {
  1632. this.r = source.r;
  1633. this.g = source.g;
  1634. this.b = source.b;
  1635. return this;
  1636. };
  1637. /**
  1638. * Updates the Color3 rgb values from the given floats
  1639. * @param r defines the red component to read from
  1640. * @param g defines the green component to read from
  1641. * @param b defines the blue component to read from
  1642. * @returns the current Color3 object
  1643. */
  1644. Color3.prototype.copyFromFloats = function (r, g, b) {
  1645. this.r = r;
  1646. this.g = g;
  1647. this.b = b;
  1648. return this;
  1649. };
  1650. /**
  1651. * Updates the Color3 rgb values from the given floats
  1652. * @param r defines the red component to read from
  1653. * @param g defines the green component to read from
  1654. * @param b defines the blue component to read from
  1655. * @returns the current Color3 object
  1656. */
  1657. Color3.prototype.set = function (r, g, b) {
  1658. return this.copyFromFloats(r, g, b);
  1659. };
  1660. /**
  1661. * Compute the Color3 hexadecimal code as a string
  1662. * @returns a string containing the hexadecimal representation of the Color3 object
  1663. */
  1664. Color3.prototype.toHexString = function () {
  1665. var intR = (this.r * 255) | 0;
  1666. var intG = (this.g * 255) | 0;
  1667. var intB = (this.b * 255) | 0;
  1668. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1669. };
  1670. /**
  1671. * Computes a new Color3 converted from the current one to linear space
  1672. * @returns a new Color3 object
  1673. */
  1674. Color3.prototype.toLinearSpace = function () {
  1675. var convertedColor = new Color3();
  1676. this.toLinearSpaceToRef(convertedColor);
  1677. return convertedColor;
  1678. };
  1679. /**
  1680. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1681. * @param convertedColor defines the Color3 object where to store the linear space version
  1682. * @returns the unmodified Color3
  1683. */
  1684. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1685. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1686. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1687. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1688. return this;
  1689. };
  1690. /**
  1691. * Computes a new Color3 converted from the current one to gamma space
  1692. * @returns a new Color3 object
  1693. */
  1694. Color3.prototype.toGammaSpace = function () {
  1695. var convertedColor = new Color3();
  1696. this.toGammaSpaceToRef(convertedColor);
  1697. return convertedColor;
  1698. };
  1699. /**
  1700. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1701. * @param convertedColor defines the Color3 object where to store the gamma space version
  1702. * @returns the unmodified Color3
  1703. */
  1704. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1705. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1706. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1707. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1708. return this;
  1709. };
  1710. // Statics
  1711. /**
  1712. * Creates a new Color3 from the string containing valid hexadecimal values
  1713. * @param hex defines a string containing valid hexadecimal values
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromHexString = function (hex) {
  1717. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1718. return new Color3(0, 0, 0);
  1719. }
  1720. var r = parseInt(hex.substring(1, 3), 16);
  1721. var g = parseInt(hex.substring(3, 5), 16);
  1722. var b = parseInt(hex.substring(5, 7), 16);
  1723. return Color3.FromInts(r, g, b);
  1724. };
  1725. /**
  1726. * Creates a new Vector3 from the starting index of the given array
  1727. * @param array defines the source array
  1728. * @param offset defines an offset in the source array
  1729. * @returns a new Color3 object
  1730. */
  1731. Color3.FromArray = function (array, offset) {
  1732. if (offset === void 0) { offset = 0; }
  1733. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1734. };
  1735. /**
  1736. * Creates a new Color3 from integer values (< 256)
  1737. * @param r defines the red component to read from (value between 0 and 255)
  1738. * @param g defines the green component to read from (value between 0 and 255)
  1739. * @param b defines the blue component to read from (value between 0 and 255)
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.FromInts = function (r, g, b) {
  1743. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1744. };
  1745. /**
  1746. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1747. * @param start defines the start Color3 value
  1748. * @param end defines the end Color3 value
  1749. * @param amount defines the gradient value between start and end
  1750. * @returns a new Color3 object
  1751. */
  1752. Color3.Lerp = function (start, end, amount) {
  1753. var result = new Color3(0.0, 0.0, 0.0);
  1754. Color3.LerpToRef(start, end, amount, result);
  1755. return result;
  1756. };
  1757. /**
  1758. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1759. * @param left defines the start value
  1760. * @param right defines the end value
  1761. * @param amount defines the gradient factor
  1762. * @param result defines the Color3 object where to store the result
  1763. */
  1764. Color3.LerpToRef = function (left, right, amount, result) {
  1765. result.r = left.r + ((right.r - left.r) * amount);
  1766. result.g = left.g + ((right.g - left.g) * amount);
  1767. result.b = left.b + ((right.b - left.b) * amount);
  1768. };
  1769. /**
  1770. * Returns a Color3 value containing a red color
  1771. * @returns a new Color3 object
  1772. */
  1773. Color3.Red = function () { return new Color3(1, 0, 0); };
  1774. /**
  1775. * Returns a Color3 value containing a green color
  1776. * @returns a new Color3 object
  1777. */
  1778. Color3.Green = function () { return new Color3(0, 1, 0); };
  1779. /**
  1780. * Returns a Color3 value containing a blue color
  1781. * @returns a new Color3 object
  1782. */
  1783. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1784. /**
  1785. * Returns a Color3 value containing a black color
  1786. * @returns a new Color3 object
  1787. */
  1788. Color3.Black = function () { return new Color3(0, 0, 0); };
  1789. /**
  1790. * Returns a Color3 value containing a white color
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.White = function () { return new Color3(1, 1, 1); };
  1794. /**
  1795. * Returns a Color3 value containing a purple color
  1796. * @returns a new Color3 object
  1797. */
  1798. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1799. /**
  1800. * Returns a Color3 value containing a magenta color
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1804. /**
  1805. * Returns a Color3 value containing a yellow color
  1806. * @returns a new Color3 object
  1807. */
  1808. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1809. /**
  1810. * Returns a Color3 value containing a gray color
  1811. * @returns a new Color3 object
  1812. */
  1813. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1814. /**
  1815. * Returns a Color3 value containing a teal color
  1816. * @returns a new Color3 object
  1817. */
  1818. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1819. /**
  1820. * Returns a Color3 value containing a random color
  1821. * @returns a new Color3 object
  1822. */
  1823. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1824. return Color3;
  1825. }());
  1826. BABYLON.Color3 = Color3;
  1827. /**
  1828. * Class used to hold a RBGA color
  1829. */
  1830. var Color4 = /** @class */ (function () {
  1831. /**
  1832. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1833. * @param r defines the red component (between 0 and 1, default is 0)
  1834. * @param g defines the green component (between 0 and 1, default is 0)
  1835. * @param b defines the blue component (between 0 and 1, default is 0)
  1836. * @param a defines the alpha component (between 0 and 1, default is 1)
  1837. */
  1838. function Color4(
  1839. /**
  1840. * Defines the red component (between 0 and 1, default is 0)
  1841. */
  1842. r,
  1843. /**
  1844. * Defines the green component (between 0 and 1, default is 0)
  1845. */
  1846. g,
  1847. /**
  1848. * Defines the blue component (between 0 and 1, default is 0)
  1849. */
  1850. b,
  1851. /**
  1852. * Defines the alpha component (between 0 and 1, default is 1)
  1853. */
  1854. a) {
  1855. if (r === void 0) { r = 0; }
  1856. if (g === void 0) { g = 0; }
  1857. if (b === void 0) { b = 0; }
  1858. if (a === void 0) { a = 1; }
  1859. this.r = r;
  1860. this.g = g;
  1861. this.b = b;
  1862. this.a = a;
  1863. }
  1864. // Operators
  1865. /**
  1866. * Adds in place the given Color4 values to the current Color4 object
  1867. * @param right defines the second operand
  1868. * @returns the current updated Color4 object
  1869. */
  1870. Color4.prototype.addInPlace = function (right) {
  1871. this.r += right.r;
  1872. this.g += right.g;
  1873. this.b += right.b;
  1874. this.a += right.a;
  1875. return this;
  1876. };
  1877. /**
  1878. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1879. * @returns the new array
  1880. */
  1881. Color4.prototype.asArray = function () {
  1882. var result = new Array();
  1883. this.toArray(result, 0);
  1884. return result;
  1885. };
  1886. /**
  1887. * Stores from the starting index in the given array the Color4 successive values
  1888. * @param array defines the array where to store the r,g,b components
  1889. * @param index defines an optional index in the target array to define where to start storing values
  1890. * @returns the current Color4 object
  1891. */
  1892. Color4.prototype.toArray = function (array, index) {
  1893. if (index === undefined) {
  1894. index = 0;
  1895. }
  1896. array[index] = this.r;
  1897. array[index + 1] = this.g;
  1898. array[index + 2] = this.b;
  1899. array[index + 3] = this.a;
  1900. return this;
  1901. };
  1902. /**
  1903. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1904. * @param right defines the second operand
  1905. * @returns a new Color4 object
  1906. */
  1907. Color4.prototype.add = function (right) {
  1908. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1909. };
  1910. /**
  1911. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1912. * @param right defines the second operand
  1913. * @returns a new Color4 object
  1914. */
  1915. Color4.prototype.subtract = function (right) {
  1916. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1917. };
  1918. /**
  1919. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1920. * @param right defines the second operand
  1921. * @param result defines the Color4 object where to store the result
  1922. * @returns the current Color4 object
  1923. */
  1924. Color4.prototype.subtractToRef = function (right, result) {
  1925. result.r = this.r - right.r;
  1926. result.g = this.g - right.g;
  1927. result.b = this.b - right.b;
  1928. result.a = this.a - right.a;
  1929. return this;
  1930. };
  1931. /**
  1932. * Creates a new Color4 with the current Color4 values multiplied by scale
  1933. * @param scale defines the scaling factor to apply
  1934. * @returns a new Color4 object
  1935. */
  1936. Color4.prototype.scale = function (scale) {
  1937. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1938. };
  1939. /**
  1940. * Multiplies the current Color4 values by scale and stores the result in "result"
  1941. * @param scale defines the scaling factor to apply
  1942. * @param result defines the Color4 object where to store the result
  1943. * @returns the current unmodified Color4
  1944. */
  1945. Color4.prototype.scaleToRef = function (scale, result) {
  1946. result.r = this.r * scale;
  1947. result.g = this.g * scale;
  1948. result.b = this.b * scale;
  1949. result.a = this.a * scale;
  1950. return this;
  1951. };
  1952. /**
  1953. * Scale the current Color4 values by a factor and add the result to a given Color4
  1954. * @param scale defines the scale factor
  1955. * @param result defines the Color4 object where to store the result
  1956. * @returns the unmodified current Color4
  1957. */
  1958. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1959. result.r += this.r * scale;
  1960. result.g += this.g * scale;
  1961. result.b += this.b * scale;
  1962. result.a += this.a * scale;
  1963. return this;
  1964. };
  1965. /**
  1966. * Clamps the rgb values by the min and max values and stores the result into "result"
  1967. * @param min defines minimum clamping value (default is 0)
  1968. * @param max defines maximum clamping value (default is 1)
  1969. * @param result defines color to store the result into.
  1970. * @returns the cuurent Color4
  1971. */
  1972. Color4.prototype.clampToRef = function (min, max, result) {
  1973. if (min === void 0) { min = 0; }
  1974. if (max === void 0) { max = 1; }
  1975. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1976. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1977. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1978. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1979. return this;
  1980. };
  1981. /**
  1982. * Multipy an Color4 value by another and return a new Color4 object
  1983. * @param color defines the Color4 value to multiply by
  1984. * @returns a new Color4 object
  1985. */
  1986. Color4.prototype.multiply = function (color) {
  1987. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1988. };
  1989. /**
  1990. * Multipy a Color4 value by another and push the result in a reference value
  1991. * @param color defines the Color4 value to multiply by
  1992. * @param result defines the Color4 to fill the result in
  1993. * @returns the result Color4
  1994. */
  1995. Color4.prototype.multiplyToRef = function (color, result) {
  1996. result.r = this.r * color.r;
  1997. result.g = this.g * color.g;
  1998. result.b = this.b * color.b;
  1999. result.a = this.a * color.a;
  2000. return result;
  2001. };
  2002. /**
  2003. * Creates a string with the Color4 current values
  2004. * @returns the string representation of the Color4 object
  2005. */
  2006. Color4.prototype.toString = function () {
  2007. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2008. };
  2009. /**
  2010. * Returns the string "Color4"
  2011. * @returns "Color4"
  2012. */
  2013. Color4.prototype.getClassName = function () {
  2014. return "Color4";
  2015. };
  2016. /**
  2017. * Compute the Color4 hash code
  2018. * @returns an unique number that can be used to hash Color4 objects
  2019. */
  2020. Color4.prototype.getHashCode = function () {
  2021. var hash = this.r || 0;
  2022. hash = (hash * 397) ^ (this.g || 0);
  2023. hash = (hash * 397) ^ (this.b || 0);
  2024. hash = (hash * 397) ^ (this.a || 0);
  2025. return hash;
  2026. };
  2027. /**
  2028. * Creates a new Color4 copied from the current one
  2029. * @returns a new Color4 object
  2030. */
  2031. Color4.prototype.clone = function () {
  2032. return new Color4(this.r, this.g, this.b, this.a);
  2033. };
  2034. /**
  2035. * Copies the given Color4 values into the current one
  2036. * @param source defines the source Color4 object
  2037. * @returns the current updated Color4 object
  2038. */
  2039. Color4.prototype.copyFrom = function (source) {
  2040. this.r = source.r;
  2041. this.g = source.g;
  2042. this.b = source.b;
  2043. this.a = source.a;
  2044. return this;
  2045. };
  2046. /**
  2047. * Copies the given float values into the current one
  2048. * @param r defines the red component to read from
  2049. * @param g defines the green component to read from
  2050. * @param b defines the blue component to read from
  2051. * @param a defines the alpha component to read from
  2052. * @returns the current updated Color4 object
  2053. */
  2054. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2055. this.r = r;
  2056. this.g = g;
  2057. this.b = b;
  2058. this.a = a;
  2059. return this;
  2060. };
  2061. /**
  2062. * Copies the given float values into the current one
  2063. * @param r defines the red component to read from
  2064. * @param g defines the green component to read from
  2065. * @param b defines the blue component to read from
  2066. * @param a defines the alpha component to read from
  2067. * @returns the current updated Color4 object
  2068. */
  2069. Color4.prototype.set = function (r, g, b, a) {
  2070. return this.copyFromFloats(r, g, b, a);
  2071. };
  2072. /**
  2073. * Compute the Color4 hexadecimal code as a string
  2074. * @returns a string containing the hexadecimal representation of the Color4 object
  2075. */
  2076. Color4.prototype.toHexString = function () {
  2077. var intR = (this.r * 255) | 0;
  2078. var intG = (this.g * 255) | 0;
  2079. var intB = (this.b * 255) | 0;
  2080. var intA = (this.a * 255) | 0;
  2081. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2082. };
  2083. /**
  2084. * Computes a new Color4 converted from the current one to linear space
  2085. * @returns a new Color4 object
  2086. */
  2087. Color4.prototype.toLinearSpace = function () {
  2088. var convertedColor = new Color4();
  2089. this.toLinearSpaceToRef(convertedColor);
  2090. return convertedColor;
  2091. };
  2092. /**
  2093. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2094. * @param convertedColor defines the Color4 object where to store the linear space version
  2095. * @returns the unmodified Color4
  2096. */
  2097. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2098. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2099. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2100. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2101. convertedColor.a = this.a;
  2102. return this;
  2103. };
  2104. /**
  2105. * Computes a new Color4 converted from the current one to gamma space
  2106. * @returns a new Color4 object
  2107. */
  2108. Color4.prototype.toGammaSpace = function () {
  2109. var convertedColor = new Color4();
  2110. this.toGammaSpaceToRef(convertedColor);
  2111. return convertedColor;
  2112. };
  2113. /**
  2114. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2115. * @param convertedColor defines the Color4 object where to store the gamma space version
  2116. * @returns the unmodified Color4
  2117. */
  2118. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2119. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2120. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2121. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2122. convertedColor.a = this.a;
  2123. return this;
  2124. };
  2125. // Statics
  2126. /**
  2127. * Creates a new Color4 from the string containing valid hexadecimal values
  2128. * @param hex defines a string containing valid hexadecimal values
  2129. * @returns a new Color4 object
  2130. */
  2131. Color4.FromHexString = function (hex) {
  2132. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2133. return new Color4(0.0, 0.0, 0.0, 0.0);
  2134. }
  2135. var r = parseInt(hex.substring(1, 3), 16);
  2136. var g = parseInt(hex.substring(3, 5), 16);
  2137. var b = parseInt(hex.substring(5, 7), 16);
  2138. var a = parseInt(hex.substring(7, 9), 16);
  2139. return Color4.FromInts(r, g, b, a);
  2140. };
  2141. /**
  2142. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2143. * @param left defines the start value
  2144. * @param right defines the end value
  2145. * @param amount defines the gradient factor
  2146. * @returns a new Color4 object
  2147. */
  2148. Color4.Lerp = function (left, right, amount) {
  2149. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2150. Color4.LerpToRef(left, right, amount, result);
  2151. return result;
  2152. };
  2153. /**
  2154. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2155. * @param left defines the start value
  2156. * @param right defines the end value
  2157. * @param amount defines the gradient factor
  2158. * @param result defines the Color4 object where to store data
  2159. */
  2160. Color4.LerpToRef = function (left, right, amount, result) {
  2161. result.r = left.r + (right.r - left.r) * amount;
  2162. result.g = left.g + (right.g - left.g) * amount;
  2163. result.b = left.b + (right.b - left.b) * amount;
  2164. result.a = left.a + (right.a - left.a) * amount;
  2165. };
  2166. /**
  2167. * Creates a new Color4 from a Color3 and an alpha value
  2168. * @param color3 defines the source Color3 to read from
  2169. * @param alpha defines the alpha component (1.0 by default)
  2170. * @returns a new Color4 object
  2171. */
  2172. Color4.FromColor3 = function (color3, alpha) {
  2173. if (alpha === void 0) { alpha = 1.0; }
  2174. return new Color4(color3.r, color3.g, color3.b, alpha);
  2175. };
  2176. /**
  2177. * Creates a new Color4 from the starting index element of the given array
  2178. * @param array defines the source array to read from
  2179. * @param offset defines the offset in the source array
  2180. * @returns a new Color4 object
  2181. */
  2182. Color4.FromArray = function (array, offset) {
  2183. if (offset === void 0) { offset = 0; }
  2184. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2185. };
  2186. /**
  2187. * Creates a new Color3 from integer values (< 256)
  2188. * @param r defines the red component to read from (value between 0 and 255)
  2189. * @param g defines the green component to read from (value between 0 and 255)
  2190. * @param b defines the blue component to read from (value between 0 and 255)
  2191. * @param a defines the alpha component to read from (value between 0 and 255)
  2192. * @returns a new Color3 object
  2193. */
  2194. Color4.FromInts = function (r, g, b, a) {
  2195. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2196. };
  2197. /**
  2198. * Check the content of a given array and convert it to an array containing RGBA data
  2199. * If the original array was already containing count * 4 values then it is returned directly
  2200. * @param colors defines the array to check
  2201. * @param count defines the number of RGBA data to expect
  2202. * @returns an array containing count * 4 values (RGBA)
  2203. */
  2204. Color4.CheckColors4 = function (colors, count) {
  2205. // Check if color3 was used
  2206. if (colors.length === count * 3) {
  2207. var colors4 = [];
  2208. for (var index = 0; index < colors.length; index += 3) {
  2209. var newIndex = (index / 3) * 4;
  2210. colors4[newIndex] = colors[index];
  2211. colors4[newIndex + 1] = colors[index + 1];
  2212. colors4[newIndex + 2] = colors[index + 2];
  2213. colors4[newIndex + 3] = 1.0;
  2214. }
  2215. return colors4;
  2216. }
  2217. return colors;
  2218. };
  2219. return Color4;
  2220. }());
  2221. BABYLON.Color4 = Color4;
  2222. /**
  2223. * Class representing a vector containing 2 coordinates
  2224. */
  2225. var Vector2 = /** @class */ (function () {
  2226. /**
  2227. * Creates a new Vector2 from the given x and y coordinates
  2228. * @param x defines the first coordinate
  2229. * @param y defines the second coordinate
  2230. */
  2231. function Vector2(
  2232. /** defines the first coordinate */
  2233. x,
  2234. /** defines the second coordinate */
  2235. y) {
  2236. if (x === void 0) { x = 0; }
  2237. if (y === void 0) { y = 0; }
  2238. this.x = x;
  2239. this.y = y;
  2240. }
  2241. /**
  2242. * Gets a string with the Vector2 coordinates
  2243. * @returns a string with the Vector2 coordinates
  2244. */
  2245. Vector2.prototype.toString = function () {
  2246. return "{X: " + this.x + " Y:" + this.y + "}";
  2247. };
  2248. /**
  2249. * Gets class name
  2250. * @returns the string "Vector2"
  2251. */
  2252. Vector2.prototype.getClassName = function () {
  2253. return "Vector2";
  2254. };
  2255. /**
  2256. * Gets current vector hash code
  2257. * @returns the Vector2 hash code as a number
  2258. */
  2259. Vector2.prototype.getHashCode = function () {
  2260. var hash = this.x || 0;
  2261. hash = (hash * 397) ^ (this.y || 0);
  2262. return hash;
  2263. };
  2264. // Operators
  2265. /**
  2266. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2267. * @param array defines the source array
  2268. * @param index defines the offset in source array
  2269. * @returns the current Vector2
  2270. */
  2271. Vector2.prototype.toArray = function (array, index) {
  2272. if (index === void 0) { index = 0; }
  2273. array[index] = this.x;
  2274. array[index + 1] = this.y;
  2275. return this;
  2276. };
  2277. /**
  2278. * Copy the current vector to an array
  2279. * @returns a new array with 2 elements: the Vector2 coordinates.
  2280. */
  2281. Vector2.prototype.asArray = function () {
  2282. var result = new Array();
  2283. this.toArray(result, 0);
  2284. return result;
  2285. };
  2286. /**
  2287. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2288. * @param source defines the source Vector2
  2289. * @returns the current updated Vector2
  2290. */
  2291. Vector2.prototype.copyFrom = function (source) {
  2292. this.x = source.x;
  2293. this.y = source.y;
  2294. return this;
  2295. };
  2296. /**
  2297. * Sets the Vector2 coordinates with the given floats
  2298. * @param x defines the first coordinate
  2299. * @param y defines the second coordinate
  2300. * @returns the current updated Vector2
  2301. */
  2302. Vector2.prototype.copyFromFloats = function (x, y) {
  2303. this.x = x;
  2304. this.y = y;
  2305. return this;
  2306. };
  2307. /**
  2308. * Sets the Vector2 coordinates with the given floats
  2309. * @param x defines the first coordinate
  2310. * @param y defines the second coordinate
  2311. * @returns the current updated Vector2
  2312. */
  2313. Vector2.prototype.set = function (x, y) {
  2314. return this.copyFromFloats(x, y);
  2315. };
  2316. /**
  2317. * Add another vector with the current one
  2318. * @param otherVector defines the other vector
  2319. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2320. */
  2321. Vector2.prototype.add = function (otherVector) {
  2322. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2323. };
  2324. /**
  2325. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2326. * @param otherVector defines the other vector
  2327. * @param result defines the target vector
  2328. * @returns the unmodified current Vector2
  2329. */
  2330. Vector2.prototype.addToRef = function (otherVector, result) {
  2331. result.x = this.x + otherVector.x;
  2332. result.y = this.y + otherVector.y;
  2333. return this;
  2334. };
  2335. /**
  2336. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2337. * @param otherVector defines the other vector
  2338. * @returns the current updated Vector2
  2339. */
  2340. Vector2.prototype.addInPlace = function (otherVector) {
  2341. this.x += otherVector.x;
  2342. this.y += otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2347. * @param otherVector defines the other vector
  2348. * @returns a new Vector2
  2349. */
  2350. Vector2.prototype.addVector3 = function (otherVector) {
  2351. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2352. };
  2353. /**
  2354. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2355. * @param otherVector defines the other vector
  2356. * @returns a new Vector2
  2357. */
  2358. Vector2.prototype.subtract = function (otherVector) {
  2359. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2360. };
  2361. /**
  2362. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2363. * @param otherVector defines the other vector
  2364. * @param result defines the target vector
  2365. * @returns the unmodified current Vector2
  2366. */
  2367. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2368. result.x = this.x - otherVector.x;
  2369. result.y = this.y - otherVector.y;
  2370. return this;
  2371. };
  2372. /**
  2373. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2374. * @param otherVector defines the other vector
  2375. * @returns the current updated Vector2
  2376. */
  2377. Vector2.prototype.subtractInPlace = function (otherVector) {
  2378. this.x -= otherVector.x;
  2379. this.y -= otherVector.y;
  2380. return this;
  2381. };
  2382. /**
  2383. * Multiplies in place the current Vector2 coordinates by the given ones
  2384. * @param otherVector defines the other vector
  2385. * @returns the current updated Vector2
  2386. */
  2387. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2388. this.x *= otherVector.x;
  2389. this.y *= otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2394. * @param otherVector defines the other vector
  2395. * @returns a new Vector2
  2396. */
  2397. Vector2.prototype.multiply = function (otherVector) {
  2398. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2399. };
  2400. /**
  2401. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2402. * @param otherVector defines the other vector
  2403. * @param result defines the target vector
  2404. * @returns the unmodified current Vector2
  2405. */
  2406. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2407. result.x = this.x * otherVector.x;
  2408. result.y = this.y * otherVector.y;
  2409. return this;
  2410. };
  2411. /**
  2412. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2413. * @param x defines the first coordinate
  2414. * @param y defines the second coordinate
  2415. * @returns a new Vector2
  2416. */
  2417. Vector2.prototype.multiplyByFloats = function (x, y) {
  2418. return new Vector2(this.x * x, this.y * y);
  2419. };
  2420. /**
  2421. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2422. * @param otherVector defines the other vector
  2423. * @returns a new Vector2
  2424. */
  2425. Vector2.prototype.divide = function (otherVector) {
  2426. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2427. };
  2428. /**
  2429. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2430. * @param otherVector defines the other vector
  2431. * @param result defines the target vector
  2432. * @returns the unmodified current Vector2
  2433. */
  2434. Vector2.prototype.divideToRef = function (otherVector, result) {
  2435. result.x = this.x / otherVector.x;
  2436. result.y = this.y / otherVector.y;
  2437. return this;
  2438. };
  2439. /**
  2440. * Divides the current Vector2 coordinates by the given ones
  2441. * @param otherVector defines the other vector
  2442. * @returns the current updated Vector2
  2443. */
  2444. Vector2.prototype.divideInPlace = function (otherVector) {
  2445. return this.divideToRef(otherVector, this);
  2446. };
  2447. /**
  2448. * Gets a new Vector2 with current Vector2 negated coordinates
  2449. * @returns a new Vector2
  2450. */
  2451. Vector2.prototype.negate = function () {
  2452. return new Vector2(-this.x, -this.y);
  2453. };
  2454. /**
  2455. * Multiply the Vector2 coordinates by scale
  2456. * @param scale defines the scaling factor
  2457. * @returns the current updated Vector2
  2458. */
  2459. Vector2.prototype.scaleInPlace = function (scale) {
  2460. this.x *= scale;
  2461. this.y *= scale;
  2462. return this;
  2463. };
  2464. /**
  2465. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2466. * @param scale defines the scaling factor
  2467. * @returns a new Vector2
  2468. */
  2469. Vector2.prototype.scale = function (scale) {
  2470. var result = new Vector2(0, 0);
  2471. this.scaleToRef(scale, result);
  2472. return result;
  2473. };
  2474. /**
  2475. * Scale the current Vector2 values by a factor to a given Vector2
  2476. * @param scale defines the scale factor
  2477. * @param result defines the Vector2 object where to store the result
  2478. * @returns the unmodified current Vector2
  2479. */
  2480. Vector2.prototype.scaleToRef = function (scale, result) {
  2481. result.x = this.x * scale;
  2482. result.y = this.y * scale;
  2483. return this;
  2484. };
  2485. /**
  2486. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2487. * @param scale defines the scale factor
  2488. * @param result defines the Vector2 object where to store the result
  2489. * @returns the unmodified current Vector2
  2490. */
  2491. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2492. result.x += this.x * scale;
  2493. result.y += this.y * scale;
  2494. return this;
  2495. };
  2496. /**
  2497. * Gets a boolean if two vectors are equals
  2498. * @param otherVector defines the other vector
  2499. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2500. */
  2501. Vector2.prototype.equals = function (otherVector) {
  2502. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2503. };
  2504. /**
  2505. * Gets a boolean if two vectors are equals (using an epsilon value)
  2506. * @param otherVector defines the other vector
  2507. * @param epsilon defines the minimal distance to consider equality
  2508. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2509. */
  2510. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2511. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2512. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2513. };
  2514. /**
  2515. * Gets a new Vector2 from current Vector2 floored values
  2516. * @returns a new Vector2
  2517. */
  2518. Vector2.prototype.floor = function () {
  2519. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2520. };
  2521. /**
  2522. * Gets a new Vector2 from current Vector2 floored values
  2523. * @returns a new Vector2
  2524. */
  2525. Vector2.prototype.fract = function () {
  2526. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2527. };
  2528. // Properties
  2529. /**
  2530. * Gets the length of the vector
  2531. * @returns the vector length (float)
  2532. */
  2533. Vector2.prototype.length = function () {
  2534. return Math.sqrt(this.x * this.x + this.y * this.y);
  2535. };
  2536. /**
  2537. * Gets the vector squared length
  2538. * @returns the vector squared length (float)
  2539. */
  2540. Vector2.prototype.lengthSquared = function () {
  2541. return (this.x * this.x + this.y * this.y);
  2542. };
  2543. // Methods
  2544. /**
  2545. * Normalize the vector
  2546. * @returns the current updated Vector2
  2547. */
  2548. Vector2.prototype.normalize = function () {
  2549. var len = this.length();
  2550. if (len === 0)
  2551. return this;
  2552. var num = 1.0 / len;
  2553. this.x *= num;
  2554. this.y *= num;
  2555. return this;
  2556. };
  2557. /**
  2558. * Gets a new Vector2 copied from the Vector2
  2559. * @returns a new Vector2
  2560. */
  2561. Vector2.prototype.clone = function () {
  2562. return new Vector2(this.x, this.y);
  2563. };
  2564. // Statics
  2565. /**
  2566. * Gets a new Vector2(0, 0)
  2567. * @returns a new Vector2
  2568. */
  2569. Vector2.Zero = function () {
  2570. return new Vector2(0, 0);
  2571. };
  2572. /**
  2573. * Gets a new Vector2(1, 1)
  2574. * @returns a new Vector2
  2575. */
  2576. Vector2.One = function () {
  2577. return new Vector2(1, 1);
  2578. };
  2579. /**
  2580. * Gets a new Vector2 set from the given index element of the given array
  2581. * @param array defines the data source
  2582. * @param offset defines the offset in the data source
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.FromArray = function (array, offset) {
  2586. if (offset === void 0) { offset = 0; }
  2587. return new Vector2(array[offset], array[offset + 1]);
  2588. };
  2589. /**
  2590. * Sets "result" from the given index element of the given array
  2591. * @param array defines the data source
  2592. * @param offset defines the offset in the data source
  2593. * @param result defines the target vector
  2594. */
  2595. Vector2.FromArrayToRef = function (array, offset, result) {
  2596. result.x = array[offset];
  2597. result.y = array[offset + 1];
  2598. };
  2599. /**
  2600. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2601. * @param value1 defines 1st point of control
  2602. * @param value2 defines 2nd point of control
  2603. * @param value3 defines 3rd point of control
  2604. * @param value4 defines 4th point of control
  2605. * @param amount defines the interpolation factor
  2606. * @returns a new Vector2
  2607. */
  2608. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2609. var squared = amount * amount;
  2610. var cubed = amount * squared;
  2611. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2612. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2613. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2614. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2615. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2616. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2617. return new Vector2(x, y);
  2618. };
  2619. /**
  2620. * 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".
  2621. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2622. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2623. * @param value defines the value to clamp
  2624. * @param min defines the lower limit
  2625. * @param max defines the upper limit
  2626. * @returns a new Vector2
  2627. */
  2628. Vector2.Clamp = function (value, min, max) {
  2629. var x = value.x;
  2630. x = (x > max.x) ? max.x : x;
  2631. x = (x < min.x) ? min.x : x;
  2632. var y = value.y;
  2633. y = (y > max.y) ? max.y : y;
  2634. y = (y < min.y) ? min.y : y;
  2635. return new Vector2(x, y);
  2636. };
  2637. /**
  2638. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2639. * @param value1 defines the 1st control point
  2640. * @param tangent1 defines the outgoing tangent
  2641. * @param value2 defines the 2nd control point
  2642. * @param tangent2 defines the incoming tangent
  2643. * @param amount defines the interpolation factor
  2644. * @returns a new Vector2
  2645. */
  2646. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2647. var squared = amount * amount;
  2648. var cubed = amount * squared;
  2649. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2650. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2651. var part3 = (cubed - (2.0 * squared)) + amount;
  2652. var part4 = cubed - squared;
  2653. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2654. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2655. return new Vector2(x, y);
  2656. };
  2657. /**
  2658. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2659. * @param start defines the start vector
  2660. * @param end defines the end vector
  2661. * @param amount defines the interpolation factor
  2662. * @returns a new Vector2
  2663. */
  2664. Vector2.Lerp = function (start, end, amount) {
  2665. var x = start.x + ((end.x - start.x) * amount);
  2666. var y = start.y + ((end.y - start.y) * amount);
  2667. return new Vector2(x, y);
  2668. };
  2669. /**
  2670. * Gets the dot product of the vector "left" and the vector "right"
  2671. * @param left defines first vector
  2672. * @param right defines second vector
  2673. * @returns the dot product (float)
  2674. */
  2675. Vector2.Dot = function (left, right) {
  2676. return left.x * right.x + left.y * right.y;
  2677. };
  2678. /**
  2679. * Returns a new Vector2 equal to the normalized given vector
  2680. * @param vector defines the vector to normalize
  2681. * @returns a new Vector2
  2682. */
  2683. Vector2.Normalize = function (vector) {
  2684. var newVector = vector.clone();
  2685. newVector.normalize();
  2686. return newVector;
  2687. };
  2688. /**
  2689. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2690. * @param left defines 1st vector
  2691. * @param right defines 2nd vector
  2692. * @returns a new Vector2
  2693. */
  2694. Vector2.Minimize = function (left, right) {
  2695. var x = (left.x < right.x) ? left.x : right.x;
  2696. var y = (left.y < right.y) ? left.y : right.y;
  2697. return new Vector2(x, y);
  2698. };
  2699. /**
  2700. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2701. * @param left defines 1st vector
  2702. * @param right defines 2nd vector
  2703. * @returns a new Vector2
  2704. */
  2705. Vector2.Maximize = function (left, right) {
  2706. var x = (left.x > right.x) ? left.x : right.x;
  2707. var y = (left.y > right.y) ? left.y : right.y;
  2708. return new Vector2(x, y);
  2709. };
  2710. /**
  2711. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2712. * @param vector defines the vector to transform
  2713. * @param transformation defines the matrix to apply
  2714. * @returns a new Vector2
  2715. */
  2716. Vector2.Transform = function (vector, transformation) {
  2717. var r = Vector2.Zero();
  2718. Vector2.TransformToRef(vector, transformation, r);
  2719. return r;
  2720. };
  2721. /**
  2722. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2723. * @param vector defines the vector to transform
  2724. * @param transformation defines the matrix to apply
  2725. * @param result defines the target vector
  2726. */
  2727. Vector2.TransformToRef = function (vector, transformation, result) {
  2728. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2729. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2730. result.x = x;
  2731. result.y = y;
  2732. };
  2733. /**
  2734. * Determines if a given vector is included in a triangle
  2735. * @param p defines the vector to test
  2736. * @param p0 defines 1st triangle point
  2737. * @param p1 defines 2nd triangle point
  2738. * @param p2 defines 3rd triangle point
  2739. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2740. */
  2741. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2742. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2743. var sign = a < 0 ? -1 : 1;
  2744. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2745. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2746. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2747. };
  2748. /**
  2749. * Gets the distance between the vectors "value1" and "value2"
  2750. * @param value1 defines first vector
  2751. * @param value2 defines second vector
  2752. * @returns the distance between vectors
  2753. */
  2754. Vector2.Distance = function (value1, value2) {
  2755. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2756. };
  2757. /**
  2758. * Returns the squared distance between the vectors "value1" and "value2"
  2759. * @param value1 defines first vector
  2760. * @param value2 defines second vector
  2761. * @returns the squared distance between vectors
  2762. */
  2763. Vector2.DistanceSquared = function (value1, value2) {
  2764. var x = value1.x - value2.x;
  2765. var y = value1.y - value2.y;
  2766. return (x * x) + (y * y);
  2767. };
  2768. /**
  2769. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2770. * @param value1 defines first vector
  2771. * @param value2 defines second vector
  2772. * @returns a new Vector2
  2773. */
  2774. Vector2.Center = function (value1, value2) {
  2775. var center = value1.add(value2);
  2776. center.scaleInPlace(0.5);
  2777. return center;
  2778. };
  2779. /**
  2780. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2781. * @param p defines the middle point
  2782. * @param segA defines one point of the segment
  2783. * @param segB defines the other point of the segment
  2784. * @returns the shortest distance
  2785. */
  2786. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2787. var l2 = Vector2.DistanceSquared(segA, segB);
  2788. if (l2 === 0.0) {
  2789. return Vector2.Distance(p, segA);
  2790. }
  2791. var v = segB.subtract(segA);
  2792. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2793. var proj = segA.add(v.multiplyByFloats(t, t));
  2794. return Vector2.Distance(p, proj);
  2795. };
  2796. return Vector2;
  2797. }());
  2798. BABYLON.Vector2 = Vector2;
  2799. /**
  2800. * Classed used to store (x,y,z) vector representation
  2801. * A Vector3 is the main object used in 3D geometry
  2802. * It can represent etiher the coordinates of a point the space, either a direction
  2803. * Reminder: Babylon.js uses a left handed forward facing system
  2804. */
  2805. var Vector3 = /** @class */ (function () {
  2806. /**
  2807. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2808. * @param x defines the first coordinates (on X axis)
  2809. * @param y defines the second coordinates (on Y axis)
  2810. * @param z defines the third coordinates (on Z axis)
  2811. */
  2812. function Vector3(
  2813. /**
  2814. * Defines the first coordinates (on X axis)
  2815. */
  2816. x,
  2817. /**
  2818. * Defines the second coordinates (on Y axis)
  2819. */
  2820. y,
  2821. /**
  2822. * Defines the third coordinates (on Z axis)
  2823. */
  2824. z) {
  2825. if (x === void 0) { x = 0; }
  2826. if (y === void 0) { y = 0; }
  2827. if (z === void 0) { z = 0; }
  2828. this.x = x;
  2829. this.y = y;
  2830. this.z = z;
  2831. }
  2832. /**
  2833. * Creates a string representation of the Vector3
  2834. * @returns a string with the Vector3 coordinates.
  2835. */
  2836. Vector3.prototype.toString = function () {
  2837. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2838. };
  2839. /**
  2840. * Gets the class name
  2841. * @returns the string "Vector3"
  2842. */
  2843. Vector3.prototype.getClassName = function () {
  2844. return "Vector3";
  2845. };
  2846. /**
  2847. * Creates the Vector3 hash code
  2848. * @returns a number which tends to be unique between Vector3 instances
  2849. */
  2850. Vector3.prototype.getHashCode = function () {
  2851. var hash = this.x || 0;
  2852. hash = (hash * 397) ^ (this.y || 0);
  2853. hash = (hash * 397) ^ (this.z || 0);
  2854. return hash;
  2855. };
  2856. // Operators
  2857. /**
  2858. * Creates an array containing three elements : the coordinates of the Vector3
  2859. * @returns a new array of numbers
  2860. */
  2861. Vector3.prototype.asArray = function () {
  2862. var result = [];
  2863. this.toArray(result, 0);
  2864. return result;
  2865. };
  2866. /**
  2867. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2868. * @param array defines the destination array
  2869. * @param index defines the offset in the destination array
  2870. * @returns the current Vector3
  2871. */
  2872. Vector3.prototype.toArray = function (array, index) {
  2873. if (index === void 0) { index = 0; }
  2874. array[index] = this.x;
  2875. array[index + 1] = this.y;
  2876. array[index + 2] = this.z;
  2877. return this;
  2878. };
  2879. /**
  2880. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2881. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2882. */
  2883. Vector3.prototype.toQuaternion = function () {
  2884. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2885. };
  2886. /**
  2887. * Adds the given vector to the current Vector3
  2888. * @param otherVector defines the second operand
  2889. * @returns the current updated Vector3
  2890. */
  2891. Vector3.prototype.addInPlace = function (otherVector) {
  2892. this.x += otherVector.x;
  2893. this.y += otherVector.y;
  2894. this.z += otherVector.z;
  2895. return this;
  2896. };
  2897. /**
  2898. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2899. * @param otherVector defines the second operand
  2900. * @returns the resulting Vector3
  2901. */
  2902. Vector3.prototype.add = function (otherVector) {
  2903. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2904. };
  2905. /**
  2906. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2907. * @param otherVector defines the second operand
  2908. * @param result defines the Vector3 object where to store the result
  2909. * @returns the current Vector3
  2910. */
  2911. Vector3.prototype.addToRef = function (otherVector, result) {
  2912. result.x = this.x + otherVector.x;
  2913. result.y = this.y + otherVector.y;
  2914. result.z = this.z + otherVector.z;
  2915. return this;
  2916. };
  2917. /**
  2918. * Subtract the given vector from the current Vector3
  2919. * @param otherVector defines the second operand
  2920. * @returns the current updated Vector3
  2921. */
  2922. Vector3.prototype.subtractInPlace = function (otherVector) {
  2923. this.x -= otherVector.x;
  2924. this.y -= otherVector.y;
  2925. this.z -= otherVector.z;
  2926. return this;
  2927. };
  2928. /**
  2929. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2930. * @param otherVector defines the second operand
  2931. * @returns the resulting Vector3
  2932. */
  2933. Vector3.prototype.subtract = function (otherVector) {
  2934. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2935. };
  2936. /**
  2937. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2938. * @param otherVector defines the second operand
  2939. * @param result defines the Vector3 object where to store the result
  2940. * @returns the current Vector3
  2941. */
  2942. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2943. result.x = this.x - otherVector.x;
  2944. result.y = this.y - otherVector.y;
  2945. result.z = this.z - otherVector.z;
  2946. return this;
  2947. };
  2948. /**
  2949. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2950. * @param x defines the x coordinate of the operand
  2951. * @param y defines the y coordinate of the operand
  2952. * @param z defines the z coordinate of the operand
  2953. * @returns the resulting Vector3
  2954. */
  2955. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2956. return new Vector3(this.x - x, this.y - y, this.z - z);
  2957. };
  2958. /**
  2959. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2960. * @param x defines the x coordinate of the operand
  2961. * @param y defines the y coordinate of the operand
  2962. * @param z defines the z coordinate of the operand
  2963. * @param result defines the Vector3 object where to store the result
  2964. * @returns the current Vector3
  2965. */
  2966. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2967. result.x = this.x - x;
  2968. result.y = this.y - y;
  2969. result.z = this.z - z;
  2970. return this;
  2971. };
  2972. /**
  2973. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2974. * @returns a new Vector3
  2975. */
  2976. Vector3.prototype.negate = function () {
  2977. return new Vector3(-this.x, -this.y, -this.z);
  2978. };
  2979. /**
  2980. * Multiplies the Vector3 coordinates by the float "scale"
  2981. * @param scale defines the multiplier factor
  2982. * @returns the current updated Vector3
  2983. */
  2984. Vector3.prototype.scaleInPlace = function (scale) {
  2985. this.x *= scale;
  2986. this.y *= scale;
  2987. this.z *= scale;
  2988. return this;
  2989. };
  2990. /**
  2991. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2992. * @param scale defines the multiplier factor
  2993. * @returns a new Vector3
  2994. */
  2995. Vector3.prototype.scale = function (scale) {
  2996. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2997. };
  2998. /**
  2999. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3000. * @param scale defines the multiplier factor
  3001. * @param result defines the Vector3 object where to store the result
  3002. * @returns the current Vector3
  3003. */
  3004. Vector3.prototype.scaleToRef = function (scale, result) {
  3005. result.x = this.x * scale;
  3006. result.y = this.y * scale;
  3007. result.z = this.z * scale;
  3008. return this;
  3009. };
  3010. /**
  3011. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3012. * @param scale defines the scale factor
  3013. * @param result defines the Vector3 object where to store the result
  3014. * @returns the unmodified current Vector3
  3015. */
  3016. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3017. result.x += this.x * scale;
  3018. result.y += this.y * scale;
  3019. result.z += this.z * scale;
  3020. return this;
  3021. };
  3022. /**
  3023. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3024. * @param otherVector defines the second operand
  3025. * @returns true if both vectors are equals
  3026. */
  3027. Vector3.prototype.equals = function (otherVector) {
  3028. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3029. };
  3030. /**
  3031. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3032. * @param otherVector defines the second operand
  3033. * @param epsilon defines the minimal distance to define values as equals
  3034. * @returns true if both vectors are distant less than epsilon
  3035. */
  3036. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3037. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3038. 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);
  3039. };
  3040. /**
  3041. * Returns true if the current Vector3 coordinates equals the given floats
  3042. * @param x defines the x coordinate of the operand
  3043. * @param y defines the y coordinate of the operand
  3044. * @param z defines the z coordinate of the operand
  3045. * @returns true if both vectors are equals
  3046. */
  3047. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3048. return this.x === x && this.y === y && this.z === z;
  3049. };
  3050. /**
  3051. * Multiplies the current Vector3 coordinates by the given ones
  3052. * @param otherVector defines the second operand
  3053. * @returns the current updated Vector3
  3054. */
  3055. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3056. this.x *= otherVector.x;
  3057. this.y *= otherVector.y;
  3058. this.z *= otherVector.z;
  3059. return this;
  3060. };
  3061. /**
  3062. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3063. * @param otherVector defines the second operand
  3064. * @returns the new Vector3
  3065. */
  3066. Vector3.prototype.multiply = function (otherVector) {
  3067. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3068. };
  3069. /**
  3070. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3071. * @param otherVector defines the second operand
  3072. * @param result defines the Vector3 object where to store the result
  3073. * @returns the current Vector3
  3074. */
  3075. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3076. result.x = this.x * otherVector.x;
  3077. result.y = this.y * otherVector.y;
  3078. result.z = this.z * otherVector.z;
  3079. return this;
  3080. };
  3081. /**
  3082. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3083. * @param x defines the x coordinate of the operand
  3084. * @param y defines the y coordinate of the operand
  3085. * @param z defines the z coordinate of the operand
  3086. * @returns the new Vector3
  3087. */
  3088. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3089. return new Vector3(this.x * x, this.y * y, this.z * z);
  3090. };
  3091. /**
  3092. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3093. * @param otherVector defines the second operand
  3094. * @returns the new Vector3
  3095. */
  3096. Vector3.prototype.divide = function (otherVector) {
  3097. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3098. };
  3099. /**
  3100. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3101. * @param otherVector defines the second operand
  3102. * @param result defines the Vector3 object where to store the result
  3103. * @returns the current Vector3
  3104. */
  3105. Vector3.prototype.divideToRef = function (otherVector, result) {
  3106. result.x = this.x / otherVector.x;
  3107. result.y = this.y / otherVector.y;
  3108. result.z = this.z / otherVector.z;
  3109. return this;
  3110. };
  3111. /**
  3112. * Divides the current Vector3 coordinates by the given ones.
  3113. * @param otherVector defines the second operand
  3114. * @returns the current updated Vector3
  3115. */
  3116. Vector3.prototype.divideInPlace = function (otherVector) {
  3117. return this.divideToRef(otherVector, this);
  3118. };
  3119. /**
  3120. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3121. * @param other defines the second operand
  3122. * @returns the current updated Vector3
  3123. */
  3124. Vector3.prototype.minimizeInPlace = function (other) {
  3125. if (other.x < this.x)
  3126. this.x = other.x;
  3127. if (other.y < this.y)
  3128. this.y = other.y;
  3129. if (other.z < this.z)
  3130. this.z = other.z;
  3131. return this;
  3132. };
  3133. /**
  3134. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3135. * @param other defines the second operand
  3136. * @returns the current updated Vector3
  3137. */
  3138. Vector3.prototype.maximizeInPlace = function (other) {
  3139. if (other.x > this.x)
  3140. this.x = other.x;
  3141. if (other.y > this.y)
  3142. this.y = other.y;
  3143. if (other.z > this.z)
  3144. this.z = other.z;
  3145. return this;
  3146. };
  3147. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3148. /**
  3149. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3150. */
  3151. get: function () {
  3152. var absX = Math.abs(this.x);
  3153. var absY = Math.abs(this.y);
  3154. if (absX !== absY) {
  3155. return true;
  3156. }
  3157. var absZ = Math.abs(this.z);
  3158. if (absX !== absZ) {
  3159. return true;
  3160. }
  3161. if (absY !== absZ) {
  3162. return true;
  3163. }
  3164. return false;
  3165. },
  3166. enumerable: true,
  3167. configurable: true
  3168. });
  3169. /**
  3170. * Gets a new Vector3 from current Vector3 floored values
  3171. * @returns a new Vector3
  3172. */
  3173. Vector3.prototype.floor = function () {
  3174. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3175. };
  3176. /**
  3177. * Gets a new Vector3 from current Vector3 floored values
  3178. * @returns a new Vector3
  3179. */
  3180. Vector3.prototype.fract = function () {
  3181. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3182. };
  3183. // Properties
  3184. /**
  3185. * Gets the length of the Vector3
  3186. * @returns the length of the Vecto3
  3187. */
  3188. Vector3.prototype.length = function () {
  3189. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3190. };
  3191. /**
  3192. * Gets the squared length of the Vector3
  3193. * @returns squared length of the Vector3
  3194. */
  3195. Vector3.prototype.lengthSquared = function () {
  3196. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3197. };
  3198. /**
  3199. * Normalize the current Vector3.
  3200. * Please note that this is an in place operation.
  3201. * @returns the current updated Vector3
  3202. */
  3203. Vector3.prototype.normalize = function () {
  3204. var len = this.length();
  3205. if (len === 0 || len === 1.0)
  3206. return this;
  3207. var num = 1.0 / len;
  3208. this.x *= num;
  3209. this.y *= num;
  3210. this.z *= num;
  3211. return this;
  3212. };
  3213. /**
  3214. * Normalize the current Vector3 to a new vector
  3215. * @returns the new Vector3
  3216. */
  3217. Vector3.prototype.normalizeToNew = function () {
  3218. var normalized = new Vector3(0, 0, 0);
  3219. this.normalizeToRef(normalized);
  3220. return normalized;
  3221. };
  3222. /**
  3223. * Normalize the current Vector3 to the reference
  3224. * @param reference define the Vector3 to update
  3225. * @returns the updated Vector3
  3226. */
  3227. Vector3.prototype.normalizeToRef = function (reference) {
  3228. var len = this.length();
  3229. if (len === 0 || len === 1.0) {
  3230. reference.set(this.x, this.y, this.z);
  3231. return reference;
  3232. }
  3233. var scale = 1.0 / len;
  3234. this.scaleToRef(scale, reference);
  3235. return reference;
  3236. };
  3237. /**
  3238. * Creates a new Vector3 copied from the current Vector3
  3239. * @returns the new Vector3
  3240. */
  3241. Vector3.prototype.clone = function () {
  3242. return new Vector3(this.x, this.y, this.z);
  3243. };
  3244. /**
  3245. * Copies the given vector coordinates to the current Vector3 ones
  3246. * @param source defines the source Vector3
  3247. * @returns the current updated Vector3
  3248. */
  3249. Vector3.prototype.copyFrom = function (source) {
  3250. this.x = source.x;
  3251. this.y = source.y;
  3252. this.z = source.z;
  3253. return this;
  3254. };
  3255. /**
  3256. * Copies the given floats to the current Vector3 coordinates
  3257. * @param x defines the x coordinate of the operand
  3258. * @param y defines the y coordinate of the operand
  3259. * @param z defines the z coordinate of the operand
  3260. * @returns the current updated Vector3
  3261. */
  3262. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3263. this.x = x;
  3264. this.y = y;
  3265. this.z = z;
  3266. return this;
  3267. };
  3268. /**
  3269. * Copies the given floats to the current Vector3 coordinates
  3270. * @param x defines the x coordinate of the operand
  3271. * @param y defines the y coordinate of the operand
  3272. * @param z defines the z coordinate of the operand
  3273. * @returns the current updated Vector3
  3274. */
  3275. Vector3.prototype.set = function (x, y, z) {
  3276. return this.copyFromFloats(x, y, z);
  3277. };
  3278. // Statics
  3279. /**
  3280. * Get the clip factor between two vectors
  3281. * @param vector0 defines the first operand
  3282. * @param vector1 defines the second operand
  3283. * @param axis defines the axis to use
  3284. * @param size defines the size along the axis
  3285. * @returns the clip factor
  3286. */
  3287. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3288. var d0 = Vector3.Dot(vector0, axis) - size;
  3289. var d1 = Vector3.Dot(vector1, axis) - size;
  3290. var s = d0 / (d0 - d1);
  3291. return s;
  3292. };
  3293. /**
  3294. * Get angle between two vectors
  3295. * @param vector0 angle between vector0 and vector1
  3296. * @param vector1 angle between vector0 and vector1
  3297. * @param normal direction of the normal
  3298. * @return the angle between vector0 and vector1
  3299. */
  3300. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3301. var v0 = vector0.clone().normalize();
  3302. var v1 = vector1.clone().normalize();
  3303. var dot = Vector3.Dot(v0, v1);
  3304. var n = Vector3.Cross(v0, v1);
  3305. if (Vector3.Dot(n, normal) > 0) {
  3306. return Math.acos(dot);
  3307. }
  3308. return -Math.acos(dot);
  3309. };
  3310. /**
  3311. * Returns a new Vector3 set from the index "offset" of the given array
  3312. * @param array defines the source array
  3313. * @param offset defines the offset in the source array
  3314. * @returns the new Vector3
  3315. */
  3316. Vector3.FromArray = function (array, offset) {
  3317. if (!offset) {
  3318. offset = 0;
  3319. }
  3320. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3321. };
  3322. /**
  3323. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3324. * This function is deprecated. Use FromArray instead
  3325. * @param array defines the source array
  3326. * @param offset defines the offset in the source array
  3327. * @returns the new Vector3
  3328. */
  3329. Vector3.FromFloatArray = function (array, offset) {
  3330. return Vector3.FromArray(array, offset);
  3331. };
  3332. /**
  3333. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3334. * @param array defines the source array
  3335. * @param offset defines the offset in the source array
  3336. * @param result defines the Vector3 where to store the result
  3337. */
  3338. Vector3.FromArrayToRef = function (array, offset, result) {
  3339. result.x = array[offset];
  3340. result.y = array[offset + 1];
  3341. result.z = array[offset + 2];
  3342. };
  3343. /**
  3344. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3345. * This function is deprecated. Use FromArrayToRef instead.
  3346. * @param array defines the source array
  3347. * @param offset defines the offset in the source array
  3348. * @param result defines the Vector3 where to store the result
  3349. */
  3350. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3351. return Vector3.FromArrayToRef(array, offset, result);
  3352. };
  3353. /**
  3354. * Sets the given vector "result" with the given floats.
  3355. * @param x defines the x coordinate of the source
  3356. * @param y defines the y coordinate of the source
  3357. * @param z defines the z coordinate of the source
  3358. * @param result defines the Vector3 where to store the result
  3359. */
  3360. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3361. result.x = x;
  3362. result.y = y;
  3363. result.z = z;
  3364. };
  3365. /**
  3366. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3367. * @returns a new empty Vector3
  3368. */
  3369. Vector3.Zero = function () {
  3370. return new Vector3(0.0, 0.0, 0.0);
  3371. };
  3372. /**
  3373. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3374. * @returns a new unit Vector3
  3375. */
  3376. Vector3.One = function () {
  3377. return new Vector3(1.0, 1.0, 1.0);
  3378. };
  3379. /**
  3380. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3381. * @returns a new up Vector3
  3382. */
  3383. Vector3.Up = function () {
  3384. return new Vector3(0.0, 1.0, 0.0);
  3385. };
  3386. /**
  3387. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3388. * @returns a new down Vector3
  3389. */
  3390. Vector3.Down = function () {
  3391. return new Vector3(0.0, -1.0, 0.0);
  3392. };
  3393. /**
  3394. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3395. * @returns a new forward Vector3
  3396. */
  3397. Vector3.Forward = function () {
  3398. return new Vector3(0.0, 0.0, 1.0);
  3399. };
  3400. /**
  3401. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3402. * @returns a new right Vector3
  3403. */
  3404. Vector3.Right = function () {
  3405. return new Vector3(1.0, 0.0, 0.0);
  3406. };
  3407. /**
  3408. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3409. * @returns a new left Vector3
  3410. */
  3411. Vector3.Left = function () {
  3412. return new Vector3(-1.0, 0.0, 0.0);
  3413. };
  3414. /**
  3415. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3416. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3417. * @param vector defines the Vector3 to transform
  3418. * @param transformation defines the transformation matrix
  3419. * @returns the transformed Vector3
  3420. */
  3421. Vector3.TransformCoordinates = function (vector, transformation) {
  3422. var result = Vector3.Zero();
  3423. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3424. return result;
  3425. };
  3426. /**
  3427. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3428. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3429. * @param vector defines the Vector3 to transform
  3430. * @param transformation defines the transformation matrix
  3431. * @param result defines the Vector3 where to store the result
  3432. */
  3433. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3434. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3435. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3436. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3437. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3438. result.x = x / w;
  3439. result.y = y / w;
  3440. result.z = z / w;
  3441. };
  3442. /**
  3443. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3444. * This method computes tranformed coordinates only, not transformed direction vectors
  3445. * @param x define the x coordinate of the source vector
  3446. * @param y define the y coordinate of the source vector
  3447. * @param z define the z coordinate of the source vector
  3448. * @param transformation defines the transformation matrix
  3449. * @param result defines the Vector3 where to store the result
  3450. */
  3451. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3452. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3453. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3454. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3455. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3456. result.x = rx / rw;
  3457. result.y = ry / rw;
  3458. result.z = rz / rw;
  3459. };
  3460. /**
  3461. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3462. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3463. * @param vector defines the Vector3 to transform
  3464. * @param transformation defines the transformation matrix
  3465. * @returns the new Vector3
  3466. */
  3467. Vector3.TransformNormal = function (vector, transformation) {
  3468. var result = Vector3.Zero();
  3469. Vector3.TransformNormalToRef(vector, transformation, result);
  3470. return result;
  3471. };
  3472. /**
  3473. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3474. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3475. * @param vector defines the Vector3 to transform
  3476. * @param transformation defines the transformation matrix
  3477. * @param result defines the Vector3 where to store the result
  3478. */
  3479. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3480. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3481. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3482. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3483. result.x = x;
  3484. result.y = y;
  3485. result.z = z;
  3486. };
  3487. /**
  3488. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3489. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3490. * @param x define the x coordinate of the source vector
  3491. * @param y define the y coordinate of the source vector
  3492. * @param z define the z coordinate of the source vector
  3493. * @param transformation defines the transformation matrix
  3494. * @param result defines the Vector3 where to store the result
  3495. */
  3496. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3497. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3498. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3499. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3500. };
  3501. /**
  3502. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3503. * @param value1 defines the first control point
  3504. * @param value2 defines the second control point
  3505. * @param value3 defines the third control point
  3506. * @param value4 defines the fourth control point
  3507. * @param amount defines the amount on the spline to use
  3508. * @returns the new Vector3
  3509. */
  3510. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3511. var squared = amount * amount;
  3512. var cubed = amount * squared;
  3513. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3514. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3515. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3516. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3517. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3518. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3519. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3520. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3521. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3522. return new Vector3(x, y, z);
  3523. };
  3524. /**
  3525. * 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"
  3526. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3527. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3528. * @param value defines the current value
  3529. * @param min defines the lower range value
  3530. * @param max defines the upper range value
  3531. * @returns the new Vector3
  3532. */
  3533. Vector3.Clamp = function (value, min, max) {
  3534. var x = value.x;
  3535. x = (x > max.x) ? max.x : x;
  3536. x = (x < min.x) ? min.x : x;
  3537. var y = value.y;
  3538. y = (y > max.y) ? max.y : y;
  3539. y = (y < min.y) ? min.y : y;
  3540. var z = value.z;
  3541. z = (z > max.z) ? max.z : z;
  3542. z = (z < min.z) ? min.z : z;
  3543. return new Vector3(x, y, z);
  3544. };
  3545. /**
  3546. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3547. * @param value1 defines the first control point
  3548. * @param tangent1 defines the first tangent vector
  3549. * @param value2 defines the second control point
  3550. * @param tangent2 defines the second tangent vector
  3551. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3552. * @returns the new Vector3
  3553. */
  3554. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3555. var squared = amount * amount;
  3556. var cubed = amount * squared;
  3557. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3558. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3559. var part3 = (cubed - (2.0 * squared)) + amount;
  3560. var part4 = cubed - squared;
  3561. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3562. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3563. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3564. return new Vector3(x, y, z);
  3565. };
  3566. /**
  3567. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3568. * @param start defines the start value
  3569. * @param end defines the end value
  3570. * @param amount max defines amount between both (between 0 and 1)
  3571. * @returns the new Vector3
  3572. */
  3573. Vector3.Lerp = function (start, end, amount) {
  3574. var result = new Vector3(0, 0, 0);
  3575. Vector3.LerpToRef(start, end, amount, result);
  3576. return result;
  3577. };
  3578. /**
  3579. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3580. * @param start defines the start value
  3581. * @param end defines the end value
  3582. * @param amount max defines amount between both (between 0 and 1)
  3583. * @param result defines the Vector3 where to store the result
  3584. */
  3585. Vector3.LerpToRef = function (start, end, amount, result) {
  3586. result.x = start.x + ((end.x - start.x) * amount);
  3587. result.y = start.y + ((end.y - start.y) * amount);
  3588. result.z = start.z + ((end.z - start.z) * amount);
  3589. };
  3590. /**
  3591. * Returns the dot product (float) between the vectors "left" and "right"
  3592. * @param left defines the left operand
  3593. * @param right defines the right operand
  3594. * @returns the dot product
  3595. */
  3596. Vector3.Dot = function (left, right) {
  3597. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3598. };
  3599. /**
  3600. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3601. * The cross product is then orthogonal to both "left" and "right"
  3602. * @param left defines the left operand
  3603. * @param right defines the right operand
  3604. * @returns the cross product
  3605. */
  3606. Vector3.Cross = function (left, right) {
  3607. var result = Vector3.Zero();
  3608. Vector3.CrossToRef(left, right, result);
  3609. return result;
  3610. };
  3611. /**
  3612. * Sets the given vector "result" with the cross product of "left" and "right"
  3613. * The cross product is then orthogonal to both "left" and "right"
  3614. * @param left defines the left operand
  3615. * @param right defines the right operand
  3616. * @param result defines the Vector3 where to store the result
  3617. */
  3618. Vector3.CrossToRef = function (left, right, result) {
  3619. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3620. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3621. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3622. result.copyFrom(MathTmp.Vector3[0]);
  3623. };
  3624. /**
  3625. * Returns a new Vector3 as the normalization of the given vector
  3626. * @param vector defines the Vector3 to normalize
  3627. * @returns the new Vector3
  3628. */
  3629. Vector3.Normalize = function (vector) {
  3630. var result = Vector3.Zero();
  3631. Vector3.NormalizeToRef(vector, result);
  3632. return result;
  3633. };
  3634. /**
  3635. * Sets the given vector "result" with the normalization of the given first vector
  3636. * @param vector defines the Vector3 to normalize
  3637. * @param result defines the Vector3 where to store the result
  3638. */
  3639. Vector3.NormalizeToRef = function (vector, result) {
  3640. result.copyFrom(vector);
  3641. result.normalize();
  3642. };
  3643. /**
  3644. * Project a Vector3 onto screen space
  3645. * @param vector defines the Vector3 to project
  3646. * @param world defines the world matrix to use
  3647. * @param transform defines the transform (view x projection) matrix to use
  3648. * @param viewport defines the screen viewport to use
  3649. * @returns the new Vector3
  3650. */
  3651. Vector3.Project = function (vector, world, transform, viewport) {
  3652. var cw = viewport.width;
  3653. var ch = viewport.height;
  3654. var cx = viewport.x;
  3655. var cy = viewport.y;
  3656. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3657. 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);
  3658. var matrix = MathTmp.Matrix[0];
  3659. world.multiplyToRef(transform, matrix);
  3660. matrix.multiplyToRef(viewportMatrix, matrix);
  3661. return Vector3.TransformCoordinates(vector, matrix);
  3662. };
  3663. /**
  3664. * Unproject from screen space to object space
  3665. * @param source defines the screen space Vector3 to use
  3666. * @param viewportWidth defines the current width of the viewport
  3667. * @param viewportHeight defines the current height of the viewport
  3668. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3669. * @param transform defines the transform (view x projection) matrix to use
  3670. * @returns the new Vector3
  3671. */
  3672. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3673. var matrix = MathTmp.Matrix[0];
  3674. world.multiplyToRef(transform, matrix);
  3675. matrix.invert();
  3676. source.x = source.x / viewportWidth * 2 - 1;
  3677. source.y = -(source.y / viewportHeight * 2 - 1);
  3678. var vector = Vector3.TransformCoordinates(source, matrix);
  3679. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3680. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3681. vector = vector.scale(1.0 / num);
  3682. }
  3683. return vector;
  3684. };
  3685. /**
  3686. * Unproject from screen space to object space
  3687. * @param source defines the screen space Vector3 to use
  3688. * @param viewportWidth defines the current width of the viewport
  3689. * @param viewportHeight defines the current height of the viewport
  3690. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3691. * @param view defines the view matrix to use
  3692. * @param projection defines the projection matrix to use
  3693. * @returns the new Vector3
  3694. */
  3695. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3696. var result = Vector3.Zero();
  3697. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3698. return result;
  3699. };
  3700. /**
  3701. * Unproject from screen space to object space
  3702. * @param source defines the screen space Vector3 to use
  3703. * @param viewportWidth defines the current width of the viewport
  3704. * @param viewportHeight defines the current height of the viewport
  3705. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3706. * @param view defines the view matrix to use
  3707. * @param projection defines the projection matrix to use
  3708. * @param result defines the Vector3 where to store the result
  3709. */
  3710. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3711. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3712. };
  3713. /**
  3714. * Unproject from screen space to object space
  3715. * @param sourceX defines the screen space x coordinate to use
  3716. * @param sourceY defines the screen space y coordinate to use
  3717. * @param sourceZ defines the screen space z coordinate to use
  3718. * @param viewportWidth defines the current width of the viewport
  3719. * @param viewportHeight defines the current height of the viewport
  3720. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3721. * @param view defines the view matrix to use
  3722. * @param projection defines the projection matrix to use
  3723. * @param result defines the Vector3 where to store the result
  3724. */
  3725. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3726. var matrix = MathTmp.Matrix[0];
  3727. world.multiplyToRef(view, matrix);
  3728. matrix.multiplyToRef(projection, matrix);
  3729. matrix.invert();
  3730. var screenSource = MathTmp.Vector3[0];
  3731. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3732. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3733. screenSource.z = 2 * sourceZ - 1.0;
  3734. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3735. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3736. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3737. result.scaleInPlace(1.0 / num);
  3738. }
  3739. };
  3740. /**
  3741. * Gets the minimal coordinate values between two Vector3
  3742. * @param left defines the first operand
  3743. * @param right defines the second operand
  3744. * @returns the new Vector3
  3745. */
  3746. Vector3.Minimize = function (left, right) {
  3747. var min = left.clone();
  3748. min.minimizeInPlace(right);
  3749. return min;
  3750. };
  3751. /**
  3752. * Gets the maximal coordinate values between two Vector3
  3753. * @param left defines the first operand
  3754. * @param right defines the second operand
  3755. * @returns the new Vector3
  3756. */
  3757. Vector3.Maximize = function (left, right) {
  3758. var max = left.clone();
  3759. max.maximizeInPlace(right);
  3760. return max;
  3761. };
  3762. /**
  3763. * Returns the distance between the vectors "value1" and "value2"
  3764. * @param value1 defines the first operand
  3765. * @param value2 defines the second operand
  3766. * @returns the distance
  3767. */
  3768. Vector3.Distance = function (value1, value2) {
  3769. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3770. };
  3771. /**
  3772. * Returns the squared distance between the vectors "value1" and "value2"
  3773. * @param value1 defines the first operand
  3774. * @param value2 defines the second operand
  3775. * @returns the squared distance
  3776. */
  3777. Vector3.DistanceSquared = function (value1, value2) {
  3778. var x = value1.x - value2.x;
  3779. var y = value1.y - value2.y;
  3780. var z = value1.z - value2.z;
  3781. return (x * x) + (y * y) + (z * z);
  3782. };
  3783. /**
  3784. * Returns a new Vector3 located at the center between "value1" and "value2"
  3785. * @param value1 defines the first operand
  3786. * @param value2 defines the second operand
  3787. * @returns the new Vector3
  3788. */
  3789. Vector3.Center = function (value1, value2) {
  3790. var center = value1.add(value2);
  3791. center.scaleInPlace(0.5);
  3792. return center;
  3793. };
  3794. /**
  3795. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3796. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3797. * to something in order to rotate it from its local system to the given target system
  3798. * Note: axis1, axis2 and axis3 are normalized during this operation
  3799. * @param axis1 defines the first axis
  3800. * @param axis2 defines the second axis
  3801. * @param axis3 defines the third axis
  3802. * @returns a new Vector3
  3803. */
  3804. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3805. var rotation = Vector3.Zero();
  3806. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3807. return rotation;
  3808. };
  3809. /**
  3810. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3811. * @param axis1 defines the first axis
  3812. * @param axis2 defines the second axis
  3813. * @param axis3 defines the third axis
  3814. * @param ref defines the Vector3 where to store the result
  3815. */
  3816. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3817. var quat = MathTmp.Quaternion[0];
  3818. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3819. quat.toEulerAnglesToRef(ref);
  3820. };
  3821. return Vector3;
  3822. }());
  3823. BABYLON.Vector3 = Vector3;
  3824. //Vector4 class created for EulerAngle class conversion to Quaternion
  3825. var Vector4 = /** @class */ (function () {
  3826. /**
  3827. * Creates a Vector4 object from the given floats.
  3828. */
  3829. function Vector4(x, y, z, w) {
  3830. this.x = x;
  3831. this.y = y;
  3832. this.z = z;
  3833. this.w = w;
  3834. }
  3835. /**
  3836. * Returns the string with the Vector4 coordinates.
  3837. */
  3838. Vector4.prototype.toString = function () {
  3839. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3840. };
  3841. /**
  3842. * Returns the string "Vector4".
  3843. */
  3844. Vector4.prototype.getClassName = function () {
  3845. return "Vector4";
  3846. };
  3847. /**
  3848. * Returns the Vector4 hash code.
  3849. */
  3850. Vector4.prototype.getHashCode = function () {
  3851. var hash = this.x || 0;
  3852. hash = (hash * 397) ^ (this.y || 0);
  3853. hash = (hash * 397) ^ (this.z || 0);
  3854. hash = (hash * 397) ^ (this.w || 0);
  3855. return hash;
  3856. };
  3857. // Operators
  3858. /**
  3859. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3860. */
  3861. Vector4.prototype.asArray = function () {
  3862. var result = new Array();
  3863. this.toArray(result, 0);
  3864. return result;
  3865. };
  3866. /**
  3867. * Populates the given array from the given index with the Vector4 coordinates.
  3868. * Returns the Vector4.
  3869. */
  3870. Vector4.prototype.toArray = function (array, index) {
  3871. if (index === undefined) {
  3872. index = 0;
  3873. }
  3874. array[index] = this.x;
  3875. array[index + 1] = this.y;
  3876. array[index + 2] = this.z;
  3877. array[index + 3] = this.w;
  3878. return this;
  3879. };
  3880. /**
  3881. * Adds the given vector to the current Vector4.
  3882. * Returns the updated Vector4.
  3883. */
  3884. Vector4.prototype.addInPlace = function (otherVector) {
  3885. this.x += otherVector.x;
  3886. this.y += otherVector.y;
  3887. this.z += otherVector.z;
  3888. this.w += otherVector.w;
  3889. return this;
  3890. };
  3891. /**
  3892. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3893. */
  3894. Vector4.prototype.add = function (otherVector) {
  3895. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3896. };
  3897. /**
  3898. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3899. * Returns the current Vector4.
  3900. */
  3901. Vector4.prototype.addToRef = function (otherVector, result) {
  3902. result.x = this.x + otherVector.x;
  3903. result.y = this.y + otherVector.y;
  3904. result.z = this.z + otherVector.z;
  3905. result.w = this.w + otherVector.w;
  3906. return this;
  3907. };
  3908. /**
  3909. * Subtract in place the given vector from the current Vector4.
  3910. * Returns the updated Vector4.
  3911. */
  3912. Vector4.prototype.subtractInPlace = function (otherVector) {
  3913. this.x -= otherVector.x;
  3914. this.y -= otherVector.y;
  3915. this.z -= otherVector.z;
  3916. this.w -= otherVector.w;
  3917. return this;
  3918. };
  3919. /**
  3920. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3921. */
  3922. Vector4.prototype.subtract = function (otherVector) {
  3923. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3924. };
  3925. /**
  3926. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3927. * Returns the current Vector4.
  3928. */
  3929. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3930. result.x = this.x - otherVector.x;
  3931. result.y = this.y - otherVector.y;
  3932. result.z = this.z - otherVector.z;
  3933. result.w = this.w - otherVector.w;
  3934. return this;
  3935. };
  3936. /**
  3937. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3938. */
  3939. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3940. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3941. };
  3942. /**
  3943. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3944. * Returns the current Vector4.
  3945. */
  3946. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3947. result.x = this.x - x;
  3948. result.y = this.y - y;
  3949. result.z = this.z - z;
  3950. result.w = this.w - w;
  3951. return this;
  3952. };
  3953. /**
  3954. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3955. */
  3956. Vector4.prototype.negate = function () {
  3957. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3958. };
  3959. /**
  3960. * Multiplies the current Vector4 coordinates by scale (float).
  3961. * Returns the updated Vector4.
  3962. */
  3963. Vector4.prototype.scaleInPlace = function (scale) {
  3964. this.x *= scale;
  3965. this.y *= scale;
  3966. this.z *= scale;
  3967. this.w *= scale;
  3968. return this;
  3969. };
  3970. /**
  3971. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3972. */
  3973. Vector4.prototype.scale = function (scale) {
  3974. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3975. };
  3976. /**
  3977. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3978. * Returns the current Vector4.
  3979. */
  3980. Vector4.prototype.scaleToRef = function (scale, result) {
  3981. result.x = this.x * scale;
  3982. result.y = this.y * scale;
  3983. result.z = this.z * scale;
  3984. result.w = this.w * scale;
  3985. return this;
  3986. };
  3987. /**
  3988. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3989. * @param scale defines the scale factor
  3990. * @param result defines the Vector4 object where to store the result
  3991. * @returns the unmodified current Vector4
  3992. */
  3993. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3994. result.x += this.x * scale;
  3995. result.y += this.y * scale;
  3996. result.z += this.z * scale;
  3997. result.w += this.w * scale;
  3998. return this;
  3999. };
  4000. /**
  4001. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4002. */
  4003. Vector4.prototype.equals = function (otherVector) {
  4004. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4005. };
  4006. /**
  4007. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4008. */
  4009. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4010. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4011. return otherVector
  4012. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4013. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4014. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4015. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4016. };
  4017. /**
  4018. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4019. */
  4020. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4021. return this.x === x && this.y === y && this.z === z && this.w === w;
  4022. };
  4023. /**
  4024. * Multiplies in place the current Vector4 by the given one.
  4025. * Returns the updated Vector4.
  4026. */
  4027. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4028. this.x *= otherVector.x;
  4029. this.y *= otherVector.y;
  4030. this.z *= otherVector.z;
  4031. this.w *= otherVector.w;
  4032. return this;
  4033. };
  4034. /**
  4035. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4036. */
  4037. Vector4.prototype.multiply = function (otherVector) {
  4038. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4039. };
  4040. /**
  4041. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4042. * Returns the current Vector4.
  4043. */
  4044. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4045. result.x = this.x * otherVector.x;
  4046. result.y = this.y * otherVector.y;
  4047. result.z = this.z * otherVector.z;
  4048. result.w = this.w * otherVector.w;
  4049. return this;
  4050. };
  4051. /**
  4052. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4053. */
  4054. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4055. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4056. };
  4057. /**
  4058. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4059. */
  4060. Vector4.prototype.divide = function (otherVector) {
  4061. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4062. };
  4063. /**
  4064. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4065. * Returns the current Vector4.
  4066. */
  4067. Vector4.prototype.divideToRef = function (otherVector, result) {
  4068. result.x = this.x / otherVector.x;
  4069. result.y = this.y / otherVector.y;
  4070. result.z = this.z / otherVector.z;
  4071. result.w = this.w / otherVector.w;
  4072. return this;
  4073. };
  4074. /**
  4075. * Divides the current Vector3 coordinates by the given ones.
  4076. * @returns the updated Vector3.
  4077. */
  4078. Vector4.prototype.divideInPlace = function (otherVector) {
  4079. return this.divideToRef(otherVector, this);
  4080. };
  4081. /**
  4082. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4083. * @param other defines the second operand
  4084. * @returns the current updated Vector4
  4085. */
  4086. Vector4.prototype.minimizeInPlace = function (other) {
  4087. if (other.x < this.x)
  4088. this.x = other.x;
  4089. if (other.y < this.y)
  4090. this.y = other.y;
  4091. if (other.z < this.z)
  4092. this.z = other.z;
  4093. if (other.w < this.w)
  4094. this.w = other.w;
  4095. return this;
  4096. };
  4097. /**
  4098. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4099. * @param other defines the second operand
  4100. * @returns the current updated Vector4
  4101. */
  4102. Vector4.prototype.maximizeInPlace = function (other) {
  4103. if (other.x > this.x)
  4104. this.x = other.x;
  4105. if (other.y > this.y)
  4106. this.y = other.y;
  4107. if (other.z > this.z)
  4108. this.z = other.z;
  4109. if (other.w > this.w)
  4110. this.w = other.w;
  4111. return this;
  4112. };
  4113. /**
  4114. * Gets a new Vector4 from current Vector4 floored values
  4115. * @returns a new Vector4
  4116. */
  4117. Vector4.prototype.floor = function () {
  4118. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4119. };
  4120. /**
  4121. * Gets a new Vector4 from current Vector3 floored values
  4122. * @returns a new Vector4
  4123. */
  4124. Vector4.prototype.fract = function () {
  4125. return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
  4126. };
  4127. // Properties
  4128. /**
  4129. * Returns the Vector4 length (float).
  4130. */
  4131. Vector4.prototype.length = function () {
  4132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4133. };
  4134. /**
  4135. * Returns the Vector4 squared length (float).
  4136. */
  4137. Vector4.prototype.lengthSquared = function () {
  4138. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4139. };
  4140. // Methods
  4141. /**
  4142. * Normalizes in place the Vector4.
  4143. * Returns the updated Vector4.
  4144. */
  4145. Vector4.prototype.normalize = function () {
  4146. var len = this.length();
  4147. if (len === 0)
  4148. return this;
  4149. var num = 1.0 / len;
  4150. this.x *= num;
  4151. this.y *= num;
  4152. this.z *= num;
  4153. this.w *= num;
  4154. return this;
  4155. };
  4156. /**
  4157. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4158. */
  4159. Vector4.prototype.toVector3 = function () {
  4160. return new Vector3(this.x, this.y, this.z);
  4161. };
  4162. /**
  4163. * Returns a new Vector4 copied from the current one.
  4164. */
  4165. Vector4.prototype.clone = function () {
  4166. return new Vector4(this.x, this.y, this.z, this.w);
  4167. };
  4168. /**
  4169. * Updates the current Vector4 with the given one coordinates.
  4170. * Returns the updated Vector4.
  4171. */
  4172. Vector4.prototype.copyFrom = function (source) {
  4173. this.x = source.x;
  4174. this.y = source.y;
  4175. this.z = source.z;
  4176. this.w = source.w;
  4177. return this;
  4178. };
  4179. /**
  4180. * Updates the current Vector4 coordinates with the given floats.
  4181. * Returns the updated Vector4.
  4182. */
  4183. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4184. this.x = x;
  4185. this.y = y;
  4186. this.z = z;
  4187. this.w = w;
  4188. return this;
  4189. };
  4190. /**
  4191. * Updates the current Vector4 coordinates with the given floats.
  4192. * Returns the updated Vector4.
  4193. */
  4194. Vector4.prototype.set = function (x, y, z, w) {
  4195. return this.copyFromFloats(x, y, z, w);
  4196. };
  4197. // Statics
  4198. /**
  4199. * Returns a new Vector4 set from the starting index of the given array.
  4200. */
  4201. Vector4.FromArray = function (array, offset) {
  4202. if (!offset) {
  4203. offset = 0;
  4204. }
  4205. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4206. };
  4207. /**
  4208. * Updates the given vector "result" from the starting index of the given array.
  4209. */
  4210. Vector4.FromArrayToRef = function (array, offset, result) {
  4211. result.x = array[offset];
  4212. result.y = array[offset + 1];
  4213. result.z = array[offset + 2];
  4214. result.w = array[offset + 3];
  4215. };
  4216. /**
  4217. * Updates the given vector "result" from the starting index of the given Float32Array.
  4218. */
  4219. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4220. Vector4.FromArrayToRef(array, offset, result);
  4221. };
  4222. /**
  4223. * Updates the given vector "result" coordinates from the given floats.
  4224. */
  4225. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4226. result.x = x;
  4227. result.y = y;
  4228. result.z = z;
  4229. result.w = w;
  4230. };
  4231. /**
  4232. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4233. */
  4234. Vector4.Zero = function () {
  4235. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4236. };
  4237. /**
  4238. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4239. */
  4240. Vector4.One = function () {
  4241. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4242. };
  4243. /**
  4244. * Returns a new normalized Vector4 from the given one.
  4245. */
  4246. Vector4.Normalize = function (vector) {
  4247. var result = Vector4.Zero();
  4248. Vector4.NormalizeToRef(vector, result);
  4249. return result;
  4250. };
  4251. /**
  4252. * Updates the given vector "result" from the normalization of the given one.
  4253. */
  4254. Vector4.NormalizeToRef = function (vector, result) {
  4255. result.copyFrom(vector);
  4256. result.normalize();
  4257. };
  4258. Vector4.Minimize = function (left, right) {
  4259. var min = left.clone();
  4260. min.minimizeInPlace(right);
  4261. return min;
  4262. };
  4263. Vector4.Maximize = function (left, right) {
  4264. var max = left.clone();
  4265. max.maximizeInPlace(right);
  4266. return max;
  4267. };
  4268. /**
  4269. * Returns the distance (float) between the vectors "value1" and "value2".
  4270. */
  4271. Vector4.Distance = function (value1, value2) {
  4272. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4273. };
  4274. /**
  4275. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4276. */
  4277. Vector4.DistanceSquared = function (value1, value2) {
  4278. var x = value1.x - value2.x;
  4279. var y = value1.y - value2.y;
  4280. var z = value1.z - value2.z;
  4281. var w = value1.w - value2.w;
  4282. return (x * x) + (y * y) + (z * z) + (w * w);
  4283. };
  4284. /**
  4285. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4286. */
  4287. Vector4.Center = function (value1, value2) {
  4288. var center = value1.add(value2);
  4289. center.scaleInPlace(0.5);
  4290. return center;
  4291. };
  4292. /**
  4293. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4294. * This methods computes transformed normalized direction vectors only.
  4295. */
  4296. Vector4.TransformNormal = function (vector, transformation) {
  4297. var result = Vector4.Zero();
  4298. Vector4.TransformNormalToRef(vector, transformation, result);
  4299. return result;
  4300. };
  4301. /**
  4302. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4303. * This methods computes transformed normalized direction vectors only.
  4304. */
  4305. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4306. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4307. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4308. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4309. result.x = x;
  4310. result.y = y;
  4311. result.z = z;
  4312. result.w = vector.w;
  4313. };
  4314. /**
  4315. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4316. * This methods computes transformed normalized direction vectors only.
  4317. */
  4318. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4319. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4320. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4321. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4322. result.w = w;
  4323. };
  4324. return Vector4;
  4325. }());
  4326. BABYLON.Vector4 = Vector4;
  4327. var Size = /** @class */ (function () {
  4328. /**
  4329. * Creates a Size object from the given width and height (floats).
  4330. */
  4331. function Size(width, height) {
  4332. this.width = width;
  4333. this.height = height;
  4334. }
  4335. // Returns a string with the Size width and height.
  4336. Size.prototype.toString = function () {
  4337. return "{W: " + this.width + ", H: " + this.height + "}";
  4338. };
  4339. /**
  4340. * Returns the string "Size"
  4341. */
  4342. Size.prototype.getClassName = function () {
  4343. return "Size";
  4344. };
  4345. /**
  4346. * Returns the Size hash code.
  4347. */
  4348. Size.prototype.getHashCode = function () {
  4349. var hash = this.width || 0;
  4350. hash = (hash * 397) ^ (this.height || 0);
  4351. return hash;
  4352. };
  4353. /**
  4354. * Updates the current size from the given one.
  4355. * Returns the updated Size.
  4356. */
  4357. Size.prototype.copyFrom = function (src) {
  4358. this.width = src.width;
  4359. this.height = src.height;
  4360. };
  4361. /**
  4362. * Updates in place the current Size from the given floats.
  4363. * Returns the updated Size.
  4364. */
  4365. Size.prototype.copyFromFloats = function (width, height) {
  4366. this.width = width;
  4367. this.height = height;
  4368. return this;
  4369. };
  4370. /**
  4371. * Updates in place the current Size from the given floats.
  4372. * Returns the updated Size.
  4373. */
  4374. Size.prototype.set = function (width, height) {
  4375. return this.copyFromFloats(width, height);
  4376. };
  4377. /**
  4378. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4379. */
  4380. Size.prototype.multiplyByFloats = function (w, h) {
  4381. return new Size(this.width * w, this.height * h);
  4382. };
  4383. /**
  4384. * Returns a new Size copied from the given one.
  4385. */
  4386. Size.prototype.clone = function () {
  4387. return new Size(this.width, this.height);
  4388. };
  4389. /**
  4390. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4391. */
  4392. Size.prototype.equals = function (other) {
  4393. if (!other) {
  4394. return false;
  4395. }
  4396. return (this.width === other.width) && (this.height === other.height);
  4397. };
  4398. Object.defineProperty(Size.prototype, "surface", {
  4399. /**
  4400. * Returns the surface of the Size : width * height (float).
  4401. */
  4402. get: function () {
  4403. return this.width * this.height;
  4404. },
  4405. enumerable: true,
  4406. configurable: true
  4407. });
  4408. /**
  4409. * Returns a new Size set to (0.0, 0.0)
  4410. */
  4411. Size.Zero = function () {
  4412. return new Size(0.0, 0.0);
  4413. };
  4414. /**
  4415. * Returns a new Size set as the addition result of the current Size and the given one.
  4416. */
  4417. Size.prototype.add = function (otherSize) {
  4418. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4419. return r;
  4420. };
  4421. /**
  4422. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4423. */
  4424. Size.prototype.subtract = function (otherSize) {
  4425. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4426. return r;
  4427. };
  4428. /**
  4429. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4430. */
  4431. Size.Lerp = function (start, end, amount) {
  4432. var w = start.width + ((end.width - start.width) * amount);
  4433. var h = start.height + ((end.height - start.height) * amount);
  4434. return new Size(w, h);
  4435. };
  4436. return Size;
  4437. }());
  4438. BABYLON.Size = Size;
  4439. /**
  4440. * Class used to store quaternion data
  4441. * @see https://en.wikipedia.org/wiki/Quaternion
  4442. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4443. */
  4444. var Quaternion = /** @class */ (function () {
  4445. /**
  4446. * Creates a new Quaternion from the given floats
  4447. * @param x defines the first component (0 by default)
  4448. * @param y defines the second component (0 by default)
  4449. * @param z defines the third component (0 by default)
  4450. * @param w defines the fourth component (1.0 by default)
  4451. */
  4452. function Quaternion(
  4453. /** defines the first component (0 by default) */
  4454. x,
  4455. /** defines the second component (0 by default) */
  4456. y,
  4457. /** defines the third component (0 by default) */
  4458. z,
  4459. /** defines the fourth component (1.0 by default) */
  4460. w) {
  4461. if (x === void 0) { x = 0.0; }
  4462. if (y === void 0) { y = 0.0; }
  4463. if (z === void 0) { z = 0.0; }
  4464. if (w === void 0) { w = 1.0; }
  4465. this.x = x;
  4466. this.y = y;
  4467. this.z = z;
  4468. this.w = w;
  4469. }
  4470. /**
  4471. * Gets a string representation for the current quaternion
  4472. * @returns a string with the Quaternion coordinates
  4473. */
  4474. Quaternion.prototype.toString = function () {
  4475. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4476. };
  4477. /**
  4478. * Gets the class name of the quaternion
  4479. * @returns the string "Quaternion"
  4480. */
  4481. Quaternion.prototype.getClassName = function () {
  4482. return "Quaternion";
  4483. };
  4484. /**
  4485. * Gets a hash code for this quaternion
  4486. * @returns the quaternion hash code
  4487. */
  4488. Quaternion.prototype.getHashCode = function () {
  4489. var hash = this.x || 0;
  4490. hash = (hash * 397) ^ (this.y || 0);
  4491. hash = (hash * 397) ^ (this.z || 0);
  4492. hash = (hash * 397) ^ (this.w || 0);
  4493. return hash;
  4494. };
  4495. /**
  4496. * Copy the quaternion to an array
  4497. * @returns a new array populated with 4 elements from the quaternion coordinates
  4498. */
  4499. Quaternion.prototype.asArray = function () {
  4500. return [this.x, this.y, this.z, this.w];
  4501. };
  4502. /**
  4503. * Check if two quaternions are equals
  4504. * @param otherQuaternion defines the second operand
  4505. * @return true if the current quaternion and the given one coordinates are strictly equals
  4506. */
  4507. Quaternion.prototype.equals = function (otherQuaternion) {
  4508. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4509. };
  4510. /**
  4511. * Clone the current quaternion
  4512. * @returns a new quaternion copied from the current one
  4513. */
  4514. Quaternion.prototype.clone = function () {
  4515. return new Quaternion(this.x, this.y, this.z, this.w);
  4516. };
  4517. /**
  4518. * Copy a quaternion to the current one
  4519. * @param other defines the other quaternion
  4520. * @returns the updated current quaternion
  4521. */
  4522. Quaternion.prototype.copyFrom = function (other) {
  4523. this.x = other.x;
  4524. this.y = other.y;
  4525. this.z = other.z;
  4526. this.w = other.w;
  4527. return this;
  4528. };
  4529. /**
  4530. * Updates the current quaternion with the given float coordinates
  4531. * @param x defines the x coordinate
  4532. * @param y defines the y coordinate
  4533. * @param z defines the z coordinate
  4534. * @param w defines the w coordinate
  4535. * @returns the updated current quaternion
  4536. */
  4537. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4538. this.x = x;
  4539. this.y = y;
  4540. this.z = z;
  4541. this.w = w;
  4542. return this;
  4543. };
  4544. /**
  4545. * Updates the current quaternion from the given float coordinates
  4546. * @param x defines the x coordinate
  4547. * @param y defines the y coordinate
  4548. * @param z defines the z coordinate
  4549. * @param w defines the w coordinate
  4550. * @returns the updated current quaternion
  4551. */
  4552. Quaternion.prototype.set = function (x, y, z, w) {
  4553. return this.copyFromFloats(x, y, z, w);
  4554. };
  4555. /**
  4556. * Adds two quaternions
  4557. * @param other defines the second operand
  4558. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4559. */
  4560. Quaternion.prototype.add = function (other) {
  4561. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4562. };
  4563. /**
  4564. * Add a quaternion to the current one
  4565. * @param other defines the quaternion to add
  4566. * @returns the current quaternion
  4567. */
  4568. Quaternion.prototype.addInPlace = function (other) {
  4569. this.x += other.x;
  4570. this.y += other.y;
  4571. this.z += other.z;
  4572. this.w += other.w;
  4573. return this;
  4574. };
  4575. /**
  4576. * Subtract two quaternions
  4577. * @param other defines the second operand
  4578. * @returns a new quaternion as the subtraction result of the given one from the current one
  4579. */
  4580. Quaternion.prototype.subtract = function (other) {
  4581. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4582. };
  4583. /**
  4584. * Multiplies the current quaternion by a scale factor
  4585. * @param value defines the scale factor
  4586. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4587. */
  4588. Quaternion.prototype.scale = function (value) {
  4589. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4590. };
  4591. /**
  4592. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4593. * @param scale defines the scale factor
  4594. * @param result defines the Quaternion object where to store the result
  4595. * @returns the unmodified current quaternion
  4596. */
  4597. Quaternion.prototype.scaleToRef = function (scale, result) {
  4598. result.x = this.x * scale;
  4599. result.y = this.y * scale;
  4600. result.z = this.z * scale;
  4601. result.w = this.w * scale;
  4602. return this;
  4603. };
  4604. /**
  4605. * Multiplies in place the current quaternion by a scale factor
  4606. * @param value defines the scale factor
  4607. * @returns the current modified quaternion
  4608. */
  4609. Quaternion.prototype.scaleInPlace = function (value) {
  4610. this.x *= value;
  4611. this.y *= value;
  4612. this.z *= value;
  4613. this.w *= value;
  4614. return this;
  4615. };
  4616. /**
  4617. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4618. * @param scale defines the scale factor
  4619. * @param result defines the Quaternion object where to store the result
  4620. * @returns the unmodified current quaternion
  4621. */
  4622. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4623. result.x += this.x * scale;
  4624. result.y += this.y * scale;
  4625. result.z += this.z * scale;
  4626. result.w += this.w * scale;
  4627. return this;
  4628. };
  4629. /**
  4630. * Multiplies two quaternions
  4631. * @param q1 defines the second operand
  4632. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4633. */
  4634. Quaternion.prototype.multiply = function (q1) {
  4635. var result = new Quaternion(0, 0, 0, 1.0);
  4636. this.multiplyToRef(q1, result);
  4637. return result;
  4638. };
  4639. /**
  4640. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4641. * @param q1 defines the second operand
  4642. * @param result defines the target quaternion
  4643. * @returns the current quaternion
  4644. */
  4645. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4646. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4647. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4648. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4649. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4650. result.copyFromFloats(x, y, z, w);
  4651. return this;
  4652. };
  4653. /**
  4654. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4655. * @param q1 defines the second operand
  4656. * @returns the currentupdated quaternion
  4657. */
  4658. Quaternion.prototype.multiplyInPlace = function (q1) {
  4659. this.multiplyToRef(q1, this);
  4660. return this;
  4661. };
  4662. /**
  4663. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4664. * @param ref defines the target quaternion
  4665. * @returns the current quaternion
  4666. */
  4667. Quaternion.prototype.conjugateToRef = function (ref) {
  4668. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4669. return this;
  4670. };
  4671. /**
  4672. * Conjugates in place (1-q) the current quaternion
  4673. * @returns the current updated quaternion
  4674. */
  4675. Quaternion.prototype.conjugateInPlace = function () {
  4676. this.x *= -1;
  4677. this.y *= -1;
  4678. this.z *= -1;
  4679. return this;
  4680. };
  4681. /**
  4682. * Conjugates in place (1-q) the current quaternion
  4683. * @returns a new quaternion
  4684. */
  4685. Quaternion.prototype.conjugate = function () {
  4686. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4687. return result;
  4688. };
  4689. /**
  4690. * Gets length of current quaternion
  4691. * @returns the quaternion length (float)
  4692. */
  4693. Quaternion.prototype.length = function () {
  4694. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4695. };
  4696. /**
  4697. * Normalize in place the current quaternion
  4698. * @returns the current updated quaternion
  4699. */
  4700. Quaternion.prototype.normalize = function () {
  4701. var length = 1.0 / this.length();
  4702. this.x *= length;
  4703. this.y *= length;
  4704. this.z *= length;
  4705. this.w *= length;
  4706. return this;
  4707. };
  4708. /**
  4709. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4710. * @param order is a reserved parameter and is ignore for now
  4711. * @returns a new Vector3 containing the Euler angles
  4712. */
  4713. Quaternion.prototype.toEulerAngles = function (order) {
  4714. if (order === void 0) { order = "YZX"; }
  4715. var result = Vector3.Zero();
  4716. this.toEulerAnglesToRef(result, order);
  4717. return result;
  4718. };
  4719. /**
  4720. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4721. * @param result defines the vector which will be filled with the Euler angles
  4722. * @param order is a reserved parameter and is ignore for now
  4723. * @returns the current unchanged quaternion
  4724. */
  4725. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4726. if (order === void 0) { order = "YZX"; }
  4727. var qz = this.z;
  4728. var qx = this.x;
  4729. var qy = this.y;
  4730. var qw = this.w;
  4731. var sqw = qw * qw;
  4732. var sqz = qz * qz;
  4733. var sqx = qx * qx;
  4734. var sqy = qy * qy;
  4735. var zAxisY = qy * qz - qx * qw;
  4736. var limit = .4999999;
  4737. if (zAxisY < -limit) {
  4738. result.y = 2 * Math.atan2(qy, qw);
  4739. result.x = Math.PI / 2;
  4740. result.z = 0;
  4741. }
  4742. else if (zAxisY > limit) {
  4743. result.y = 2 * Math.atan2(qy, qw);
  4744. result.x = -Math.PI / 2;
  4745. result.z = 0;
  4746. }
  4747. else {
  4748. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4749. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4750. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4751. }
  4752. return this;
  4753. };
  4754. /**
  4755. * Updates the given rotation matrix with the current quaternion values
  4756. * @param result defines the target matrix
  4757. * @returns the current unchanged quaternion
  4758. */
  4759. Quaternion.prototype.toRotationMatrix = function (result) {
  4760. var xx = this.x * this.x;
  4761. var yy = this.y * this.y;
  4762. var zz = this.z * this.z;
  4763. var xy = this.x * this.y;
  4764. var zw = this.z * this.w;
  4765. var zx = this.z * this.x;
  4766. var yw = this.y * this.w;
  4767. var yz = this.y * this.z;
  4768. var xw = this.x * this.w;
  4769. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4770. result.m[1] = 2.0 * (xy + zw);
  4771. result.m[2] = 2.0 * (zx - yw);
  4772. result.m[3] = 0;
  4773. result.m[4] = 2.0 * (xy - zw);
  4774. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4775. result.m[6] = 2.0 * (yz + xw);
  4776. result.m[7] = 0;
  4777. result.m[8] = 2.0 * (zx + yw);
  4778. result.m[9] = 2.0 * (yz - xw);
  4779. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4780. result.m[11] = 0;
  4781. result.m[12] = 0;
  4782. result.m[13] = 0;
  4783. result.m[14] = 0;
  4784. result.m[15] = 1.0;
  4785. result._markAsUpdated();
  4786. return this;
  4787. };
  4788. /**
  4789. * Updates the current quaternion from the given rotation matrix values
  4790. * @param matrix defines the source matrix
  4791. * @returns the current updated quaternion
  4792. */
  4793. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4794. Quaternion.FromRotationMatrixToRef(matrix, this);
  4795. return this;
  4796. };
  4797. // Statics
  4798. /**
  4799. * Creates a new quaternion from a rotation matrix
  4800. * @param matrix defines the source matrix
  4801. * @returns a new quaternion created from the given rotation matrix values
  4802. */
  4803. Quaternion.FromRotationMatrix = function (matrix) {
  4804. var result = new Quaternion();
  4805. Quaternion.FromRotationMatrixToRef(matrix, result);
  4806. return result;
  4807. };
  4808. /**
  4809. * Updates the given quaternion with the given rotation matrix values
  4810. * @param matrix defines the source matrix
  4811. * @param result defines the target quaternion
  4812. */
  4813. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4814. var data = matrix.m;
  4815. var m11 = data[0], m12 = data[4], m13 = data[8];
  4816. var m21 = data[1], m22 = data[5], m23 = data[9];
  4817. var m31 = data[2], m32 = data[6], m33 = data[10];
  4818. var trace = m11 + m22 + m33;
  4819. var s;
  4820. if (trace > 0) {
  4821. s = 0.5 / Math.sqrt(trace + 1.0);
  4822. result.w = 0.25 / s;
  4823. result.x = (m32 - m23) * s;
  4824. result.y = (m13 - m31) * s;
  4825. result.z = (m21 - m12) * s;
  4826. }
  4827. else if (m11 > m22 && m11 > m33) {
  4828. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4829. result.w = (m32 - m23) / s;
  4830. result.x = 0.25 * s;
  4831. result.y = (m12 + m21) / s;
  4832. result.z = (m13 + m31) / s;
  4833. }
  4834. else if (m22 > m33) {
  4835. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4836. result.w = (m13 - m31) / s;
  4837. result.x = (m12 + m21) / s;
  4838. result.y = 0.25 * s;
  4839. result.z = (m23 + m32) / s;
  4840. }
  4841. else {
  4842. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4843. result.w = (m21 - m12) / s;
  4844. result.x = (m13 + m31) / s;
  4845. result.y = (m23 + m32) / s;
  4846. result.z = 0.25 * s;
  4847. }
  4848. };
  4849. /**
  4850. * Returns the dot product (float) between the quaternions "left" and "right"
  4851. * @param left defines the left operand
  4852. * @param right defines the right operand
  4853. * @returns the dot product
  4854. */
  4855. Quaternion.Dot = function (left, right) {
  4856. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4857. };
  4858. /**
  4859. * Checks if the two quaternions are close to each other
  4860. * @param quat0 defines the first quaternion to check
  4861. * @param quat1 defines the second quaternion to check
  4862. * @returns true if the two quaternions are close to each other
  4863. */
  4864. Quaternion.AreClose = function (quat0, quat1) {
  4865. var dot = Quaternion.Dot(quat0, quat1);
  4866. return dot >= 0;
  4867. };
  4868. /**
  4869. * Creates an empty quaternion
  4870. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4871. */
  4872. Quaternion.Zero = function () {
  4873. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4874. };
  4875. /**
  4876. * Inverse a given quaternion
  4877. * @param q defines the source quaternion
  4878. * @returns a new quaternion as the inverted current quaternion
  4879. */
  4880. Quaternion.Inverse = function (q) {
  4881. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4882. };
  4883. /**
  4884. * Creates an identity quaternion
  4885. * @returns the identity quaternion
  4886. */
  4887. Quaternion.Identity = function () {
  4888. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4889. };
  4890. /**
  4891. * Gets a boolean indicating if the given quaternion is identity
  4892. * @param quaternion defines the quaternion to check
  4893. * @returns true if the quaternion is identity
  4894. */
  4895. Quaternion.IsIdentity = function (quaternion) {
  4896. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4897. };
  4898. /**
  4899. * Creates a quaternion from a rotation around an axis
  4900. * @param axis defines the axis to use
  4901. * @param angle defines the angle to use
  4902. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4903. */
  4904. Quaternion.RotationAxis = function (axis, angle) {
  4905. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4906. };
  4907. /**
  4908. * Creates a rotation around an axis and stores it into the given quaternion
  4909. * @param axis defines the axis to use
  4910. * @param angle defines the angle to use
  4911. * @param result defines the target quaternion
  4912. * @returns the target quaternion
  4913. */
  4914. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4915. var sin = Math.sin(angle / 2);
  4916. axis.normalize();
  4917. result.w = Math.cos(angle / 2);
  4918. result.x = axis.x * sin;
  4919. result.y = axis.y * sin;
  4920. result.z = axis.z * sin;
  4921. return result;
  4922. };
  4923. /**
  4924. * Creates a new quaternion from data stored into an array
  4925. * @param array defines the data source
  4926. * @param offset defines the offset in the source array where the data starts
  4927. * @returns a new quaternion
  4928. */
  4929. Quaternion.FromArray = function (array, offset) {
  4930. if (!offset) {
  4931. offset = 0;
  4932. }
  4933. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4934. };
  4935. /**
  4936. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4937. * @param yaw defines the rotation around Y axis
  4938. * @param pitch defines the rotation around X axis
  4939. * @param roll defines the rotation around Z axis
  4940. * @returns the new quaternion
  4941. */
  4942. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4943. var q = new Quaternion();
  4944. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4945. return q;
  4946. };
  4947. /**
  4948. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4949. * @param yaw defines the rotation around Y axis
  4950. * @param pitch defines the rotation around X axis
  4951. * @param roll defines the rotation around Z axis
  4952. * @param result defines the target quaternion
  4953. */
  4954. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4955. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4956. var halfRoll = roll * 0.5;
  4957. var halfPitch = pitch * 0.5;
  4958. var halfYaw = yaw * 0.5;
  4959. var sinRoll = Math.sin(halfRoll);
  4960. var cosRoll = Math.cos(halfRoll);
  4961. var sinPitch = Math.sin(halfPitch);
  4962. var cosPitch = Math.cos(halfPitch);
  4963. var sinYaw = Math.sin(halfYaw);
  4964. var cosYaw = Math.cos(halfYaw);
  4965. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4966. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4967. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4968. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4969. };
  4970. /**
  4971. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4972. * @param alpha defines the rotation around first axis
  4973. * @param beta defines the rotation around second axis
  4974. * @param gamma defines the rotation around third axis
  4975. * @returns the new quaternion
  4976. */
  4977. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4978. var result = new Quaternion();
  4979. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4980. return result;
  4981. };
  4982. /**
  4983. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4984. * @param alpha defines the rotation around first axis
  4985. * @param beta defines the rotation around second axis
  4986. * @param gamma defines the rotation around third axis
  4987. * @param result defines the target quaternion
  4988. */
  4989. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4990. // Produces a quaternion from Euler angles in the z-x-z orientation
  4991. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4992. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4993. var halfBeta = beta * 0.5;
  4994. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4995. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4996. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4997. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4998. };
  4999. /**
  5000. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  5001. * @param axis1 defines the first axis
  5002. * @param axis2 defines the second axis
  5003. * @param axis3 defines the third axis
  5004. * @returns the new quaternion
  5005. */
  5006. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5007. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5008. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5009. return quat;
  5010. };
  5011. /**
  5012. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  5013. * @param axis1 defines the first axis
  5014. * @param axis2 defines the second axis
  5015. * @param axis3 defines the third axis
  5016. * @param ref defines the target quaternion
  5017. */
  5018. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5019. var rotMat = MathTmp.Matrix[0];
  5020. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5021. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5022. };
  5023. /**
  5024. * Interpolates between two quaternions
  5025. * @param left defines first quaternion
  5026. * @param right defines second quaternion
  5027. * @param amount defines the gradient to use
  5028. * @returns the new interpolated quaternion
  5029. */
  5030. Quaternion.Slerp = function (left, right, amount) {
  5031. var result = Quaternion.Identity();
  5032. Quaternion.SlerpToRef(left, right, amount, result);
  5033. return result;
  5034. };
  5035. /**
  5036. * Interpolates between two quaternions and stores it into a target quaternion
  5037. * @param left defines first quaternion
  5038. * @param right defines second quaternion
  5039. * @param amount defines the gradient to use
  5040. * @param result defines the target quaternion
  5041. */
  5042. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5043. var num2;
  5044. var num3;
  5045. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5046. var flag = false;
  5047. if (num4 < 0) {
  5048. flag = true;
  5049. num4 = -num4;
  5050. }
  5051. if (num4 > 0.999999) {
  5052. num3 = 1 - amount;
  5053. num2 = flag ? -amount : amount;
  5054. }
  5055. else {
  5056. var num5 = Math.acos(num4);
  5057. var num6 = (1.0 / Math.sin(num5));
  5058. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5059. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5060. }
  5061. result.x = (num3 * left.x) + (num2 * right.x);
  5062. result.y = (num3 * left.y) + (num2 * right.y);
  5063. result.z = (num3 * left.z) + (num2 * right.z);
  5064. result.w = (num3 * left.w) + (num2 * right.w);
  5065. };
  5066. /**
  5067. * Interpolate between two quaternions using Hermite interpolation
  5068. * @param value1 defines first quaternion
  5069. * @param tangent1 defines the incoming tangent
  5070. * @param value2 defines second quaternion
  5071. * @param tangent2 defines the outgoing tangent
  5072. * @param amount defines the target quaternion
  5073. * @returns the new interpolated quaternion
  5074. */
  5075. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5076. var squared = amount * amount;
  5077. var cubed = amount * squared;
  5078. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5079. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5080. var part3 = (cubed - (2.0 * squared)) + amount;
  5081. var part4 = cubed - squared;
  5082. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5083. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5084. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5085. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5086. return new Quaternion(x, y, z, w);
  5087. };
  5088. return Quaternion;
  5089. }());
  5090. BABYLON.Quaternion = Quaternion;
  5091. /**
  5092. * Class used to store matrix data (4x4)
  5093. */
  5094. var Matrix = /** @class */ (function () {
  5095. /**
  5096. * Creates an empty matrix (filled with zeros)
  5097. */
  5098. function Matrix() {
  5099. this._isIdentity = false;
  5100. this._isIdentityDirty = true;
  5101. /**
  5102. * Gets or sets the internal data of the matrix
  5103. */
  5104. this.m = new Float32Array(16);
  5105. this._markAsUpdated();
  5106. }
  5107. /** @hidden */
  5108. Matrix.prototype._markAsUpdated = function () {
  5109. this.updateFlag = Matrix._updateFlagSeed++;
  5110. this._isIdentityDirty = true;
  5111. };
  5112. // Properties
  5113. /**
  5114. * Check if the current matrix is indentity
  5115. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5116. * @returns true is the matrix is the identity matrix
  5117. */
  5118. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5119. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5120. if (this._isIdentityDirty) {
  5121. this._isIdentityDirty = false;
  5122. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5123. this._isIdentity = false;
  5124. }
  5125. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5126. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5127. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5128. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5129. this._isIdentity = false;
  5130. }
  5131. else {
  5132. this._isIdentity = true;
  5133. }
  5134. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5135. this._isIdentity = false;
  5136. }
  5137. }
  5138. return this._isIdentity;
  5139. };
  5140. /**
  5141. * Gets the determinant of the matrix
  5142. * @returns the matrix determinant
  5143. */
  5144. Matrix.prototype.determinant = function () {
  5145. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5146. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5147. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5148. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5149. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5150. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5151. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5152. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5153. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5154. };
  5155. // Methods
  5156. /**
  5157. * Returns the matrix as a Float32Array
  5158. * @returns the matrix underlying array
  5159. */
  5160. Matrix.prototype.toArray = function () {
  5161. return this.m;
  5162. };
  5163. /**
  5164. * Returns the matrix as a Float32Array
  5165. * @returns the matrix underlying array.
  5166. */
  5167. Matrix.prototype.asArray = function () {
  5168. return this.toArray();
  5169. };
  5170. /**
  5171. * Inverts the current matrix in place
  5172. * @returns the current inverted matrix
  5173. */
  5174. Matrix.prototype.invert = function () {
  5175. this.invertToRef(this);
  5176. return this;
  5177. };
  5178. /**
  5179. * Sets all the matrix elements to zero
  5180. * @returns the current matrix
  5181. */
  5182. Matrix.prototype.reset = function () {
  5183. for (var index = 0; index < 16; index++) {
  5184. this.m[index] = 0.0;
  5185. }
  5186. this._markAsUpdated();
  5187. return this;
  5188. };
  5189. /**
  5190. * Adds the current matrix with a second one
  5191. * @param other defines the matrix to add
  5192. * @returns a new matrix as the addition of the current matrix and the given one
  5193. */
  5194. Matrix.prototype.add = function (other) {
  5195. var result = new Matrix();
  5196. this.addToRef(other, result);
  5197. return result;
  5198. };
  5199. /**
  5200. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5201. * @param other defines the matrix to add
  5202. * @param result defines the target matrix
  5203. * @returns the current matrix
  5204. */
  5205. Matrix.prototype.addToRef = function (other, result) {
  5206. for (var index = 0; index < 16; index++) {
  5207. result.m[index] = this.m[index] + other.m[index];
  5208. }
  5209. result._markAsUpdated();
  5210. return this;
  5211. };
  5212. /**
  5213. * Adds in place the given matrix to the current matrix
  5214. * @param other defines the second operand
  5215. * @returns the current updated matrix
  5216. */
  5217. Matrix.prototype.addToSelf = function (other) {
  5218. for (var index = 0; index < 16; index++) {
  5219. this.m[index] += other.m[index];
  5220. }
  5221. this._markAsUpdated();
  5222. return this;
  5223. };
  5224. /**
  5225. * Sets the given matrix to the current inverted Matrix
  5226. * @param other defines the target matrix
  5227. * @returns the unmodified current matrix
  5228. */
  5229. Matrix.prototype.invertToRef = function (other) {
  5230. var l1 = this.m[0];
  5231. var l2 = this.m[1];
  5232. var l3 = this.m[2];
  5233. var l4 = this.m[3];
  5234. var l5 = this.m[4];
  5235. var l6 = this.m[5];
  5236. var l7 = this.m[6];
  5237. var l8 = this.m[7];
  5238. var l9 = this.m[8];
  5239. var l10 = this.m[9];
  5240. var l11 = this.m[10];
  5241. var l12 = this.m[11];
  5242. var l13 = this.m[12];
  5243. var l14 = this.m[13];
  5244. var l15 = this.m[14];
  5245. var l16 = this.m[15];
  5246. var l17 = (l11 * l16) - (l12 * l15);
  5247. var l18 = (l10 * l16) - (l12 * l14);
  5248. var l19 = (l10 * l15) - (l11 * l14);
  5249. var l20 = (l9 * l16) - (l12 * l13);
  5250. var l21 = (l9 * l15) - (l11 * l13);
  5251. var l22 = (l9 * l14) - (l10 * l13);
  5252. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5253. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5254. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5255. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5256. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5257. var l28 = (l7 * l16) - (l8 * l15);
  5258. var l29 = (l6 * l16) - (l8 * l14);
  5259. var l30 = (l6 * l15) - (l7 * l14);
  5260. var l31 = (l5 * l16) - (l8 * l13);
  5261. var l32 = (l5 * l15) - (l7 * l13);
  5262. var l33 = (l5 * l14) - (l6 * l13);
  5263. var l34 = (l7 * l12) - (l8 * l11);
  5264. var l35 = (l6 * l12) - (l8 * l10);
  5265. var l36 = (l6 * l11) - (l7 * l10);
  5266. var l37 = (l5 * l12) - (l8 * l9);
  5267. var l38 = (l5 * l11) - (l7 * l9);
  5268. var l39 = (l5 * l10) - (l6 * l9);
  5269. other.m[0] = l23 * l27;
  5270. other.m[4] = l24 * l27;
  5271. other.m[8] = l25 * l27;
  5272. other.m[12] = l26 * l27;
  5273. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5274. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5275. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5276. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5277. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5278. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5279. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5280. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5281. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5282. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5283. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5284. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5285. other._markAsUpdated();
  5286. return this;
  5287. };
  5288. /**
  5289. * Inserts the translation vector (using 3 floats) in the current matrix
  5290. * @param x defines the 1st component of the translation
  5291. * @param y defines the 2nd component of the translation
  5292. * @param z defines the 3rd component of the translation
  5293. * @returns the current updated matrix
  5294. */
  5295. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5296. this.m[12] = x;
  5297. this.m[13] = y;
  5298. this.m[14] = z;
  5299. this._markAsUpdated();
  5300. return this;
  5301. };
  5302. /**
  5303. * Inserts the translation vector in the current matrix
  5304. * @param vector3 defines the translation to insert
  5305. * @returns the current updated matrix
  5306. */
  5307. Matrix.prototype.setTranslation = function (vector3) {
  5308. this.m[12] = vector3.x;
  5309. this.m[13] = vector3.y;
  5310. this.m[14] = vector3.z;
  5311. this._markAsUpdated();
  5312. return this;
  5313. };
  5314. /**
  5315. * Gets the translation value of the current matrix
  5316. * @returns a new Vector3 as the extracted translation from the matrix
  5317. */
  5318. Matrix.prototype.getTranslation = function () {
  5319. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5320. };
  5321. /**
  5322. * Fill a Vector3 with the extracted translation from the matrix
  5323. * @param result defines the Vector3 where to store the translation
  5324. * @returns the current matrix
  5325. */
  5326. Matrix.prototype.getTranslationToRef = function (result) {
  5327. result.x = this.m[12];
  5328. result.y = this.m[13];
  5329. result.z = this.m[14];
  5330. return this;
  5331. };
  5332. /**
  5333. * Remove rotation and scaling part from the matrix
  5334. * @returns the updated matrix
  5335. */
  5336. Matrix.prototype.removeRotationAndScaling = function () {
  5337. this.setRowFromFloats(0, 1, 0, 0, 0);
  5338. this.setRowFromFloats(1, 0, 1, 0, 0);
  5339. this.setRowFromFloats(2, 0, 0, 1, 0);
  5340. return this;
  5341. };
  5342. /**
  5343. * Multiply two matrices
  5344. * @param other defines the second operand
  5345. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5346. */
  5347. Matrix.prototype.multiply = function (other) {
  5348. var result = new Matrix();
  5349. this.multiplyToRef(other, result);
  5350. return result;
  5351. };
  5352. /**
  5353. * Copy the current matrix from the given one
  5354. * @param other defines the source matrix
  5355. * @returns the current updated matrix
  5356. */
  5357. Matrix.prototype.copyFrom = function (other) {
  5358. for (var index = 0; index < 16; index++) {
  5359. this.m[index] = other.m[index];
  5360. }
  5361. this._markAsUpdated();
  5362. return this;
  5363. };
  5364. /**
  5365. * Populates the given array from the starting index with the current matrix values
  5366. * @param array defines the target array
  5367. * @param offset defines the offset in the target array where to start storing values
  5368. * @returns the current matrix
  5369. */
  5370. Matrix.prototype.copyToArray = function (array, offset) {
  5371. if (offset === void 0) { offset = 0; }
  5372. for (var index = 0; index < 16; index++) {
  5373. array[offset + index] = this.m[index];
  5374. }
  5375. return this;
  5376. };
  5377. /**
  5378. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5379. * @param other defines the second operand
  5380. * @param result defines the matrix where to store the multiplication
  5381. * @returns the current matrix
  5382. */
  5383. Matrix.prototype.multiplyToRef = function (other, result) {
  5384. this.multiplyToArray(other, result.m, 0);
  5385. result._markAsUpdated();
  5386. return this;
  5387. };
  5388. /**
  5389. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5390. * @param other defines the second operand
  5391. * @param result defines the array where to store the multiplication
  5392. * @param offset defines the offset in the target array where to start storing values
  5393. * @returns the current matrix
  5394. */
  5395. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5396. var tm0 = this.m[0];
  5397. var tm1 = this.m[1];
  5398. var tm2 = this.m[2];
  5399. var tm3 = this.m[3];
  5400. var tm4 = this.m[4];
  5401. var tm5 = this.m[5];
  5402. var tm6 = this.m[6];
  5403. var tm7 = this.m[7];
  5404. var tm8 = this.m[8];
  5405. var tm9 = this.m[9];
  5406. var tm10 = this.m[10];
  5407. var tm11 = this.m[11];
  5408. var tm12 = this.m[12];
  5409. var tm13 = this.m[13];
  5410. var tm14 = this.m[14];
  5411. var tm15 = this.m[15];
  5412. var om0 = other.m[0];
  5413. var om1 = other.m[1];
  5414. var om2 = other.m[2];
  5415. var om3 = other.m[3];
  5416. var om4 = other.m[4];
  5417. var om5 = other.m[5];
  5418. var om6 = other.m[6];
  5419. var om7 = other.m[7];
  5420. var om8 = other.m[8];
  5421. var om9 = other.m[9];
  5422. var om10 = other.m[10];
  5423. var om11 = other.m[11];
  5424. var om12 = other.m[12];
  5425. var om13 = other.m[13];
  5426. var om14 = other.m[14];
  5427. var om15 = other.m[15];
  5428. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5429. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5430. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5431. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5432. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5433. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5434. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5435. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5436. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5437. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5438. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5439. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5440. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5441. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5442. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5443. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5444. return this;
  5445. };
  5446. /**
  5447. * Check equality between this matrix and a second one
  5448. * @param value defines the second matrix to compare
  5449. * @returns true is the current matrix and the given one values are strictly equal
  5450. */
  5451. Matrix.prototype.equals = function (value) {
  5452. return value &&
  5453. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5454. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5455. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5456. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5457. };
  5458. /**
  5459. * Clone the current matrix
  5460. * @returns a new matrix from the current matrix
  5461. */
  5462. Matrix.prototype.clone = function () {
  5463. 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]);
  5464. };
  5465. /**
  5466. * Returns the name of the current matrix class
  5467. * @returns the string "Matrix"
  5468. */
  5469. Matrix.prototype.getClassName = function () {
  5470. return "Matrix";
  5471. };
  5472. /**
  5473. * Gets the hash code of the current matrix
  5474. * @returns the hash code
  5475. */
  5476. Matrix.prototype.getHashCode = function () {
  5477. var hash = this.m[0] || 0;
  5478. for (var i = 1; i < 16; i++) {
  5479. hash = (hash * 397) ^ (this.m[i] || 0);
  5480. }
  5481. return hash;
  5482. };
  5483. /**
  5484. * Decomposes the current Matrix into a translation, rotation and scaling components
  5485. * @param scale defines the scale vector3 given as a reference to update
  5486. * @param rotation defines the rotation quaternion given as a reference to update
  5487. * @param translation defines the translation vector3 given as a reference to update
  5488. * @returns true if operation was successful
  5489. */
  5490. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5491. if (translation) {
  5492. translation.x = this.m[12];
  5493. translation.y = this.m[13];
  5494. translation.z = this.m[14];
  5495. }
  5496. scale = scale || MathTmp.Vector3[0];
  5497. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5498. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5499. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5500. if (this.determinant() <= 0) {
  5501. scale.y *= -1;
  5502. }
  5503. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5504. if (rotation) {
  5505. rotation.x = 0;
  5506. rotation.y = 0;
  5507. rotation.z = 0;
  5508. rotation.w = 1;
  5509. }
  5510. return false;
  5511. }
  5512. if (rotation) {
  5513. 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]);
  5514. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5515. }
  5516. return true;
  5517. };
  5518. /**
  5519. * Gets specific row of the matrix
  5520. * @param index defines the number of the row to get
  5521. * @returns the index-th row of the current matrix as a new Vector4
  5522. */
  5523. Matrix.prototype.getRow = function (index) {
  5524. if (index < 0 || index > 3) {
  5525. return null;
  5526. }
  5527. var i = index * 4;
  5528. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5529. };
  5530. /**
  5531. * Sets the index-th row of the current matrix to the vector4 values
  5532. * @param index defines the number of the row to set
  5533. * @param row defines the target vector4
  5534. * @returns the updated current matrix
  5535. */
  5536. Matrix.prototype.setRow = function (index, row) {
  5537. if (index < 0 || index > 3) {
  5538. return this;
  5539. }
  5540. var i = index * 4;
  5541. this.m[i + 0] = row.x;
  5542. this.m[i + 1] = row.y;
  5543. this.m[i + 2] = row.z;
  5544. this.m[i + 3] = row.w;
  5545. this._markAsUpdated();
  5546. return this;
  5547. };
  5548. /**
  5549. * Compute the transpose of the matrix
  5550. * @returns the new transposed matrix
  5551. */
  5552. Matrix.prototype.transpose = function () {
  5553. return Matrix.Transpose(this);
  5554. };
  5555. /**
  5556. * Compute the transpose of the matrix and store it in a given matrix
  5557. * @param result defines the target matrix
  5558. * @returns the current matrix
  5559. */
  5560. Matrix.prototype.transposeToRef = function (result) {
  5561. Matrix.TransposeToRef(this, result);
  5562. return this;
  5563. };
  5564. /**
  5565. * Sets the index-th row of the current matrix with the given 4 x float values
  5566. * @param index defines the row index
  5567. * @param x defines the x component to set
  5568. * @param y defines the y component to set
  5569. * @param z defines the z component to set
  5570. * @param w defines the w component to set
  5571. * @returns the updated current matrix
  5572. */
  5573. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5574. if (index < 0 || index > 3) {
  5575. return this;
  5576. }
  5577. var i = index * 4;
  5578. this.m[i + 0] = x;
  5579. this.m[i + 1] = y;
  5580. this.m[i + 2] = z;
  5581. this.m[i + 3] = w;
  5582. this._markAsUpdated();
  5583. return this;
  5584. };
  5585. /**
  5586. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5587. * @param scale defines the scale factor
  5588. * @returns a new matrix
  5589. */
  5590. Matrix.prototype.scale = function (scale) {
  5591. var result = new Matrix();
  5592. this.scaleToRef(scale, result);
  5593. return result;
  5594. };
  5595. /**
  5596. * Scale the current matrix values by a factor to a given result matrix
  5597. * @param scale defines the scale factor
  5598. * @param result defines the matrix to store the result
  5599. * @returns the current matrix
  5600. */
  5601. Matrix.prototype.scaleToRef = function (scale, result) {
  5602. for (var index = 0; index < 16; index++) {
  5603. result.m[index] = this.m[index] * scale;
  5604. }
  5605. result._markAsUpdated();
  5606. return this;
  5607. };
  5608. /**
  5609. * Scale the current matrix values by a factor and add the result to a given matrix
  5610. * @param scale defines the scale factor
  5611. * @param result defines the Matrix to store the result
  5612. * @returns the current matrix
  5613. */
  5614. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5615. for (var index = 0; index < 16; index++) {
  5616. result.m[index] += this.m[index] * scale;
  5617. }
  5618. result._markAsUpdated();
  5619. return this;
  5620. };
  5621. /**
  5622. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5623. * @param ref matrix to store the result
  5624. */
  5625. Matrix.prototype.toNormalMatrix = function (ref) {
  5626. this.invertToRef(ref);
  5627. ref.transpose();
  5628. var m = ref.m;
  5629. 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);
  5630. };
  5631. /**
  5632. * Gets only rotation part of the current matrix
  5633. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5634. */
  5635. Matrix.prototype.getRotationMatrix = function () {
  5636. var result = Matrix.Identity();
  5637. this.getRotationMatrixToRef(result);
  5638. return result;
  5639. };
  5640. /**
  5641. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5642. * @param result defines the target matrix to store data to
  5643. * @returns the current matrix
  5644. */
  5645. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5646. var m = this.m;
  5647. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5648. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5649. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5650. if (this.determinant() <= 0) {
  5651. sy *= -1;
  5652. }
  5653. if (sx === 0 || sy === 0 || sz === 0) {
  5654. Matrix.IdentityToRef(result);
  5655. }
  5656. else {
  5657. 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);
  5658. }
  5659. return this;
  5660. };
  5661. // Statics
  5662. /**
  5663. * Creates a matrix from an array
  5664. * @param array defines the source array
  5665. * @param offset defines an offset in the source array
  5666. * @returns a new Matrix set from the starting index of the given array
  5667. */
  5668. Matrix.FromArray = function (array, offset) {
  5669. var result = new Matrix();
  5670. if (!offset) {
  5671. offset = 0;
  5672. }
  5673. Matrix.FromArrayToRef(array, offset, result);
  5674. return result;
  5675. };
  5676. /**
  5677. * Copy the content of an array into a given matrix
  5678. * @param array defines the source array
  5679. * @param offset defines an offset in the source array
  5680. * @param result defines the target matrix
  5681. */
  5682. Matrix.FromArrayToRef = function (array, offset, result) {
  5683. for (var index = 0; index < 16; index++) {
  5684. result.m[index] = array[index + offset];
  5685. }
  5686. result._markAsUpdated();
  5687. };
  5688. /**
  5689. * Stores an array into a matrix after having multiplied each component by a given factor
  5690. * @param array defines the source array
  5691. * @param offset defines the offset in the source array
  5692. * @param scale defines the scaling factor
  5693. * @param result defines the target matrix
  5694. */
  5695. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5696. for (var index = 0; index < 16; index++) {
  5697. result.m[index] = array[index + offset] * scale;
  5698. }
  5699. result._markAsUpdated();
  5700. };
  5701. /**
  5702. * Stores a list of values (16) inside a given matrix
  5703. * @param initialM11 defines 1st value of 1st row
  5704. * @param initialM12 defines 2nd value of 1st row
  5705. * @param initialM13 defines 3rd value of 1st row
  5706. * @param initialM14 defines 4th value of 1st row
  5707. * @param initialM21 defines 1st value of 2nd row
  5708. * @param initialM22 defines 2nd value of 2nd row
  5709. * @param initialM23 defines 3rd value of 2nd row
  5710. * @param initialM24 defines 4th value of 2nd row
  5711. * @param initialM31 defines 1st value of 3rd row
  5712. * @param initialM32 defines 2nd value of 3rd row
  5713. * @param initialM33 defines 3rd value of 3rd row
  5714. * @param initialM34 defines 4th value of 3rd row
  5715. * @param initialM41 defines 1st value of 4th row
  5716. * @param initialM42 defines 2nd value of 4th row
  5717. * @param initialM43 defines 3rd value of 4th row
  5718. * @param initialM44 defines 4th value of 4th row
  5719. * @param result defines the target matrix
  5720. */
  5721. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5722. result.m[0] = initialM11;
  5723. result.m[1] = initialM12;
  5724. result.m[2] = initialM13;
  5725. result.m[3] = initialM14;
  5726. result.m[4] = initialM21;
  5727. result.m[5] = initialM22;
  5728. result.m[6] = initialM23;
  5729. result.m[7] = initialM24;
  5730. result.m[8] = initialM31;
  5731. result.m[9] = initialM32;
  5732. result.m[10] = initialM33;
  5733. result.m[11] = initialM34;
  5734. result.m[12] = initialM41;
  5735. result.m[13] = initialM42;
  5736. result.m[14] = initialM43;
  5737. result.m[15] = initialM44;
  5738. result._markAsUpdated();
  5739. };
  5740. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5741. /**
  5742. * Gets an identity matrix that must not be updated
  5743. */
  5744. get: function () {
  5745. return Matrix._identityReadOnly;
  5746. },
  5747. enumerable: true,
  5748. configurable: true
  5749. });
  5750. /**
  5751. * Creates new matrix from a list of values (16)
  5752. * @param initialM11 defines 1st value of 1st row
  5753. * @param initialM12 defines 2nd value of 1st row
  5754. * @param initialM13 defines 3rd value of 1st row
  5755. * @param initialM14 defines 4th value of 1st row
  5756. * @param initialM21 defines 1st value of 2nd row
  5757. * @param initialM22 defines 2nd value of 2nd row
  5758. * @param initialM23 defines 3rd value of 2nd row
  5759. * @param initialM24 defines 4th value of 2nd row
  5760. * @param initialM31 defines 1st value of 3rd row
  5761. * @param initialM32 defines 2nd value of 3rd row
  5762. * @param initialM33 defines 3rd value of 3rd row
  5763. * @param initialM34 defines 4th value of 3rd row
  5764. * @param initialM41 defines 1st value of 4th row
  5765. * @param initialM42 defines 2nd value of 4th row
  5766. * @param initialM43 defines 3rd value of 4th row
  5767. * @param initialM44 defines 4th value of 4th row
  5768. * @returns the new matrix
  5769. */
  5770. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5771. var result = new Matrix();
  5772. result.m[0] = initialM11;
  5773. result.m[1] = initialM12;
  5774. result.m[2] = initialM13;
  5775. result.m[3] = initialM14;
  5776. result.m[4] = initialM21;
  5777. result.m[5] = initialM22;
  5778. result.m[6] = initialM23;
  5779. result.m[7] = initialM24;
  5780. result.m[8] = initialM31;
  5781. result.m[9] = initialM32;
  5782. result.m[10] = initialM33;
  5783. result.m[11] = initialM34;
  5784. result.m[12] = initialM41;
  5785. result.m[13] = initialM42;
  5786. result.m[14] = initialM43;
  5787. result.m[15] = initialM44;
  5788. return result;
  5789. };
  5790. /**
  5791. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5792. * @param scale defines the scale vector3
  5793. * @param rotation defines the rotation quaternion
  5794. * @param translation defines the translation vector3
  5795. * @returns a new matrix
  5796. */
  5797. Matrix.Compose = function (scale, rotation, translation) {
  5798. var result = Matrix.Identity();
  5799. Matrix.ComposeToRef(scale, rotation, translation, result);
  5800. return result;
  5801. };
  5802. /**
  5803. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5804. * @param scale defines the scale vector3
  5805. * @param rotation defines the rotation quaternion
  5806. * @param translation defines the translation vector3
  5807. * @param result defines the target matrix
  5808. */
  5809. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5810. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5811. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5812. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5813. result.setTranslation(translation);
  5814. };
  5815. /**
  5816. * Creates a new identity matrix
  5817. * @returns a new identity matrix
  5818. */
  5819. Matrix.Identity = function () {
  5820. 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);
  5821. };
  5822. /**
  5823. * Creates a new identity matrix and stores the result in a given matrix
  5824. * @param result defines the target matrix
  5825. */
  5826. Matrix.IdentityToRef = function (result) {
  5827. 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);
  5828. };
  5829. /**
  5830. * Creates a new zero matrix
  5831. * @returns a new zero matrix
  5832. */
  5833. Matrix.Zero = function () {
  5834. 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);
  5835. };
  5836. /**
  5837. * Creates a new rotation matrix for "angle" radians around the X axis
  5838. * @param angle defines the angle (in radians) to use
  5839. * @return the new matrix
  5840. */
  5841. Matrix.RotationX = function (angle) {
  5842. var result = new Matrix();
  5843. Matrix.RotationXToRef(angle, result);
  5844. return result;
  5845. };
  5846. /**
  5847. * Creates a new matrix as the invert of a given matrix
  5848. * @param source defines the source matrix
  5849. * @returns the new matrix
  5850. */
  5851. Matrix.Invert = function (source) {
  5852. var result = new Matrix();
  5853. source.invertToRef(result);
  5854. return result;
  5855. };
  5856. /**
  5857. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5858. * @param angle defines the angle (in radians) to use
  5859. * @param result defines the target matrix
  5860. */
  5861. Matrix.RotationXToRef = function (angle, result) {
  5862. var s = Math.sin(angle);
  5863. var c = Math.cos(angle);
  5864. result.m[0] = 1.0;
  5865. result.m[15] = 1.0;
  5866. result.m[5] = c;
  5867. result.m[10] = c;
  5868. result.m[9] = -s;
  5869. result.m[6] = s;
  5870. result.m[1] = 0.0;
  5871. result.m[2] = 0.0;
  5872. result.m[3] = 0.0;
  5873. result.m[4] = 0.0;
  5874. result.m[7] = 0.0;
  5875. result.m[8] = 0.0;
  5876. result.m[11] = 0.0;
  5877. result.m[12] = 0.0;
  5878. result.m[13] = 0.0;
  5879. result.m[14] = 0.0;
  5880. result._markAsUpdated();
  5881. };
  5882. /**
  5883. * Creates a new rotation matrix for "angle" radians around the Y axis
  5884. * @param angle defines the angle (in radians) to use
  5885. * @return the new matrix
  5886. */
  5887. Matrix.RotationY = function (angle) {
  5888. var result = new Matrix();
  5889. Matrix.RotationYToRef(angle, result);
  5890. return result;
  5891. };
  5892. /**
  5893. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5894. * @param angle defines the angle (in radians) to use
  5895. * @param result defines the target matrix
  5896. */
  5897. Matrix.RotationYToRef = function (angle, result) {
  5898. var s = Math.sin(angle);
  5899. var c = Math.cos(angle);
  5900. result.m[5] = 1.0;
  5901. result.m[15] = 1.0;
  5902. result.m[0] = c;
  5903. result.m[2] = -s;
  5904. result.m[8] = s;
  5905. result.m[10] = c;
  5906. result.m[1] = 0.0;
  5907. result.m[3] = 0.0;
  5908. result.m[4] = 0.0;
  5909. result.m[6] = 0.0;
  5910. result.m[7] = 0.0;
  5911. result.m[9] = 0.0;
  5912. result.m[11] = 0.0;
  5913. result.m[12] = 0.0;
  5914. result.m[13] = 0.0;
  5915. result.m[14] = 0.0;
  5916. result._markAsUpdated();
  5917. };
  5918. /**
  5919. * Creates a new rotation matrix for "angle" radians around the Z axis
  5920. * @param angle defines the angle (in radians) to use
  5921. * @return the new matrix
  5922. */
  5923. Matrix.RotationZ = function (angle) {
  5924. var result = new Matrix();
  5925. Matrix.RotationZToRef(angle, result);
  5926. return result;
  5927. };
  5928. /**
  5929. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5930. * @param angle defines the angle (in radians) to use
  5931. * @param result defines the target matrix
  5932. */
  5933. Matrix.RotationZToRef = function (angle, result) {
  5934. var s = Math.sin(angle);
  5935. var c = Math.cos(angle);
  5936. result.m[10] = 1.0;
  5937. result.m[15] = 1.0;
  5938. result.m[0] = c;
  5939. result.m[1] = s;
  5940. result.m[4] = -s;
  5941. result.m[5] = c;
  5942. result.m[2] = 0.0;
  5943. result.m[3] = 0.0;
  5944. result.m[6] = 0.0;
  5945. result.m[7] = 0.0;
  5946. result.m[8] = 0.0;
  5947. result.m[9] = 0.0;
  5948. result.m[11] = 0.0;
  5949. result.m[12] = 0.0;
  5950. result.m[13] = 0.0;
  5951. result.m[14] = 0.0;
  5952. result._markAsUpdated();
  5953. };
  5954. /**
  5955. * Creates a new rotation matrix for "angle" radians around the given axis
  5956. * @param axis defines the axis to use
  5957. * @param angle defines the angle (in radians) to use
  5958. * @return the new matrix
  5959. */
  5960. Matrix.RotationAxis = function (axis, angle) {
  5961. var result = Matrix.Zero();
  5962. Matrix.RotationAxisToRef(axis, angle, result);
  5963. return result;
  5964. };
  5965. /**
  5966. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5967. * @param axis defines the axis to use
  5968. * @param angle defines the angle (in radians) to use
  5969. * @param result defines the target matrix
  5970. */
  5971. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5972. var s = Math.sin(-angle);
  5973. var c = Math.cos(-angle);
  5974. var c1 = 1 - c;
  5975. axis.normalize();
  5976. result.m[0] = (axis.x * axis.x) * c1 + c;
  5977. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5978. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5979. result.m[3] = 0.0;
  5980. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5981. result.m[5] = (axis.y * axis.y) * c1 + c;
  5982. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5983. result.m[7] = 0.0;
  5984. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5985. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5986. result.m[10] = (axis.z * axis.z) * c1 + c;
  5987. result.m[11] = 0.0;
  5988. result.m[15] = 1.0;
  5989. result._markAsUpdated();
  5990. };
  5991. /**
  5992. * Creates a rotation matrix
  5993. * @param yaw defines the yaw angle in radians (Y axis)
  5994. * @param pitch defines the pitch angle in radians (X axis)
  5995. * @param roll defines the roll angle in radians (X axis)
  5996. * @returns the new rotation matrix
  5997. */
  5998. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5999. var result = new Matrix();
  6000. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6001. return result;
  6002. };
  6003. /**
  6004. * Creates a rotation matrix and stores it in a given matrix
  6005. * @param yaw defines the yaw angle in radians (Y axis)
  6006. * @param pitch defines the pitch angle in radians (X axis)
  6007. * @param roll defines the roll angle in radians (X axis)
  6008. * @param result defines the target matrix
  6009. */
  6010. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6011. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6012. this._tempQuaternion.toRotationMatrix(result);
  6013. };
  6014. /**
  6015. * Creates a scaling matrix
  6016. * @param x defines the scale factor on X axis
  6017. * @param y defines the scale factor on Y axis
  6018. * @param z defines the scale factor on Z axis
  6019. * @returns the new matrix
  6020. */
  6021. Matrix.Scaling = function (x, y, z) {
  6022. var result = Matrix.Zero();
  6023. Matrix.ScalingToRef(x, y, z, result);
  6024. return result;
  6025. };
  6026. /**
  6027. * Creates a scaling matrix and stores it in a given matrix
  6028. * @param x defines the scale factor on X axis
  6029. * @param y defines the scale factor on Y axis
  6030. * @param z defines the scale factor on Z axis
  6031. * @param result defines the target matrix
  6032. */
  6033. Matrix.ScalingToRef = function (x, y, z, result) {
  6034. result.m[0] = x;
  6035. result.m[1] = 0.0;
  6036. result.m[2] = 0.0;
  6037. result.m[3] = 0.0;
  6038. result.m[4] = 0.0;
  6039. result.m[5] = y;
  6040. result.m[6] = 0.0;
  6041. result.m[7] = 0.0;
  6042. result.m[8] = 0.0;
  6043. result.m[9] = 0.0;
  6044. result.m[10] = z;
  6045. result.m[11] = 0.0;
  6046. result.m[12] = 0.0;
  6047. result.m[13] = 0.0;
  6048. result.m[14] = 0.0;
  6049. result.m[15] = 1.0;
  6050. result._markAsUpdated();
  6051. };
  6052. /**
  6053. * Creates a translation matrix
  6054. * @param x defines the translation on X axis
  6055. * @param y defines the translation on Y axis
  6056. * @param z defines the translationon Z axis
  6057. * @returns the new matrix
  6058. */
  6059. Matrix.Translation = function (x, y, z) {
  6060. var result = Matrix.Identity();
  6061. Matrix.TranslationToRef(x, y, z, result);
  6062. return result;
  6063. };
  6064. /**
  6065. * Creates a translation matrix and stores it in a given matrix
  6066. * @param x defines the translation on X axis
  6067. * @param y defines the translation on Y axis
  6068. * @param z defines the translationon Z axis
  6069. * @param result defines the target matrix
  6070. */
  6071. Matrix.TranslationToRef = function (x, y, z, result) {
  6072. 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);
  6073. };
  6074. /**
  6075. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6076. * @param startValue defines the start value
  6077. * @param endValue defines the end value
  6078. * @param gradient defines the gradient factor
  6079. * @returns the new matrix
  6080. */
  6081. Matrix.Lerp = function (startValue, endValue, gradient) {
  6082. var result = Matrix.Zero();
  6083. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6084. return result;
  6085. };
  6086. /**
  6087. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6088. * @param startValue defines the start value
  6089. * @param endValue defines the end value
  6090. * @param gradient defines the gradient factor
  6091. * @param result defines the Matrix object where to store data
  6092. */
  6093. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6094. for (var index = 0; index < 16; index++) {
  6095. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6096. }
  6097. result._markAsUpdated();
  6098. };
  6099. /**
  6100. * Builds a new matrix whose values are computed by:
  6101. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6102. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6103. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6104. * @param startValue defines the first matrix
  6105. * @param endValue defines the second matrix
  6106. * @param gradient defines the gradient between the two matrices
  6107. * @returns the new matrix
  6108. */
  6109. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6110. var result = Matrix.Zero();
  6111. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6112. return result;
  6113. };
  6114. /**
  6115. * Update a matrix to values which are computed by:
  6116. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6117. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6118. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6119. * @param startValue defines the first matrix
  6120. * @param endValue defines the second matrix
  6121. * @param gradient defines the gradient between the two matrices
  6122. * @param result defines the target matrix
  6123. */
  6124. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6125. var startScale = MathTmp.Vector3[0];
  6126. var startRotation = MathTmp.Quaternion[0];
  6127. var startTranslation = MathTmp.Vector3[1];
  6128. startValue.decompose(startScale, startRotation, startTranslation);
  6129. var endScale = MathTmp.Vector3[2];
  6130. var endRotation = MathTmp.Quaternion[1];
  6131. var endTranslation = MathTmp.Vector3[3];
  6132. endValue.decompose(endScale, endRotation, endTranslation);
  6133. var resultScale = MathTmp.Vector3[4];
  6134. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6135. var resultRotation = MathTmp.Quaternion[2];
  6136. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6137. var resultTranslation = MathTmp.Vector3[5];
  6138. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6139. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6140. };
  6141. /**
  6142. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6143. * This function works in left handed mode
  6144. * @param eye defines the final position of the entity
  6145. * @param target defines where the entity should look at
  6146. * @param up defines the up vector for the entity
  6147. * @returns the new matrix
  6148. */
  6149. Matrix.LookAtLH = function (eye, target, up) {
  6150. var result = Matrix.Zero();
  6151. Matrix.LookAtLHToRef(eye, target, up, result);
  6152. return result;
  6153. };
  6154. /**
  6155. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6156. * This function works in left handed mode
  6157. * @param eye defines the final position of the entity
  6158. * @param target defines where the entity should look at
  6159. * @param up defines the up vector for the entity
  6160. * @param result defines the target matrix
  6161. */
  6162. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6163. // Z axis
  6164. target.subtractToRef(eye, this._zAxis);
  6165. this._zAxis.normalize();
  6166. // X axis
  6167. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6168. if (this._xAxis.lengthSquared() === 0) {
  6169. this._xAxis.x = 1.0;
  6170. }
  6171. else {
  6172. this._xAxis.normalize();
  6173. }
  6174. // Y axis
  6175. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6176. this._yAxis.normalize();
  6177. // Eye angles
  6178. var ex = -Vector3.Dot(this._xAxis, eye);
  6179. var ey = -Vector3.Dot(this._yAxis, eye);
  6180. var ez = -Vector3.Dot(this._zAxis, eye);
  6181. 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);
  6182. };
  6183. /**
  6184. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6185. * This function works in right handed mode
  6186. * @param eye defines the final position of the entity
  6187. * @param target defines where the entity should look at
  6188. * @param up defines the up vector for the entity
  6189. * @returns the new matrix
  6190. */
  6191. Matrix.LookAtRH = function (eye, target, up) {
  6192. var result = Matrix.Zero();
  6193. Matrix.LookAtRHToRef(eye, target, up, result);
  6194. return result;
  6195. };
  6196. /**
  6197. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6198. * This function works in right handed mode
  6199. * @param eye defines the final position of the entity
  6200. * @param target defines where the entity should look at
  6201. * @param up defines the up vector for the entity
  6202. * @param result defines the target matrix
  6203. */
  6204. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6205. // Z axis
  6206. eye.subtractToRef(target, this._zAxis);
  6207. this._zAxis.normalize();
  6208. // X axis
  6209. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6210. if (this._xAxis.lengthSquared() === 0) {
  6211. this._xAxis.x = 1.0;
  6212. }
  6213. else {
  6214. this._xAxis.normalize();
  6215. }
  6216. // Y axis
  6217. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6218. this._yAxis.normalize();
  6219. // Eye angles
  6220. var ex = -Vector3.Dot(this._xAxis, eye);
  6221. var ey = -Vector3.Dot(this._yAxis, eye);
  6222. var ez = -Vector3.Dot(this._zAxis, eye);
  6223. 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);
  6224. };
  6225. /**
  6226. * Create a left-handed orthographic projection matrix
  6227. * @param width defines the viewport width
  6228. * @param height defines the viewport height
  6229. * @param znear defines the near clip plane
  6230. * @param zfar defines the far clip plane
  6231. * @returns a new matrix as a left-handed orthographic projection matrix
  6232. */
  6233. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6234. var matrix = Matrix.Zero();
  6235. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6236. return matrix;
  6237. };
  6238. /**
  6239. * Store a left-handed orthographic projection to a given matrix
  6240. * @param width defines the viewport width
  6241. * @param height defines the viewport height
  6242. * @param znear defines the near clip plane
  6243. * @param zfar defines the far clip plane
  6244. * @param result defines the target matrix
  6245. */
  6246. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6247. var n = znear;
  6248. var f = zfar;
  6249. var a = 2.0 / width;
  6250. var b = 2.0 / height;
  6251. var c = 2.0 / (f - n);
  6252. var d = -(f + n) / (f - n);
  6253. 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);
  6254. };
  6255. /**
  6256. * Create a left-handed orthographic projection matrix
  6257. * @param left defines the viewport left coordinate
  6258. * @param right defines the viewport right coordinate
  6259. * @param bottom defines the viewport bottom coordinate
  6260. * @param top defines the viewport top coordinate
  6261. * @param znear defines the near clip plane
  6262. * @param zfar defines the far clip plane
  6263. * @returns a new matrix as a left-handed orthographic projection matrix
  6264. */
  6265. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6266. var matrix = Matrix.Zero();
  6267. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6268. return matrix;
  6269. };
  6270. /**
  6271. * Stores a left-handed orthographic projection into a given matrix
  6272. * @param left defines the viewport left coordinate
  6273. * @param right defines the viewport right coordinate
  6274. * @param bottom defines the viewport bottom coordinate
  6275. * @param top defines the viewport top coordinate
  6276. * @param znear defines the near clip plane
  6277. * @param zfar defines the far clip plane
  6278. * @param result defines the target matrix
  6279. */
  6280. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6281. var n = znear;
  6282. var f = zfar;
  6283. var a = 2.0 / (right - left);
  6284. var b = 2.0 / (top - bottom);
  6285. var c = 2.0 / (f - n);
  6286. var d = -(f + n) / (f - n);
  6287. var i0 = (left + right) / (left - right);
  6288. var i1 = (top + bottom) / (bottom - top);
  6289. 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);
  6290. };
  6291. /**
  6292. * Creates a right-handed orthographic projection matrix
  6293. * @param left defines the viewport left coordinate
  6294. * @param right defines the viewport right coordinate
  6295. * @param bottom defines the viewport bottom coordinate
  6296. * @param top defines the viewport top coordinate
  6297. * @param znear defines the near clip plane
  6298. * @param zfar defines the far clip plane
  6299. * @returns a new matrix as a right-handed orthographic projection matrix
  6300. */
  6301. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6302. var matrix = Matrix.Zero();
  6303. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6304. return matrix;
  6305. };
  6306. /**
  6307. * Stores a right-handed orthographic projection into a given matrix
  6308. * @param left defines the viewport left coordinate
  6309. * @param right defines the viewport right coordinate
  6310. * @param bottom defines the viewport bottom coordinate
  6311. * @param top defines the viewport top coordinate
  6312. * @param znear defines the near clip plane
  6313. * @param zfar defines the far clip plane
  6314. * @param result defines the target matrix
  6315. */
  6316. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6317. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6318. result.m[10] *= -1.0;
  6319. };
  6320. /**
  6321. * Creates a left-handed perspective projection matrix
  6322. * @param width defines the viewport width
  6323. * @param height defines the viewport height
  6324. * @param znear defines the near clip plane
  6325. * @param zfar defines the far clip plane
  6326. * @returns a new matrix as a left-handed perspective projection matrix
  6327. */
  6328. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6329. var matrix = Matrix.Zero();
  6330. var n = znear;
  6331. var f = zfar;
  6332. var a = 2.0 * n / width;
  6333. var b = 2.0 * n / height;
  6334. var c = (f + n) / (f - n);
  6335. var d = -2.0 * f * n / (f - n);
  6336. 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);
  6337. return matrix;
  6338. };
  6339. /**
  6340. * Creates a left-handed perspective projection matrix
  6341. * @param fov defines the horizontal field of view
  6342. * @param aspect defines the aspect ratio
  6343. * @param znear defines the near clip plane
  6344. * @param zfar defines the far clip plane
  6345. * @returns a new matrix as a left-handed perspective projection matrix
  6346. */
  6347. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6348. var matrix = Matrix.Zero();
  6349. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6350. return matrix;
  6351. };
  6352. /**
  6353. * Stores a left-handed perspective projection into a given matrix
  6354. * @param fov defines the horizontal field of view
  6355. * @param aspect defines the aspect ratio
  6356. * @param znear defines the near clip plane
  6357. * @param zfar defines the far clip plane
  6358. * @param result defines the target matrix
  6359. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6360. */
  6361. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6362. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6363. var n = znear;
  6364. var f = zfar;
  6365. var t = 1.0 / (Math.tan(fov * 0.5));
  6366. var a = isVerticalFovFixed ? (t / aspect) : t;
  6367. var b = isVerticalFovFixed ? t : (t * aspect);
  6368. var c = (f + n) / (f - n);
  6369. var d = -2.0 * f * n / (f - n);
  6370. 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);
  6371. };
  6372. /**
  6373. * Creates a right-handed perspective projection matrix
  6374. * @param fov defines the horizontal field of view
  6375. * @param aspect defines the aspect ratio
  6376. * @param znear defines the near clip plane
  6377. * @param zfar defines the far clip plane
  6378. * @returns a new matrix as a right-handed perspective projection matrix
  6379. */
  6380. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6381. var matrix = Matrix.Zero();
  6382. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6383. return matrix;
  6384. };
  6385. /**
  6386. * Stores a right-handed perspective projection into a given matrix
  6387. * @param fov defines the horizontal field of view
  6388. * @param aspect defines the aspect ratio
  6389. * @param znear defines the near clip plane
  6390. * @param zfar defines the far clip plane
  6391. * @param result defines the target matrix
  6392. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6393. */
  6394. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6395. //alternatively this could be expressed as:
  6396. // m = PerspectiveFovLHToRef
  6397. // m[10] *= -1.0;
  6398. // m[11] *= -1.0;
  6399. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6400. var n = znear;
  6401. var f = zfar;
  6402. var t = 1.0 / (Math.tan(fov * 0.5));
  6403. var a = isVerticalFovFixed ? (t / aspect) : t;
  6404. var b = isVerticalFovFixed ? t : (t * aspect);
  6405. var c = -(f + n) / (f - n);
  6406. var d = -2 * f * n / (f - n);
  6407. 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);
  6408. };
  6409. /**
  6410. * Stores a perspective projection for WebVR info a given matrix
  6411. * @param fov defines the field of view
  6412. * @param znear defines the near clip plane
  6413. * @param zfar defines the far clip plane
  6414. * @param result defines the target matrix
  6415. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6416. */
  6417. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6418. if (rightHanded === void 0) { rightHanded = false; }
  6419. var rightHandedFactor = rightHanded ? -1 : 1;
  6420. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6421. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6422. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6423. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6424. var xScale = 2.0 / (leftTan + rightTan);
  6425. var yScale = 2.0 / (upTan + downTan);
  6426. result.m[0] = xScale;
  6427. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6428. result.m[5] = yScale;
  6429. result.m[6] = result.m[7] = 0.0;
  6430. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6431. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6432. result.m[10] = -zfar / (znear - zfar);
  6433. result.m[11] = 1.0 * rightHandedFactor;
  6434. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6435. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6436. result._markAsUpdated();
  6437. };
  6438. /**
  6439. * Computes a complete transformation matrix
  6440. * @param viewport defines the viewport to use
  6441. * @param world defines the world matrix
  6442. * @param view defines the view matrix
  6443. * @param projection defines the projection matrix
  6444. * @param zmin defines the near clip plane
  6445. * @param zmax defines the far clip plane
  6446. * @returns the transformation matrix
  6447. */
  6448. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6449. var cw = viewport.width;
  6450. var ch = viewport.height;
  6451. var cx = viewport.x;
  6452. var cy = viewport.y;
  6453. 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);
  6454. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6455. };
  6456. /**
  6457. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6458. * @param matrix defines the matrix to use
  6459. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6460. */
  6461. Matrix.GetAsMatrix2x2 = function (matrix) {
  6462. return new Float32Array([
  6463. matrix.m[0], matrix.m[1],
  6464. matrix.m[4], matrix.m[5]
  6465. ]);
  6466. };
  6467. /**
  6468. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6469. * @param matrix defines the matrix to use
  6470. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6471. */
  6472. Matrix.GetAsMatrix3x3 = function (matrix) {
  6473. return new Float32Array([
  6474. matrix.m[0], matrix.m[1], matrix.m[2],
  6475. matrix.m[4], matrix.m[5], matrix.m[6],
  6476. matrix.m[8], matrix.m[9], matrix.m[10]
  6477. ]);
  6478. };
  6479. /**
  6480. * Compute the transpose of a given matrix
  6481. * @param matrix defines the matrix to transpose
  6482. * @returns the new matrix
  6483. */
  6484. Matrix.Transpose = function (matrix) {
  6485. var result = new Matrix();
  6486. Matrix.TransposeToRef(matrix, result);
  6487. return result;
  6488. };
  6489. /**
  6490. * Compute the transpose of a matrix and store it in a target matrix
  6491. * @param matrix defines the matrix to transpose
  6492. * @param result defines the target matrix
  6493. */
  6494. Matrix.TransposeToRef = function (matrix, result) {
  6495. result.m[0] = matrix.m[0];
  6496. result.m[1] = matrix.m[4];
  6497. result.m[2] = matrix.m[8];
  6498. result.m[3] = matrix.m[12];
  6499. result.m[4] = matrix.m[1];
  6500. result.m[5] = matrix.m[5];
  6501. result.m[6] = matrix.m[9];
  6502. result.m[7] = matrix.m[13];
  6503. result.m[8] = matrix.m[2];
  6504. result.m[9] = matrix.m[6];
  6505. result.m[10] = matrix.m[10];
  6506. result.m[11] = matrix.m[14];
  6507. result.m[12] = matrix.m[3];
  6508. result.m[13] = matrix.m[7];
  6509. result.m[14] = matrix.m[11];
  6510. result.m[15] = matrix.m[15];
  6511. };
  6512. /**
  6513. * Computes a reflection matrix from a plane
  6514. * @param plane defines the reflection plane
  6515. * @returns a new matrix
  6516. */
  6517. Matrix.Reflection = function (plane) {
  6518. var matrix = new Matrix();
  6519. Matrix.ReflectionToRef(plane, matrix);
  6520. return matrix;
  6521. };
  6522. /**
  6523. * Computes a reflection matrix from a plane
  6524. * @param plane defines the reflection plane
  6525. * @param result defines the target matrix
  6526. */
  6527. Matrix.ReflectionToRef = function (plane, result) {
  6528. plane.normalize();
  6529. var x = plane.normal.x;
  6530. var y = plane.normal.y;
  6531. var z = plane.normal.z;
  6532. var temp = -2 * x;
  6533. var temp2 = -2 * y;
  6534. var temp3 = -2 * z;
  6535. result.m[0] = (temp * x) + 1;
  6536. result.m[1] = temp2 * x;
  6537. result.m[2] = temp3 * x;
  6538. result.m[3] = 0.0;
  6539. result.m[4] = temp * y;
  6540. result.m[5] = (temp2 * y) + 1;
  6541. result.m[6] = temp3 * y;
  6542. result.m[7] = 0.0;
  6543. result.m[8] = temp * z;
  6544. result.m[9] = temp2 * z;
  6545. result.m[10] = (temp3 * z) + 1;
  6546. result.m[11] = 0.0;
  6547. result.m[12] = temp * plane.d;
  6548. result.m[13] = temp2 * plane.d;
  6549. result.m[14] = temp3 * plane.d;
  6550. result.m[15] = 1.0;
  6551. result._markAsUpdated();
  6552. };
  6553. /**
  6554. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6555. * @param xaxis defines the value of the 1st axis
  6556. * @param yaxis defines the value of the 2nd axis
  6557. * @param zaxis defines the value of the 3rd axis
  6558. * @param result defines the target matrix
  6559. */
  6560. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6561. result.m[0] = xaxis.x;
  6562. result.m[1] = xaxis.y;
  6563. result.m[2] = xaxis.z;
  6564. result.m[3] = 0.0;
  6565. result.m[4] = yaxis.x;
  6566. result.m[5] = yaxis.y;
  6567. result.m[6] = yaxis.z;
  6568. result.m[7] = 0.0;
  6569. result.m[8] = zaxis.x;
  6570. result.m[9] = zaxis.y;
  6571. result.m[10] = zaxis.z;
  6572. result.m[11] = 0.0;
  6573. result.m[12] = 0.0;
  6574. result.m[13] = 0.0;
  6575. result.m[14] = 0.0;
  6576. result.m[15] = 1.0;
  6577. result._markAsUpdated();
  6578. };
  6579. /**
  6580. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6581. * @param quat defines the quaternion to use
  6582. * @param result defines the target matrix
  6583. */
  6584. Matrix.FromQuaternionToRef = function (quat, result) {
  6585. var xx = quat.x * quat.x;
  6586. var yy = quat.y * quat.y;
  6587. var zz = quat.z * quat.z;
  6588. var xy = quat.x * quat.y;
  6589. var zw = quat.z * quat.w;
  6590. var zx = quat.z * quat.x;
  6591. var yw = quat.y * quat.w;
  6592. var yz = quat.y * quat.z;
  6593. var xw = quat.x * quat.w;
  6594. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6595. result.m[1] = 2.0 * (xy + zw);
  6596. result.m[2] = 2.0 * (zx - yw);
  6597. result.m[3] = 0.0;
  6598. result.m[4] = 2.0 * (xy - zw);
  6599. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6600. result.m[6] = 2.0 * (yz + xw);
  6601. result.m[7] = 0.0;
  6602. result.m[8] = 2.0 * (zx + yw);
  6603. result.m[9] = 2.0 * (yz - xw);
  6604. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6605. result.m[11] = 0.0;
  6606. result.m[12] = 0.0;
  6607. result.m[13] = 0.0;
  6608. result.m[14] = 0.0;
  6609. result.m[15] = 1.0;
  6610. result._markAsUpdated();
  6611. };
  6612. Matrix._tempQuaternion = new Quaternion();
  6613. Matrix._xAxis = Vector3.Zero();
  6614. Matrix._yAxis = Vector3.Zero();
  6615. Matrix._zAxis = Vector3.Zero();
  6616. Matrix._updateFlagSeed = 0;
  6617. Matrix._identityReadOnly = Matrix.Identity();
  6618. return Matrix;
  6619. }());
  6620. BABYLON.Matrix = Matrix;
  6621. var Plane = /** @class */ (function () {
  6622. /**
  6623. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6624. */
  6625. function Plane(a, b, c, d) {
  6626. this.normal = new Vector3(a, b, c);
  6627. this.d = d;
  6628. }
  6629. /**
  6630. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6631. */
  6632. Plane.prototype.asArray = function () {
  6633. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6634. };
  6635. // Methods
  6636. /**
  6637. * Returns a new plane copied from the current Plane.
  6638. */
  6639. Plane.prototype.clone = function () {
  6640. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6641. };
  6642. /**
  6643. * Returns the string "Plane".
  6644. */
  6645. Plane.prototype.getClassName = function () {
  6646. return "Plane";
  6647. };
  6648. /**
  6649. * Returns the Plane hash code.
  6650. */
  6651. Plane.prototype.getHashCode = function () {
  6652. var hash = this.normal.getHashCode();
  6653. hash = (hash * 397) ^ (this.d || 0);
  6654. return hash;
  6655. };
  6656. /**
  6657. * Normalize the current Plane in place.
  6658. * Returns the updated Plane.
  6659. */
  6660. Plane.prototype.normalize = function () {
  6661. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6662. var magnitude = 0.0;
  6663. if (norm !== 0) {
  6664. magnitude = 1.0 / norm;
  6665. }
  6666. this.normal.x *= magnitude;
  6667. this.normal.y *= magnitude;
  6668. this.normal.z *= magnitude;
  6669. this.d *= magnitude;
  6670. return this;
  6671. };
  6672. /**
  6673. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6674. */
  6675. Plane.prototype.transform = function (transformation) {
  6676. var transposedMatrix = Matrix.Transpose(transformation);
  6677. var x = this.normal.x;
  6678. var y = this.normal.y;
  6679. var z = this.normal.z;
  6680. var d = this.d;
  6681. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6682. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6683. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6684. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6685. return new Plane(normalX, normalY, normalZ, finalD);
  6686. };
  6687. /**
  6688. * Returns the dot product (float) of the point coordinates and the plane normal.
  6689. */
  6690. Plane.prototype.dotCoordinate = function (point) {
  6691. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6692. };
  6693. /**
  6694. * Updates the current Plane from the plane defined by the three given points.
  6695. * Returns the updated Plane.
  6696. */
  6697. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6698. var x1 = point2.x - point1.x;
  6699. var y1 = point2.y - point1.y;
  6700. var z1 = point2.z - point1.z;
  6701. var x2 = point3.x - point1.x;
  6702. var y2 = point3.y - point1.y;
  6703. var z2 = point3.z - point1.z;
  6704. var yz = (y1 * z2) - (z1 * y2);
  6705. var xz = (z1 * x2) - (x1 * z2);
  6706. var xy = (x1 * y2) - (y1 * x2);
  6707. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6708. var invPyth;
  6709. if (pyth !== 0) {
  6710. invPyth = 1.0 / pyth;
  6711. }
  6712. else {
  6713. invPyth = 0.0;
  6714. }
  6715. this.normal.x = yz * invPyth;
  6716. this.normal.y = xz * invPyth;
  6717. this.normal.z = xy * invPyth;
  6718. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6719. return this;
  6720. };
  6721. /**
  6722. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6723. */
  6724. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6725. var dot = Vector3.Dot(this.normal, direction);
  6726. return (dot <= epsilon);
  6727. };
  6728. /**
  6729. * Returns the signed distance (float) from the given point to the Plane.
  6730. */
  6731. Plane.prototype.signedDistanceTo = function (point) {
  6732. return Vector3.Dot(point, this.normal) + this.d;
  6733. };
  6734. // Statics
  6735. /**
  6736. * Returns a new Plane from the given array.
  6737. */
  6738. Plane.FromArray = function (array) {
  6739. return new Plane(array[0], array[1], array[2], array[3]);
  6740. };
  6741. /**
  6742. * Returns a new Plane defined by the three given points.
  6743. */
  6744. Plane.FromPoints = function (point1, point2, point3) {
  6745. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6746. result.copyFromPoints(point1, point2, point3);
  6747. return result;
  6748. };
  6749. /**
  6750. * Returns a new Plane the normal vector to this plane at the given origin point.
  6751. * Note : the vector "normal" is updated because normalized.
  6752. */
  6753. Plane.FromPositionAndNormal = function (origin, normal) {
  6754. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6755. normal.normalize();
  6756. result.normal = normal;
  6757. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6758. return result;
  6759. };
  6760. /**
  6761. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6762. */
  6763. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6764. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6765. return Vector3.Dot(point, normal) + d;
  6766. };
  6767. return Plane;
  6768. }());
  6769. BABYLON.Plane = Plane;
  6770. var Viewport = /** @class */ (function () {
  6771. /**
  6772. * Creates a Viewport object located at (x, y) and sized (width, height).
  6773. */
  6774. function Viewport(x, y, width, height) {
  6775. this.x = x;
  6776. this.y = y;
  6777. this.width = width;
  6778. this.height = height;
  6779. }
  6780. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6781. if (renderWidthOrEngine.getRenderWidth) {
  6782. var engine = renderWidthOrEngine;
  6783. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6784. }
  6785. var renderWidth = renderWidthOrEngine;
  6786. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6787. };
  6788. /**
  6789. * Returns a new Viewport copied from the current one.
  6790. */
  6791. Viewport.prototype.clone = function () {
  6792. return new Viewport(this.x, this.y, this.width, this.height);
  6793. };
  6794. return Viewport;
  6795. }());
  6796. BABYLON.Viewport = Viewport;
  6797. var Frustum = /** @class */ (function () {
  6798. function Frustum() {
  6799. }
  6800. /**
  6801. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6802. */
  6803. Frustum.GetPlanes = function (transform) {
  6804. var frustumPlanes = [];
  6805. for (var index = 0; index < 6; index++) {
  6806. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6807. }
  6808. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6809. return frustumPlanes;
  6810. };
  6811. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6812. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6813. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6814. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6815. frustumPlane.d = transform.m[15] + transform.m[14];
  6816. frustumPlane.normalize();
  6817. };
  6818. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6819. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6820. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6821. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6822. frustumPlane.d = transform.m[15] - transform.m[14];
  6823. frustumPlane.normalize();
  6824. };
  6825. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6826. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6827. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6828. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6829. frustumPlane.d = transform.m[15] + transform.m[12];
  6830. frustumPlane.normalize();
  6831. };
  6832. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6833. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6834. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6835. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6836. frustumPlane.d = transform.m[15] - transform.m[12];
  6837. frustumPlane.normalize();
  6838. };
  6839. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6840. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6841. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6842. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6843. frustumPlane.d = transform.m[15] - transform.m[13];
  6844. frustumPlane.normalize();
  6845. };
  6846. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6847. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6848. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6849. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6850. frustumPlane.d = transform.m[15] + transform.m[13];
  6851. frustumPlane.normalize();
  6852. };
  6853. /**
  6854. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6855. */
  6856. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6857. // Near
  6858. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6859. // Far
  6860. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6861. // Left
  6862. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6863. // Right
  6864. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6865. // Top
  6866. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6867. // Bottom
  6868. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6869. };
  6870. return Frustum;
  6871. }());
  6872. BABYLON.Frustum = Frustum;
  6873. /** Defines supported spaces */
  6874. var Space;
  6875. (function (Space) {
  6876. /** Local (object) space */
  6877. Space[Space["LOCAL"] = 0] = "LOCAL";
  6878. /** World space */
  6879. Space[Space["WORLD"] = 1] = "WORLD";
  6880. /** Bone space */
  6881. Space[Space["BONE"] = 2] = "BONE";
  6882. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6883. /** Defines the 3 main axes */
  6884. var Axis = /** @class */ (function () {
  6885. function Axis() {
  6886. }
  6887. /** X axis */
  6888. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6889. /** Y axis */
  6890. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6891. /** Z axis */
  6892. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6893. return Axis;
  6894. }());
  6895. BABYLON.Axis = Axis;
  6896. ;
  6897. var BezierCurve = /** @class */ (function () {
  6898. function BezierCurve() {
  6899. }
  6900. /**
  6901. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6902. */
  6903. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6904. // Extract X (which is equal to time here)
  6905. var f0 = 1 - 3 * x2 + 3 * x1;
  6906. var f1 = 3 * x2 - 6 * x1;
  6907. var f2 = 3 * x1;
  6908. var refinedT = t;
  6909. for (var i = 0; i < 5; i++) {
  6910. var refinedT2 = refinedT * refinedT;
  6911. var refinedT3 = refinedT2 * refinedT;
  6912. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6913. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6914. refinedT -= (x - t) * slope;
  6915. refinedT = Math.min(1, Math.max(0, refinedT));
  6916. }
  6917. // Resolve cubic bezier for the given x
  6918. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6919. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6920. Math.pow(refinedT, 3);
  6921. };
  6922. return BezierCurve;
  6923. }());
  6924. BABYLON.BezierCurve = BezierCurve;
  6925. /**
  6926. * Defines potential orientation for back face culling
  6927. */
  6928. var Orientation;
  6929. (function (Orientation) {
  6930. /**
  6931. * Clockwise
  6932. */
  6933. Orientation[Orientation["CW"] = 0] = "CW";
  6934. /** Counter clockwise */
  6935. Orientation[Orientation["CCW"] = 1] = "CCW";
  6936. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6937. /**
  6938. * Defines angle representation
  6939. */
  6940. var Angle = /** @class */ (function () {
  6941. /**
  6942. * Creates an Angle object of "radians" radians (float).
  6943. */
  6944. function Angle(radians) {
  6945. this._radians = radians;
  6946. if (this._radians < 0.0)
  6947. this._radians += (2.0 * Math.PI);
  6948. }
  6949. /**
  6950. * Get value in degrees
  6951. * @returns the Angle value in degrees (float)
  6952. */
  6953. Angle.prototype.degrees = function () {
  6954. return this._radians * 180.0 / Math.PI;
  6955. };
  6956. /**
  6957. * Get value in radians
  6958. * @returns the Angle value in radians (float)
  6959. */
  6960. Angle.prototype.radians = function () {
  6961. return this._radians;
  6962. };
  6963. /**
  6964. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6965. * @param a defines first vector
  6966. * @param b defines second vector
  6967. * @returns a new Angle
  6968. */
  6969. Angle.BetweenTwoPoints = function (a, b) {
  6970. var delta = b.subtract(a);
  6971. var theta = Math.atan2(delta.y, delta.x);
  6972. return new Angle(theta);
  6973. };
  6974. /**
  6975. * Gets a new Angle object from the given float in radians
  6976. * @param radians defines the angle value in radians
  6977. * @returns a new Angle
  6978. */
  6979. Angle.FromRadians = function (radians) {
  6980. return new Angle(radians);
  6981. };
  6982. /**
  6983. * Gets a new Angle object from the given float in degrees
  6984. * @param degrees defines the angle value in degrees
  6985. * @returns a new Angle
  6986. */
  6987. Angle.FromDegrees = function (degrees) {
  6988. return new Angle(degrees * Math.PI / 180.0);
  6989. };
  6990. return Angle;
  6991. }());
  6992. BABYLON.Angle = Angle;
  6993. var Arc2 = /** @class */ (function () {
  6994. /**
  6995. * Creates an Arc object from the three given points : start, middle and end.
  6996. */
  6997. function Arc2(startPoint, midPoint, endPoint) {
  6998. this.startPoint = startPoint;
  6999. this.midPoint = midPoint;
  7000. this.endPoint = endPoint;
  7001. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7002. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7003. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7004. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7005. 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);
  7006. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7007. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7008. var a1 = this.startAngle.degrees();
  7009. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7010. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7011. // angles correction
  7012. if (a2 - a1 > +180.0)
  7013. a2 -= 360.0;
  7014. if (a2 - a1 < -180.0)
  7015. a2 += 360.0;
  7016. if (a3 - a2 > +180.0)
  7017. a3 -= 360.0;
  7018. if (a3 - a2 < -180.0)
  7019. a3 += 360.0;
  7020. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7021. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7022. }
  7023. return Arc2;
  7024. }());
  7025. BABYLON.Arc2 = Arc2;
  7026. var Path2 = /** @class */ (function () {
  7027. /**
  7028. * Creates a Path2 object from the starting 2D coordinates x and y.
  7029. */
  7030. function Path2(x, y) {
  7031. this._points = new Array();
  7032. this._length = 0.0;
  7033. this.closed = false;
  7034. this._points.push(new Vector2(x, y));
  7035. }
  7036. /**
  7037. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7038. * Returns the updated Path2.
  7039. */
  7040. Path2.prototype.addLineTo = function (x, y) {
  7041. if (this.closed) {
  7042. return this;
  7043. }
  7044. var newPoint = new Vector2(x, y);
  7045. var previousPoint = this._points[this._points.length - 1];
  7046. this._points.push(newPoint);
  7047. this._length += newPoint.subtract(previousPoint).length();
  7048. return this;
  7049. };
  7050. /**
  7051. * 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.
  7052. * Returns the updated Path2.
  7053. */
  7054. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7055. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7056. if (this.closed) {
  7057. return this;
  7058. }
  7059. var startPoint = this._points[this._points.length - 1];
  7060. var midPoint = new Vector2(midX, midY);
  7061. var endPoint = new Vector2(endX, endY);
  7062. var arc = new Arc2(startPoint, midPoint, endPoint);
  7063. var increment = arc.angle.radians() / numberOfSegments;
  7064. if (arc.orientation === Orientation.CW)
  7065. increment *= -1;
  7066. var currentAngle = arc.startAngle.radians() + increment;
  7067. for (var i = 0; i < numberOfSegments; i++) {
  7068. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7069. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7070. this.addLineTo(x, y);
  7071. currentAngle += increment;
  7072. }
  7073. return this;
  7074. };
  7075. /**
  7076. * Closes the Path2.
  7077. * Returns the Path2.
  7078. */
  7079. Path2.prototype.close = function () {
  7080. this.closed = true;
  7081. return this;
  7082. };
  7083. /**
  7084. * Returns the Path2 total length (float).
  7085. */
  7086. Path2.prototype.length = function () {
  7087. var result = this._length;
  7088. if (!this.closed) {
  7089. var lastPoint = this._points[this._points.length - 1];
  7090. var firstPoint = this._points[0];
  7091. result += (firstPoint.subtract(lastPoint).length());
  7092. }
  7093. return result;
  7094. };
  7095. /**
  7096. * Returns the Path2 internal array of points.
  7097. */
  7098. Path2.prototype.getPoints = function () {
  7099. return this._points;
  7100. };
  7101. /**
  7102. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7103. */
  7104. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7105. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7106. return Vector2.Zero();
  7107. }
  7108. var lengthPosition = normalizedLengthPosition * this.length();
  7109. var previousOffset = 0;
  7110. for (var i = 0; i < this._points.length; i++) {
  7111. var j = (i + 1) % this._points.length;
  7112. var a = this._points[i];
  7113. var b = this._points[j];
  7114. var bToA = b.subtract(a);
  7115. var nextOffset = (bToA.length() + previousOffset);
  7116. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7117. var dir = bToA.normalize();
  7118. var localOffset = lengthPosition - previousOffset;
  7119. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7120. }
  7121. previousOffset = nextOffset;
  7122. }
  7123. return Vector2.Zero();
  7124. };
  7125. /**
  7126. * Returns a new Path2 starting at the coordinates (x, y).
  7127. */
  7128. Path2.StartingAt = function (x, y) {
  7129. return new Path2(x, y);
  7130. };
  7131. return Path2;
  7132. }());
  7133. BABYLON.Path2 = Path2;
  7134. var Path3D = /** @class */ (function () {
  7135. /**
  7136. * new Path3D(path, normal, raw)
  7137. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7138. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7139. * path : an array of Vector3, the curve axis of the Path3D
  7140. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7141. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7142. */
  7143. function Path3D(path, firstNormal, raw) {
  7144. if (firstNormal === void 0) { firstNormal = null; }
  7145. this.path = path;
  7146. this._curve = new Array();
  7147. this._distances = new Array();
  7148. this._tangents = new Array();
  7149. this._normals = new Array();
  7150. this._binormals = new Array();
  7151. for (var p = 0; p < path.length; p++) {
  7152. this._curve[p] = path[p].clone(); // hard copy
  7153. }
  7154. this._raw = raw || false;
  7155. this._compute(firstNormal);
  7156. }
  7157. /**
  7158. * Returns the Path3D array of successive Vector3 designing its curve.
  7159. */
  7160. Path3D.prototype.getCurve = function () {
  7161. return this._curve;
  7162. };
  7163. /**
  7164. * Returns an array populated with tangent vectors on each Path3D curve point.
  7165. */
  7166. Path3D.prototype.getTangents = function () {
  7167. return this._tangents;
  7168. };
  7169. /**
  7170. * Returns an array populated with normal vectors on each Path3D curve point.
  7171. */
  7172. Path3D.prototype.getNormals = function () {
  7173. return this._normals;
  7174. };
  7175. /**
  7176. * Returns an array populated with binormal vectors on each Path3D curve point.
  7177. */
  7178. Path3D.prototype.getBinormals = function () {
  7179. return this._binormals;
  7180. };
  7181. /**
  7182. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7183. */
  7184. Path3D.prototype.getDistances = function () {
  7185. return this._distances;
  7186. };
  7187. /**
  7188. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7189. * Returns the same object updated.
  7190. */
  7191. Path3D.prototype.update = function (path, firstNormal) {
  7192. if (firstNormal === void 0) { firstNormal = null; }
  7193. for (var p = 0; p < path.length; p++) {
  7194. this._curve[p].x = path[p].x;
  7195. this._curve[p].y = path[p].y;
  7196. this._curve[p].z = path[p].z;
  7197. }
  7198. this._compute(firstNormal);
  7199. return this;
  7200. };
  7201. // private function compute() : computes tangents, normals and binormals
  7202. Path3D.prototype._compute = function (firstNormal) {
  7203. var l = this._curve.length;
  7204. // first and last tangents
  7205. this._tangents[0] = this._getFirstNonNullVector(0);
  7206. if (!this._raw) {
  7207. this._tangents[0].normalize();
  7208. }
  7209. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7210. if (!this._raw) {
  7211. this._tangents[l - 1].normalize();
  7212. }
  7213. // normals and binormals at first point : arbitrary vector with _normalVector()
  7214. var tg0 = this._tangents[0];
  7215. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7216. this._normals[0] = pp0;
  7217. if (!this._raw) {
  7218. this._normals[0].normalize();
  7219. }
  7220. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7221. if (!this._raw) {
  7222. this._binormals[0].normalize();
  7223. }
  7224. this._distances[0] = 0.0;
  7225. // normals and binormals : next points
  7226. var prev; // previous vector (segment)
  7227. var cur; // current vector (segment)
  7228. var curTang; // current tangent
  7229. // previous normal
  7230. var prevBinor; // previous binormal
  7231. for (var i = 1; i < l; i++) {
  7232. // tangents
  7233. prev = this._getLastNonNullVector(i);
  7234. if (i < l - 1) {
  7235. cur = this._getFirstNonNullVector(i);
  7236. this._tangents[i] = prev.add(cur);
  7237. this._tangents[i].normalize();
  7238. }
  7239. this._distances[i] = this._distances[i - 1] + prev.length();
  7240. // normals and binormals
  7241. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7242. curTang = this._tangents[i];
  7243. prevBinor = this._binormals[i - 1];
  7244. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7245. if (!this._raw) {
  7246. this._normals[i].normalize();
  7247. }
  7248. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7249. if (!this._raw) {
  7250. this._binormals[i].normalize();
  7251. }
  7252. }
  7253. };
  7254. // private function getFirstNonNullVector(index)
  7255. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7256. Path3D.prototype._getFirstNonNullVector = function (index) {
  7257. var i = 1;
  7258. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7259. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7260. i++;
  7261. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7262. }
  7263. return nNVector;
  7264. };
  7265. // private function getLastNonNullVector(index)
  7266. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7267. Path3D.prototype._getLastNonNullVector = function (index) {
  7268. var i = 1;
  7269. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7270. while (nLVector.length() === 0 && index > i + 1) {
  7271. i++;
  7272. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7273. }
  7274. return nLVector;
  7275. };
  7276. // private function normalVector(v0, vt, va) :
  7277. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7278. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7279. Path3D.prototype._normalVector = function (v0, vt, va) {
  7280. var normal0;
  7281. var tgl = vt.length();
  7282. if (tgl === 0.0) {
  7283. tgl = 1.0;
  7284. }
  7285. if (va === undefined || va === null) {
  7286. var point;
  7287. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7288. point = new Vector3(0.0, -1.0, 0.0);
  7289. }
  7290. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7291. point = new Vector3(1.0, 0.0, 0.0);
  7292. }
  7293. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7294. point = new Vector3(0.0, 0.0, 1.0);
  7295. }
  7296. else {
  7297. point = Vector3.Zero();
  7298. }
  7299. normal0 = Vector3.Cross(vt, point);
  7300. }
  7301. else {
  7302. normal0 = Vector3.Cross(vt, va);
  7303. Vector3.CrossToRef(normal0, vt, normal0);
  7304. }
  7305. normal0.normalize();
  7306. return normal0;
  7307. };
  7308. return Path3D;
  7309. }());
  7310. BABYLON.Path3D = Path3D;
  7311. var Curve3 = /** @class */ (function () {
  7312. /**
  7313. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7314. * A Curve3 is designed from a series of successive Vector3.
  7315. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7316. */
  7317. function Curve3(points) {
  7318. this._length = 0.0;
  7319. this._points = points;
  7320. this._length = this._computeLength(points);
  7321. }
  7322. /**
  7323. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7324. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7325. * @param v1 (Vector3) the control point
  7326. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7327. * @param nbPoints (integer) the wanted number of points in the curve
  7328. */
  7329. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7330. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7331. var bez = new Array();
  7332. var equation = function (t, val0, val1, val2) {
  7333. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7334. return res;
  7335. };
  7336. for (var i = 0; i <= nbPoints; i++) {
  7337. 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)));
  7338. }
  7339. return new Curve3(bez);
  7340. };
  7341. /**
  7342. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7343. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7344. * @param v1 (Vector3) the first control point
  7345. * @param v2 (Vector3) the second control point
  7346. * @param v3 (Vector3) the end point of the Cubic Bezier
  7347. * @param nbPoints (integer) the wanted number of points in the curve
  7348. */
  7349. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7350. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7351. var bez = new Array();
  7352. var equation = function (t, val0, val1, val2, val3) {
  7353. 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;
  7354. return res;
  7355. };
  7356. for (var i = 0; i <= nbPoints; i++) {
  7357. 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)));
  7358. }
  7359. return new Curve3(bez);
  7360. };
  7361. /**
  7362. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7363. * @param p1 (Vector3) the origin point of the Hermite Spline
  7364. * @param t1 (Vector3) the tangent vector at the origin point
  7365. * @param p2 (Vector3) the end point of the Hermite Spline
  7366. * @param t2 (Vector3) the tangent vector at the end point
  7367. * @param nbPoints (integer) the wanted number of points in the curve
  7368. */
  7369. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7370. var hermite = new Array();
  7371. var step = 1.0 / nbPoints;
  7372. for (var i = 0; i <= nbPoints; i++) {
  7373. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7374. }
  7375. return new Curve3(hermite);
  7376. };
  7377. /**
  7378. * Returns a Curve3 object along a CatmullRom Spline curve :
  7379. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7380. * @param nbPoints (integer) the wanted number of points between each curve control points
  7381. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7382. */
  7383. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7384. var catmullRom = new Array();
  7385. var step = 1.0 / nbPoints;
  7386. var amount = 0.0;
  7387. if (closed) {
  7388. var pointsCount = points.length;
  7389. for (var i = 0; i < pointsCount; i++) {
  7390. amount = 0;
  7391. for (var c = 0; c < nbPoints; c++) {
  7392. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7393. amount += step;
  7394. }
  7395. }
  7396. catmullRom.push(catmullRom[0]);
  7397. }
  7398. else {
  7399. var totalPoints = new Array();
  7400. totalPoints.push(points[0].clone());
  7401. Array.prototype.push.apply(totalPoints, points);
  7402. totalPoints.push(points[points.length - 1].clone());
  7403. for (var i = 0; i < totalPoints.length - 3; i++) {
  7404. amount = 0;
  7405. for (var c = 0; c < nbPoints; c++) {
  7406. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7407. amount += step;
  7408. }
  7409. }
  7410. i--;
  7411. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7412. }
  7413. return new Curve3(catmullRom);
  7414. };
  7415. /**
  7416. * Returns the Curve3 stored array of successive Vector3
  7417. */
  7418. Curve3.prototype.getPoints = function () {
  7419. return this._points;
  7420. };
  7421. /**
  7422. * Returns the computed length (float) of the curve.
  7423. */
  7424. Curve3.prototype.length = function () {
  7425. return this._length;
  7426. };
  7427. /**
  7428. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7429. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7430. * curveA and curveB keep unchanged.
  7431. */
  7432. Curve3.prototype.continue = function (curve) {
  7433. var lastPoint = this._points[this._points.length - 1];
  7434. var continuedPoints = this._points.slice();
  7435. var curvePoints = curve.getPoints();
  7436. for (var i = 1; i < curvePoints.length; i++) {
  7437. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7438. }
  7439. var continuedCurve = new Curve3(continuedPoints);
  7440. return continuedCurve;
  7441. };
  7442. Curve3.prototype._computeLength = function (path) {
  7443. var l = 0;
  7444. for (var i = 1; i < path.length; i++) {
  7445. l += (path[i].subtract(path[i - 1])).length();
  7446. }
  7447. return l;
  7448. };
  7449. return Curve3;
  7450. }());
  7451. BABYLON.Curve3 = Curve3;
  7452. // Vertex formats
  7453. var PositionNormalVertex = /** @class */ (function () {
  7454. function PositionNormalVertex(position, normal) {
  7455. if (position === void 0) { position = Vector3.Zero(); }
  7456. if (normal === void 0) { normal = Vector3.Up(); }
  7457. this.position = position;
  7458. this.normal = normal;
  7459. }
  7460. PositionNormalVertex.prototype.clone = function () {
  7461. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7462. };
  7463. return PositionNormalVertex;
  7464. }());
  7465. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7466. var PositionNormalTextureVertex = /** @class */ (function () {
  7467. function PositionNormalTextureVertex(position, normal, uv) {
  7468. if (position === void 0) { position = Vector3.Zero(); }
  7469. if (normal === void 0) { normal = Vector3.Up(); }
  7470. if (uv === void 0) { uv = Vector2.Zero(); }
  7471. this.position = position;
  7472. this.normal = normal;
  7473. this.uv = uv;
  7474. }
  7475. PositionNormalTextureVertex.prototype.clone = function () {
  7476. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7477. };
  7478. return PositionNormalTextureVertex;
  7479. }());
  7480. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7481. // Temporary pre-allocated objects for engine internal use
  7482. // usage in any internal function :
  7483. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7484. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7485. var Tmp = /** @class */ (function () {
  7486. function Tmp() {
  7487. }
  7488. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7489. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7490. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7491. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7492. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7493. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7494. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7495. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7496. Matrix.Zero(), Matrix.Zero(),
  7497. Matrix.Zero(), Matrix.Zero(),
  7498. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7499. return Tmp;
  7500. }());
  7501. BABYLON.Tmp = Tmp;
  7502. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7503. var MathTmp = /** @class */ (function () {
  7504. function MathTmp() {
  7505. }
  7506. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7507. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7508. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7509. return MathTmp;
  7510. }());
  7511. })(BABYLON || (BABYLON = {}));
  7512. //# sourceMappingURL=babylon.math.js.map
  7513. var BABYLON;
  7514. (function (BABYLON) {
  7515. var Scalar = /** @class */ (function () {
  7516. function Scalar() {
  7517. }
  7518. /**
  7519. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7520. */
  7521. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7522. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7523. var num = a - b;
  7524. return -epsilon <= num && num <= epsilon;
  7525. };
  7526. /**
  7527. * Returns a string : the upper case translation of the number i to hexadecimal.
  7528. */
  7529. Scalar.ToHex = function (i) {
  7530. var str = i.toString(16);
  7531. if (i <= 15) {
  7532. return ("0" + str).toUpperCase();
  7533. }
  7534. return str.toUpperCase();
  7535. };
  7536. /**
  7537. * Returns -1 if value is negative and +1 is value is positive.
  7538. * Returns the value itself if it's equal to zero.
  7539. */
  7540. Scalar.Sign = function (value) {
  7541. value = +value; // convert to a number
  7542. if (value === 0 || isNaN(value))
  7543. return value;
  7544. return value > 0 ? 1 : -1;
  7545. };
  7546. /**
  7547. * Returns the value itself if it's between min and max.
  7548. * Returns min if the value is lower than min.
  7549. * Returns max if the value is greater than max.
  7550. */
  7551. Scalar.Clamp = function (value, min, max) {
  7552. if (min === void 0) { min = 0; }
  7553. if (max === void 0) { max = 1; }
  7554. return Math.min(max, Math.max(min, value));
  7555. };
  7556. /**
  7557. * Returns the log2 of value.
  7558. */
  7559. Scalar.Log2 = function (value) {
  7560. return Math.log(value) * Math.LOG2E;
  7561. };
  7562. /**
  7563. * Loops the value, so that it is never larger than length and never smaller than 0.
  7564. *
  7565. * This is similar to the modulo operator but it works with floating point numbers.
  7566. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7567. * With t = 5 and length = 2.5, the result would be 0.0.
  7568. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7569. */
  7570. Scalar.Repeat = function (value, length) {
  7571. return value - Math.floor(value / length) * length;
  7572. };
  7573. /**
  7574. * Normalize the value between 0.0 and 1.0 using min and max values
  7575. */
  7576. Scalar.Normalize = function (value, min, max) {
  7577. return (value - min) / (max - min);
  7578. };
  7579. /**
  7580. * Denormalize the value from 0.0 and 1.0 using min and max values
  7581. */
  7582. Scalar.Denormalize = function (normalized, min, max) {
  7583. return (normalized * (max - min) + min);
  7584. };
  7585. /**
  7586. * Calculates the shortest difference between two given angles given in degrees.
  7587. */
  7588. Scalar.DeltaAngle = function (current, target) {
  7589. var num = Scalar.Repeat(target - current, 360.0);
  7590. if (num > 180.0) {
  7591. num -= 360.0;
  7592. }
  7593. return num;
  7594. };
  7595. /**
  7596. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7597. *
  7598. * The returned value will move back and forth between 0 and length
  7599. */
  7600. Scalar.PingPong = function (tx, length) {
  7601. var t = Scalar.Repeat(tx, length * 2.0);
  7602. return length - Math.abs(t - length);
  7603. };
  7604. /**
  7605. * Interpolates between min and max with smoothing at the limits.
  7606. *
  7607. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7608. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7609. */
  7610. Scalar.SmoothStep = function (from, to, tx) {
  7611. var t = Scalar.Clamp(tx);
  7612. t = -2.0 * t * t * t + 3.0 * t * t;
  7613. return to * t + from * (1.0 - t);
  7614. };
  7615. /**
  7616. * Moves a value current towards target.
  7617. *
  7618. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7619. * Negative values of maxDelta pushes the value away from target.
  7620. */
  7621. Scalar.MoveTowards = function (current, target, maxDelta) {
  7622. var result = 0;
  7623. if (Math.abs(target - current) <= maxDelta) {
  7624. result = target;
  7625. }
  7626. else {
  7627. result = current + Scalar.Sign(target - current) * maxDelta;
  7628. }
  7629. return result;
  7630. };
  7631. /**
  7632. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7633. *
  7634. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7635. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7636. */
  7637. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7638. var num = Scalar.DeltaAngle(current, target);
  7639. var result = 0;
  7640. if (-maxDelta < num && num < maxDelta) {
  7641. result = target;
  7642. }
  7643. else {
  7644. target = current + num;
  7645. result = Scalar.MoveTowards(current, target, maxDelta);
  7646. }
  7647. return result;
  7648. };
  7649. /**
  7650. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7651. */
  7652. Scalar.Lerp = function (start, end, amount) {
  7653. return start + ((end - start) * amount);
  7654. };
  7655. /**
  7656. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7657. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7658. */
  7659. Scalar.LerpAngle = function (start, end, amount) {
  7660. var num = Scalar.Repeat(end - start, 360.0);
  7661. if (num > 180.0) {
  7662. num -= 360.0;
  7663. }
  7664. return start + num * Scalar.Clamp(amount);
  7665. };
  7666. /**
  7667. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7668. */
  7669. Scalar.InverseLerp = function (a, b, value) {
  7670. var result = 0;
  7671. if (a != b) {
  7672. result = Scalar.Clamp((value - a) / (b - a));
  7673. }
  7674. else {
  7675. result = 0.0;
  7676. }
  7677. return result;
  7678. };
  7679. /**
  7680. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7681. */
  7682. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7683. var squared = amount * amount;
  7684. var cubed = amount * squared;
  7685. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7686. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7687. var part3 = (cubed - (2.0 * squared)) + amount;
  7688. var part4 = cubed - squared;
  7689. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7690. };
  7691. /**
  7692. * Returns a random float number between and min and max values
  7693. */
  7694. Scalar.RandomRange = function (min, max) {
  7695. if (min === max)
  7696. return min;
  7697. return ((Math.random() * (max - min)) + min);
  7698. };
  7699. /**
  7700. * This function returns percentage of a number in a given range.
  7701. *
  7702. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7703. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7704. */
  7705. Scalar.RangeToPercent = function (number, min, max) {
  7706. return ((number - min) / (max - min));
  7707. };
  7708. /**
  7709. * This function returns number that corresponds to the percentage in a given range.
  7710. *
  7711. * PercentToRange(0.34,0,100) will return 34.
  7712. */
  7713. Scalar.PercentToRange = function (percent, min, max) {
  7714. return ((max - min) * percent + min);
  7715. };
  7716. /**
  7717. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7718. * @param angle The angle to normalize in radian.
  7719. * @return The converted angle.
  7720. */
  7721. Scalar.NormalizeRadians = function (angle) {
  7722. // More precise but slower version kept for reference.
  7723. // angle = angle % Tools.TwoPi;
  7724. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7725. //if (angle > Math.PI) {
  7726. // angle -= Tools.TwoPi;
  7727. //}
  7728. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7729. return angle;
  7730. };
  7731. /**
  7732. * Two pi constants convenient for computation.
  7733. */
  7734. Scalar.TwoPi = Math.PI * 2;
  7735. return Scalar;
  7736. }());
  7737. BABYLON.Scalar = Scalar;
  7738. })(BABYLON || (BABYLON = {}));
  7739. //# sourceMappingURL=babylon.math.scalar.js.map
  7740. //# sourceMappingURL=babylon.mixins.js.map
  7741. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7742. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7743. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7744. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7745. //# sourceMappingURL=babylon.webgl2.js.map
  7746. var BABYLON;
  7747. (function (BABYLON) {
  7748. var __decoratorInitialStore = {};
  7749. var __mergedStore = {};
  7750. var _copySource = function (creationFunction, source, instanciate) {
  7751. var destination = creationFunction();
  7752. // Tags
  7753. if (BABYLON.Tags) {
  7754. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7755. }
  7756. var classStore = getMergedStore(destination);
  7757. // Properties
  7758. for (var property in classStore) {
  7759. var propertyDescriptor = classStore[property];
  7760. var sourceProperty = source[property];
  7761. var propertyType = propertyDescriptor.type;
  7762. if (sourceProperty !== undefined && sourceProperty !== null) {
  7763. switch (propertyType) {
  7764. case 0: // Value
  7765. case 6: // Mesh reference
  7766. case 11: // Camera reference
  7767. destination[property] = sourceProperty;
  7768. break;
  7769. case 1: // Texture
  7770. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7771. break;
  7772. case 2: // Color3
  7773. case 3: // FresnelParameters
  7774. case 4: // Vector2
  7775. case 5: // Vector3
  7776. case 7: // Color Curves
  7777. case 10: // Quaternion
  7778. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7779. break;
  7780. }
  7781. }
  7782. }
  7783. return destination;
  7784. };
  7785. function getDirectStore(target) {
  7786. var classKey = target.getClassName();
  7787. if (!__decoratorInitialStore[classKey]) {
  7788. __decoratorInitialStore[classKey] = {};
  7789. }
  7790. return __decoratorInitialStore[classKey];
  7791. }
  7792. /**
  7793. * Return the list of properties flagged as serializable
  7794. * @param target: host object
  7795. */
  7796. function getMergedStore(target) {
  7797. var classKey = target.getClassName();
  7798. if (__mergedStore[classKey]) {
  7799. return __mergedStore[classKey];
  7800. }
  7801. __mergedStore[classKey] = {};
  7802. var store = __mergedStore[classKey];
  7803. var currentTarget = target;
  7804. var currentKey = classKey;
  7805. while (currentKey) {
  7806. var initialStore = __decoratorInitialStore[currentKey];
  7807. for (var property in initialStore) {
  7808. store[property] = initialStore[property];
  7809. }
  7810. var parent_1 = void 0;
  7811. var done = false;
  7812. do {
  7813. parent_1 = Object.getPrototypeOf(currentTarget);
  7814. if (!parent_1.getClassName) {
  7815. done = true;
  7816. break;
  7817. }
  7818. if (parent_1.getClassName() !== currentKey) {
  7819. break;
  7820. }
  7821. currentTarget = parent_1;
  7822. } while (parent_1);
  7823. if (done) {
  7824. break;
  7825. }
  7826. currentKey = parent_1.getClassName();
  7827. currentTarget = parent_1;
  7828. }
  7829. return store;
  7830. }
  7831. function generateSerializableMember(type, sourceName) {
  7832. return function (target, propertyKey) {
  7833. var classStore = getDirectStore(target);
  7834. if (!classStore[propertyKey]) {
  7835. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7836. }
  7837. };
  7838. }
  7839. function generateExpandMember(setCallback, targetKey) {
  7840. if (targetKey === void 0) { targetKey = null; }
  7841. return function (target, propertyKey) {
  7842. var key = targetKey || ("_" + propertyKey);
  7843. Object.defineProperty(target, propertyKey, {
  7844. get: function () {
  7845. return this[key];
  7846. },
  7847. set: function (value) {
  7848. if (this[key] === value) {
  7849. return;
  7850. }
  7851. this[key] = value;
  7852. target[setCallback].apply(this);
  7853. },
  7854. enumerable: true,
  7855. configurable: true
  7856. });
  7857. };
  7858. }
  7859. function expandToProperty(callback, targetKey) {
  7860. if (targetKey === void 0) { targetKey = null; }
  7861. return generateExpandMember(callback, targetKey);
  7862. }
  7863. BABYLON.expandToProperty = expandToProperty;
  7864. function serialize(sourceName) {
  7865. return generateSerializableMember(0, sourceName); // value member
  7866. }
  7867. BABYLON.serialize = serialize;
  7868. function serializeAsTexture(sourceName) {
  7869. return generateSerializableMember(1, sourceName); // texture member
  7870. }
  7871. BABYLON.serializeAsTexture = serializeAsTexture;
  7872. function serializeAsColor3(sourceName) {
  7873. return generateSerializableMember(2, sourceName); // color3 member
  7874. }
  7875. BABYLON.serializeAsColor3 = serializeAsColor3;
  7876. function serializeAsFresnelParameters(sourceName) {
  7877. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7878. }
  7879. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7880. function serializeAsVector2(sourceName) {
  7881. return generateSerializableMember(4, sourceName); // vector2 member
  7882. }
  7883. BABYLON.serializeAsVector2 = serializeAsVector2;
  7884. function serializeAsVector3(sourceName) {
  7885. return generateSerializableMember(5, sourceName); // vector3 member
  7886. }
  7887. BABYLON.serializeAsVector3 = serializeAsVector3;
  7888. function serializeAsMeshReference(sourceName) {
  7889. return generateSerializableMember(6, sourceName); // mesh reference member
  7890. }
  7891. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7892. function serializeAsColorCurves(sourceName) {
  7893. return generateSerializableMember(7, sourceName); // color curves
  7894. }
  7895. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7896. function serializeAsColor4(sourceName) {
  7897. return generateSerializableMember(8, sourceName); // color 4
  7898. }
  7899. BABYLON.serializeAsColor4 = serializeAsColor4;
  7900. function serializeAsImageProcessingConfiguration(sourceName) {
  7901. return generateSerializableMember(9, sourceName); // image processing
  7902. }
  7903. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7904. function serializeAsQuaternion(sourceName) {
  7905. return generateSerializableMember(10, sourceName); // quaternion member
  7906. }
  7907. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7908. /**
  7909. * Decorator used to define property that can be serialized as reference to a camera
  7910. * @param sourceName defines the name of the property to decorate
  7911. */
  7912. function serializeAsCameraReference(sourceName) {
  7913. return generateSerializableMember(11, sourceName); // camera reference member
  7914. }
  7915. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7916. var SerializationHelper = /** @class */ (function () {
  7917. function SerializationHelper() {
  7918. }
  7919. SerializationHelper.Serialize = function (entity, serializationObject) {
  7920. if (!serializationObject) {
  7921. serializationObject = {};
  7922. }
  7923. // Tags
  7924. if (BABYLON.Tags) {
  7925. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7926. }
  7927. var serializedProperties = getMergedStore(entity);
  7928. // Properties
  7929. for (var property in serializedProperties) {
  7930. var propertyDescriptor = serializedProperties[property];
  7931. var targetPropertyName = propertyDescriptor.sourceName || property;
  7932. var propertyType = propertyDescriptor.type;
  7933. var sourceProperty = entity[property];
  7934. if (sourceProperty !== undefined && sourceProperty !== null) {
  7935. switch (propertyType) {
  7936. case 0: // Value
  7937. serializationObject[targetPropertyName] = sourceProperty;
  7938. break;
  7939. case 1: // Texture
  7940. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7941. break;
  7942. case 2: // Color3
  7943. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7944. break;
  7945. case 3: // FresnelParameters
  7946. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7947. break;
  7948. case 4: // Vector2
  7949. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7950. break;
  7951. case 5: // Vector3
  7952. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7953. break;
  7954. case 6: // Mesh reference
  7955. serializationObject[targetPropertyName] = sourceProperty.id;
  7956. break;
  7957. case 7: // Color Curves
  7958. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7959. break;
  7960. case 8: // Color 4
  7961. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7962. break;
  7963. case 9: // Image Processing
  7964. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7965. break;
  7966. case 10: // Quaternion
  7967. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7968. break;
  7969. case 11: // Camera reference
  7970. serializationObject[targetPropertyName] = sourceProperty.id;
  7971. break;
  7972. }
  7973. }
  7974. }
  7975. return serializationObject;
  7976. };
  7977. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7978. if (rootUrl === void 0) { rootUrl = null; }
  7979. var destination = creationFunction();
  7980. if (!rootUrl) {
  7981. rootUrl = "";
  7982. }
  7983. // Tags
  7984. if (BABYLON.Tags) {
  7985. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7986. }
  7987. var classStore = getMergedStore(destination);
  7988. // Properties
  7989. for (var property in classStore) {
  7990. var propertyDescriptor = classStore[property];
  7991. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7992. var propertyType = propertyDescriptor.type;
  7993. if (sourceProperty !== undefined && sourceProperty !== null) {
  7994. var dest = destination;
  7995. switch (propertyType) {
  7996. case 0: // Value
  7997. dest[property] = sourceProperty;
  7998. break;
  7999. case 1: // Texture
  8000. if (scene) {
  8001. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8002. }
  8003. break;
  8004. case 2: // Color3
  8005. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8006. break;
  8007. case 3: // FresnelParameters
  8008. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8009. break;
  8010. case 4: // Vector2
  8011. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8012. break;
  8013. case 5: // Vector3
  8014. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8015. break;
  8016. case 6: // Mesh reference
  8017. if (scene) {
  8018. dest[property] = scene.getLastMeshByID(sourceProperty);
  8019. }
  8020. break;
  8021. case 7: // Color Curves
  8022. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8023. break;
  8024. case 8: // Color 4
  8025. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8026. break;
  8027. case 9: // Image Processing
  8028. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8029. break;
  8030. case 10: // Quaternion
  8031. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8032. break;
  8033. case 11: // Camera reference
  8034. if (scene) {
  8035. dest[property] = scene.getCameraByID(sourceProperty);
  8036. }
  8037. break;
  8038. }
  8039. }
  8040. }
  8041. return destination;
  8042. };
  8043. SerializationHelper.Clone = function (creationFunction, source) {
  8044. return _copySource(creationFunction, source, false);
  8045. };
  8046. SerializationHelper.Instanciate = function (creationFunction, source) {
  8047. return _copySource(creationFunction, source, true);
  8048. };
  8049. return SerializationHelper;
  8050. }());
  8051. BABYLON.SerializationHelper = SerializationHelper;
  8052. })(BABYLON || (BABYLON = {}));
  8053. //# sourceMappingURL=babylon.decorators.js.map
  8054. var BABYLON;
  8055. (function (BABYLON) {
  8056. /**
  8057. * Wrapper class for promise with external resolve and reject.
  8058. */
  8059. var Deferred = /** @class */ (function () {
  8060. /**
  8061. * Constructor for this deferred object.
  8062. */
  8063. function Deferred() {
  8064. var _this = this;
  8065. this.promise = new Promise(function (resolve, reject) {
  8066. _this._resolve = resolve;
  8067. _this._reject = reject;
  8068. });
  8069. }
  8070. Object.defineProperty(Deferred.prototype, "resolve", {
  8071. /**
  8072. * The resolve method of the promise associated with this deferred object.
  8073. */
  8074. get: function () {
  8075. return this._resolve;
  8076. },
  8077. enumerable: true,
  8078. configurable: true
  8079. });
  8080. Object.defineProperty(Deferred.prototype, "reject", {
  8081. /**
  8082. * The reject method of the promise associated with this deferred object.
  8083. */
  8084. get: function () {
  8085. return this._reject;
  8086. },
  8087. enumerable: true,
  8088. configurable: true
  8089. });
  8090. return Deferred;
  8091. }());
  8092. BABYLON.Deferred = Deferred;
  8093. })(BABYLON || (BABYLON = {}));
  8094. //# sourceMappingURL=babylon.deferred.js.map
  8095. var BABYLON;
  8096. (function (BABYLON) {
  8097. /**
  8098. * A class serves as a medium between the observable and its observers
  8099. */
  8100. var EventState = /** @class */ (function () {
  8101. /**
  8102. * Create a new EventState
  8103. * @param mask defines the mask associated with this state
  8104. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8105. * @param target defines the original target of the state
  8106. * @param currentTarget defines the current target of the state
  8107. */
  8108. function EventState(mask, skipNextObservers, target, currentTarget) {
  8109. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8110. this.initalize(mask, skipNextObservers, target, currentTarget);
  8111. }
  8112. /**
  8113. * Initialize the current event state
  8114. * @param mask defines the mask associated with this state
  8115. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8116. * @param target defines the original target of the state
  8117. * @param currentTarget defines the current target of the state
  8118. * @returns the current event state
  8119. */
  8120. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8121. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8122. this.mask = mask;
  8123. this.skipNextObservers = skipNextObservers;
  8124. this.target = target;
  8125. this.currentTarget = currentTarget;
  8126. return this;
  8127. };
  8128. return EventState;
  8129. }());
  8130. BABYLON.EventState = EventState;
  8131. /**
  8132. * Represent an Observer registered to a given Observable object.
  8133. */
  8134. var Observer = /** @class */ (function () {
  8135. /**
  8136. * Creates a new observer
  8137. * @param callback defines the callback to call when the observer is notified
  8138. * @param mask defines the mask of the observer (used to filter notifications)
  8139. * @param scope defines the current scope used to restore the JS context
  8140. */
  8141. function Observer(
  8142. /**
  8143. * Defines the callback to call when the observer is notified
  8144. */
  8145. callback,
  8146. /**
  8147. * Defines the mask of the observer (used to filter notifications)
  8148. */
  8149. mask,
  8150. /**
  8151. * Defines the current scope used to restore the JS context
  8152. */
  8153. scope) {
  8154. if (scope === void 0) { scope = null; }
  8155. this.callback = callback;
  8156. this.mask = mask;
  8157. this.scope = scope;
  8158. /** @hidden */
  8159. this._willBeUnregistered = false;
  8160. /**
  8161. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8162. */
  8163. this.unregisterOnNextCall = false;
  8164. }
  8165. return Observer;
  8166. }());
  8167. BABYLON.Observer = Observer;
  8168. /**
  8169. * Represent a list of observers registered to multiple Observables object.
  8170. */
  8171. var MultiObserver = /** @class */ (function () {
  8172. function MultiObserver() {
  8173. }
  8174. /**
  8175. * Release associated resources
  8176. */
  8177. MultiObserver.prototype.dispose = function () {
  8178. if (this._observers && this._observables) {
  8179. for (var index = 0; index < this._observers.length; index++) {
  8180. this._observables[index].remove(this._observers[index]);
  8181. }
  8182. }
  8183. this._observers = null;
  8184. this._observables = null;
  8185. };
  8186. /**
  8187. * Raise a callback when one of the observable will notify
  8188. * @param observables defines a list of observables to watch
  8189. * @param callback defines the callback to call on notification
  8190. * @param mask defines the mask used to filter notifications
  8191. * @param scope defines the current scope used to restore the JS context
  8192. * @returns the new MultiObserver
  8193. */
  8194. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8195. if (mask === void 0) { mask = -1; }
  8196. if (scope === void 0) { scope = null; }
  8197. var result = new MultiObserver();
  8198. result._observers = new Array();
  8199. result._observables = observables;
  8200. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8201. var observable = observables_1[_i];
  8202. var observer = observable.add(callback, mask, false, scope);
  8203. if (observer) {
  8204. result._observers.push(observer);
  8205. }
  8206. }
  8207. return result;
  8208. };
  8209. return MultiObserver;
  8210. }());
  8211. BABYLON.MultiObserver = MultiObserver;
  8212. /**
  8213. * The Observable class is a simple implementation of the Observable pattern.
  8214. *
  8215. * 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.
  8216. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8217. * 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).
  8218. * 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.
  8219. */
  8220. var Observable = /** @class */ (function () {
  8221. /**
  8222. * Creates a new observable
  8223. * @param onObserverAdded defines a callback to call when a new observer is added
  8224. */
  8225. function Observable(onObserverAdded) {
  8226. this._observers = new Array();
  8227. this._eventState = new EventState(0);
  8228. if (onObserverAdded) {
  8229. this._onObserverAdded = onObserverAdded;
  8230. }
  8231. }
  8232. /**
  8233. * Create a new Observer with the specified callback
  8234. * @param callback the callback that will be executed for that Observer
  8235. * @param mask the mask used to filter observers
  8236. * @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.
  8237. * @param scope optional scope for the callback to be called from
  8238. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8239. * @returns the new observer created for the callback
  8240. */
  8241. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8242. if (mask === void 0) { mask = -1; }
  8243. if (insertFirst === void 0) { insertFirst = false; }
  8244. if (scope === void 0) { scope = null; }
  8245. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8246. if (!callback) {
  8247. return null;
  8248. }
  8249. var observer = new Observer(callback, mask, scope);
  8250. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8251. if (insertFirst) {
  8252. this._observers.unshift(observer);
  8253. }
  8254. else {
  8255. this._observers.push(observer);
  8256. }
  8257. if (this._onObserverAdded) {
  8258. this._onObserverAdded(observer);
  8259. }
  8260. return observer;
  8261. };
  8262. /**
  8263. * Create a new Observer with the specified callback and unregisters after the next notification
  8264. * @param callback the callback that will be executed for that Observer
  8265. * @returns the new observer created for the callback
  8266. */
  8267. Observable.prototype.addOnce = function (callback) {
  8268. return this.add(callback, undefined, undefined, undefined, true);
  8269. };
  8270. /**
  8271. * Remove an Observer from the Observable object
  8272. * @param observer the instance of the Observer to remove
  8273. * @returns false if it doesn't belong to this Observable
  8274. */
  8275. Observable.prototype.remove = function (observer) {
  8276. if (!observer) {
  8277. return false;
  8278. }
  8279. var index = this._observers.indexOf(observer);
  8280. if (index !== -1) {
  8281. this._deferUnregister(observer);
  8282. return true;
  8283. }
  8284. return false;
  8285. };
  8286. /**
  8287. * Remove a callback from the Observable object
  8288. * @param callback the callback to remove
  8289. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8290. * @returns false if it doesn't belong to this Observable
  8291. */
  8292. Observable.prototype.removeCallback = function (callback, scope) {
  8293. for (var index = 0; index < this._observers.length; index++) {
  8294. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8295. this._deferUnregister(this._observers[index]);
  8296. return true;
  8297. }
  8298. }
  8299. return false;
  8300. };
  8301. Observable.prototype._deferUnregister = function (observer) {
  8302. var _this = this;
  8303. observer.unregisterOnNextCall = false;
  8304. observer._willBeUnregistered = true;
  8305. BABYLON.Tools.SetImmediate(function () {
  8306. _this._remove(observer);
  8307. });
  8308. };
  8309. // This should only be called when not iterating over _observers to avoid callback skipping.
  8310. // Removes an observer from the _observer Array.
  8311. Observable.prototype._remove = function (observer) {
  8312. if (!observer) {
  8313. return false;
  8314. }
  8315. var index = this._observers.indexOf(observer);
  8316. if (index !== -1) {
  8317. this._observers.splice(index, 1);
  8318. return true;
  8319. }
  8320. return false;
  8321. };
  8322. /**
  8323. * Notify all Observers by calling their respective callback with the given data
  8324. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8325. * @param eventData defines the data to send to all observers
  8326. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8327. * @param target defines the original target of the state
  8328. * @param currentTarget defines the current target of the state
  8329. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8330. */
  8331. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8332. if (mask === void 0) { mask = -1; }
  8333. if (!this._observers.length) {
  8334. return true;
  8335. }
  8336. var state = this._eventState;
  8337. state.mask = mask;
  8338. state.target = target;
  8339. state.currentTarget = currentTarget;
  8340. state.skipNextObservers = false;
  8341. state.lastReturnValue = eventData;
  8342. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8343. var obs = _a[_i];
  8344. if (obs._willBeUnregistered) {
  8345. continue;
  8346. }
  8347. if (obs.mask & mask) {
  8348. if (obs.scope) {
  8349. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8350. }
  8351. else {
  8352. state.lastReturnValue = obs.callback(eventData, state);
  8353. }
  8354. if (obs.unregisterOnNextCall) {
  8355. this._deferUnregister(obs);
  8356. }
  8357. }
  8358. if (state.skipNextObservers) {
  8359. return false;
  8360. }
  8361. }
  8362. return true;
  8363. };
  8364. /**
  8365. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8366. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8367. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8368. * and it is crucial that all callbacks will be executed.
  8369. * The order of the callbacks is kept, callbacks are not executed parallel.
  8370. *
  8371. * @param eventData The data to be sent to each callback
  8372. * @param mask is used to filter observers defaults to -1
  8373. * @param target defines the callback target (see EventState)
  8374. * @param currentTarget defines he current object in the bubbling phase
  8375. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8376. */
  8377. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8378. var _this = this;
  8379. if (mask === void 0) { mask = -1; }
  8380. // create an empty promise
  8381. var p = Promise.resolve(eventData);
  8382. // no observers? return this promise.
  8383. if (!this._observers.length) {
  8384. return p;
  8385. }
  8386. var state = this._eventState;
  8387. state.mask = mask;
  8388. state.target = target;
  8389. state.currentTarget = currentTarget;
  8390. state.skipNextObservers = false;
  8391. // execute one callback after another (not using Promise.all, the order is important)
  8392. this._observers.forEach(function (obs) {
  8393. if (state.skipNextObservers) {
  8394. return;
  8395. }
  8396. if (obs._willBeUnregistered) {
  8397. return;
  8398. }
  8399. if (obs.mask & mask) {
  8400. if (obs.scope) {
  8401. p = p.then(function (lastReturnedValue) {
  8402. state.lastReturnValue = lastReturnedValue;
  8403. return obs.callback.apply(obs.scope, [eventData, state]);
  8404. });
  8405. }
  8406. else {
  8407. p = p.then(function (lastReturnedValue) {
  8408. state.lastReturnValue = lastReturnedValue;
  8409. return obs.callback(eventData, state);
  8410. });
  8411. }
  8412. if (obs.unregisterOnNextCall) {
  8413. _this._deferUnregister(obs);
  8414. }
  8415. }
  8416. });
  8417. // return the eventData
  8418. return p.then(function () { return eventData; });
  8419. };
  8420. /**
  8421. * Notify a specific observer
  8422. * @param observer defines the observer to notify
  8423. * @param eventData defines the data to be sent to each callback
  8424. * @param mask is used to filter observers defaults to -1
  8425. */
  8426. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8427. if (mask === void 0) { mask = -1; }
  8428. var state = this._eventState;
  8429. state.mask = mask;
  8430. state.skipNextObservers = false;
  8431. observer.callback(eventData, state);
  8432. };
  8433. /**
  8434. * Gets a boolean indicating if the observable has at least one observer
  8435. * @returns true is the Observable has at least one Observer registered
  8436. */
  8437. Observable.prototype.hasObservers = function () {
  8438. return this._observers.length > 0;
  8439. };
  8440. /**
  8441. * Clear the list of observers
  8442. */
  8443. Observable.prototype.clear = function () {
  8444. this._observers = new Array();
  8445. this._onObserverAdded = null;
  8446. };
  8447. /**
  8448. * Clone the current observable
  8449. * @returns a new observable
  8450. */
  8451. Observable.prototype.clone = function () {
  8452. var result = new Observable();
  8453. result._observers = this._observers.slice(0);
  8454. return result;
  8455. };
  8456. /**
  8457. * Does this observable handles observer registered with a given mask
  8458. * @param mask defines the mask to be tested
  8459. * @return whether or not one observer registered with the given mask is handeled
  8460. **/
  8461. Observable.prototype.hasSpecificMask = function (mask) {
  8462. if (mask === void 0) { mask = -1; }
  8463. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8464. var obs = _a[_i];
  8465. if (obs.mask & mask || obs.mask === mask) {
  8466. return true;
  8467. }
  8468. }
  8469. return false;
  8470. };
  8471. return Observable;
  8472. }());
  8473. BABYLON.Observable = Observable;
  8474. })(BABYLON || (BABYLON = {}));
  8475. //# sourceMappingURL=babylon.observable.js.map
  8476. var BABYLON;
  8477. (function (BABYLON) {
  8478. /**
  8479. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8480. */
  8481. var SmartArray = /** @class */ (function () {
  8482. /**
  8483. * Instantiates a Smart Array.
  8484. * @param capacity defines the default capacity of the array.
  8485. */
  8486. function SmartArray(capacity) {
  8487. /**
  8488. * The active length of the array.
  8489. */
  8490. this.length = 0;
  8491. this.data = new Array(capacity);
  8492. this._id = SmartArray._GlobalId++;
  8493. }
  8494. /**
  8495. * Pushes a value at the end of the active data.
  8496. * @param value defines the object to push in the array.
  8497. */
  8498. SmartArray.prototype.push = function (value) {
  8499. this.data[this.length++] = value;
  8500. if (this.length > this.data.length) {
  8501. this.data.length *= 2;
  8502. }
  8503. };
  8504. /**
  8505. * Iterates over the active data and apply the lambda to them.
  8506. * @param func defines the action to apply on each value.
  8507. */
  8508. SmartArray.prototype.forEach = function (func) {
  8509. for (var index = 0; index < this.length; index++) {
  8510. func(this.data[index]);
  8511. }
  8512. };
  8513. /**
  8514. * Sorts the full sets of data.
  8515. * @param compareFn defines the comparison function to apply.
  8516. */
  8517. SmartArray.prototype.sort = function (compareFn) {
  8518. this.data.sort(compareFn);
  8519. };
  8520. /**
  8521. * Resets the active data to an empty array.
  8522. */
  8523. SmartArray.prototype.reset = function () {
  8524. this.length = 0;
  8525. };
  8526. /**
  8527. * Releases all the data from the array as well as the array.
  8528. */
  8529. SmartArray.prototype.dispose = function () {
  8530. this.reset();
  8531. if (this.data) {
  8532. this.data.length = 0;
  8533. this.data = [];
  8534. }
  8535. };
  8536. /**
  8537. * Concats the active data with a given array.
  8538. * @param array defines the data to concatenate with.
  8539. */
  8540. SmartArray.prototype.concat = function (array) {
  8541. if (array.length === 0) {
  8542. return;
  8543. }
  8544. if (this.length + array.length > this.data.length) {
  8545. this.data.length = (this.length + array.length) * 2;
  8546. }
  8547. for (var index = 0; index < array.length; index++) {
  8548. this.data[this.length++] = (array.data || array)[index];
  8549. }
  8550. };
  8551. /**
  8552. * Returns the position of a value in the active data.
  8553. * @param value defines the value to find the index for
  8554. * @returns the index if found in the active data otherwise -1
  8555. */
  8556. SmartArray.prototype.indexOf = function (value) {
  8557. var position = this.data.indexOf(value);
  8558. if (position >= this.length) {
  8559. return -1;
  8560. }
  8561. return position;
  8562. };
  8563. /**
  8564. * Returns whether an element is part of the active data.
  8565. * @param value defines the value to look for
  8566. * @returns true if found in the active data otherwise false
  8567. */
  8568. SmartArray.prototype.contains = function (value) {
  8569. return this.indexOf(value) !== -1;
  8570. };
  8571. // Statics
  8572. SmartArray._GlobalId = 0;
  8573. return SmartArray;
  8574. }());
  8575. BABYLON.SmartArray = SmartArray;
  8576. /**
  8577. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8578. * The data in this array can only be present once
  8579. */
  8580. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8581. __extends(SmartArrayNoDuplicate, _super);
  8582. function SmartArrayNoDuplicate() {
  8583. var _this = _super !== null && _super.apply(this, arguments) || this;
  8584. _this._duplicateId = 0;
  8585. return _this;
  8586. }
  8587. /**
  8588. * Pushes a value at the end of the active data.
  8589. * THIS DOES NOT PREVENT DUPPLICATE DATA
  8590. * @param value defines the object to push in the array.
  8591. */
  8592. SmartArrayNoDuplicate.prototype.push = function (value) {
  8593. _super.prototype.push.call(this, value);
  8594. if (!value.__smartArrayFlags) {
  8595. value.__smartArrayFlags = {};
  8596. }
  8597. value.__smartArrayFlags[this._id] = this._duplicateId;
  8598. };
  8599. /**
  8600. * Pushes a value at the end of the active data.
  8601. * If the data is already present, it won t be added again
  8602. * @param value defines the object to push in the array.
  8603. * @returns true if added false if it was already present
  8604. */
  8605. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8606. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8607. return false;
  8608. }
  8609. this.push(value);
  8610. return true;
  8611. };
  8612. /**
  8613. * Resets the active data to an empty array.
  8614. */
  8615. SmartArrayNoDuplicate.prototype.reset = function () {
  8616. _super.prototype.reset.call(this);
  8617. this._duplicateId++;
  8618. };
  8619. /**
  8620. * Concats the active data with a given array.
  8621. * This ensures no dupplicate will be present in the result.
  8622. * @param array defines the data to concatenate with.
  8623. */
  8624. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8625. if (array.length === 0) {
  8626. return;
  8627. }
  8628. if (this.length + array.length > this.data.length) {
  8629. this.data.length = (this.length + array.length) * 2;
  8630. }
  8631. for (var index = 0; index < array.length; index++) {
  8632. var item = (array.data || array)[index];
  8633. this.pushNoDuplicate(item);
  8634. }
  8635. };
  8636. return SmartArrayNoDuplicate;
  8637. }(SmartArray));
  8638. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8639. })(BABYLON || (BABYLON = {}));
  8640. //# sourceMappingURL=babylon.smartArray.js.map
  8641. var BABYLON;
  8642. (function (BABYLON) {
  8643. /** Class used to store color4 gradient */
  8644. var ColorGradient = /** @class */ (function () {
  8645. function ColorGradient() {
  8646. }
  8647. /**
  8648. * Will get a color picked randomly between color1 and color2.
  8649. * If color2 is undefined then color1 will be used
  8650. * @param result defines the target Color4 to store the result in
  8651. */
  8652. ColorGradient.prototype.getColorToRef = function (result) {
  8653. if (!this.color2) {
  8654. result.copyFrom(this.color1);
  8655. return;
  8656. }
  8657. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8658. };
  8659. return ColorGradient;
  8660. }());
  8661. BABYLON.ColorGradient = ColorGradient;
  8662. /** Class used to store color 3 gradient */
  8663. var Color3Gradient = /** @class */ (function () {
  8664. function Color3Gradient() {
  8665. }
  8666. return Color3Gradient;
  8667. }());
  8668. BABYLON.Color3Gradient = Color3Gradient;
  8669. /** Class used to store factor gradient */
  8670. var FactorGradient = /** @class */ (function () {
  8671. function FactorGradient() {
  8672. }
  8673. /**
  8674. * Will get a number picked randomly between factor1 and factor2.
  8675. * If factor2 is undefined then factor1 will be used
  8676. * @returns the picked number
  8677. */
  8678. FactorGradient.prototype.getFactor = function () {
  8679. if (this.factor2 === undefined) {
  8680. return this.factor1;
  8681. }
  8682. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8683. };
  8684. return FactorGradient;
  8685. }());
  8686. BABYLON.FactorGradient = FactorGradient;
  8687. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8688. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8689. var LoadFileError = /** @class */ (function (_super) {
  8690. __extends(LoadFileError, _super);
  8691. function LoadFileError(message, request) {
  8692. var _this = _super.call(this, message) || this;
  8693. _this.request = request;
  8694. _this.name = "LoadFileError";
  8695. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8696. return _this;
  8697. }
  8698. // Polyfill for Object.setPrototypeOf if necessary.
  8699. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8700. return LoadFileError;
  8701. }(Error));
  8702. BABYLON.LoadFileError = LoadFileError;
  8703. var RetryStrategy = /** @class */ (function () {
  8704. function RetryStrategy() {
  8705. }
  8706. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8707. if (maxRetries === void 0) { maxRetries = 3; }
  8708. if (baseInterval === void 0) { baseInterval = 500; }
  8709. return function (url, request, retryIndex) {
  8710. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8711. return -1;
  8712. }
  8713. return Math.pow(2, retryIndex) * baseInterval;
  8714. };
  8715. };
  8716. return RetryStrategy;
  8717. }());
  8718. BABYLON.RetryStrategy = RetryStrategy;
  8719. // Screenshots
  8720. var screenshotCanvas;
  8721. var cloneValue = function (source, destinationObject) {
  8722. if (!source)
  8723. return null;
  8724. if (source instanceof BABYLON.Mesh) {
  8725. return null;
  8726. }
  8727. if (source instanceof BABYLON.SubMesh) {
  8728. return source.clone(destinationObject);
  8729. }
  8730. else if (source.clone) {
  8731. return source.clone();
  8732. }
  8733. return null;
  8734. };
  8735. var Tools = /** @class */ (function () {
  8736. function Tools() {
  8737. }
  8738. /**
  8739. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8740. * @param u defines the coordinate on X axis
  8741. * @param v defines the coordinate on Y axis
  8742. * @param width defines the width of the source data
  8743. * @param height defines the height of the source data
  8744. * @param pixels defines the source byte array
  8745. * @param color defines the output color
  8746. */
  8747. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8748. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8749. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8750. var position = (wrappedU + wrappedV * width) * 4;
  8751. color.r = pixels[position] / 255;
  8752. color.g = pixels[position + 1] / 255;
  8753. color.b = pixels[position + 2] / 255;
  8754. color.a = pixels[position + 3] / 255;
  8755. };
  8756. /**
  8757. * Interpolates between a and b via alpha
  8758. * @param a The lower value (returned when alpha = 0)
  8759. * @param b The upper value (returned when alpha = 1)
  8760. * @param alpha The interpolation-factor
  8761. * @return The mixed value
  8762. */
  8763. Tools.Mix = function (a, b, alpha) {
  8764. return a * (1 - alpha) + b * alpha;
  8765. };
  8766. Tools.Instantiate = function (className) {
  8767. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8768. return Tools.RegisteredExternalClasses[className];
  8769. }
  8770. var arr = className.split(".");
  8771. var fn = (window || this);
  8772. for (var i = 0, len = arr.length; i < len; i++) {
  8773. fn = fn[arr[i]];
  8774. }
  8775. if (typeof fn !== "function") {
  8776. return null;
  8777. }
  8778. return fn;
  8779. };
  8780. /**
  8781. * Provides a slice function that will work even on IE
  8782. * @param data defines the array to slice
  8783. * @param start defines the start of the data (optional)
  8784. * @param end defines the end of the data (optional)
  8785. * @returns the new sliced array
  8786. */
  8787. Tools.Slice = function (data, start, end) {
  8788. if (data.slice) {
  8789. return data.slice(start, end);
  8790. }
  8791. return Array.prototype.slice.call(data, start, end);
  8792. };
  8793. Tools.SetImmediate = function (action) {
  8794. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8795. window.setImmediate(action);
  8796. }
  8797. else {
  8798. setTimeout(action, 1);
  8799. }
  8800. };
  8801. Tools.IsExponentOfTwo = function (value) {
  8802. var count = 1;
  8803. do {
  8804. count *= 2;
  8805. } while (count < value);
  8806. return count === value;
  8807. };
  8808. /**
  8809. * Returns the nearest 32-bit single precision float representation of a Number
  8810. * @param value A Number. If the parameter is of a different type, it will get converted
  8811. * to a number or to NaN if it cannot be converted
  8812. * @returns number
  8813. */
  8814. Tools.FloatRound = function (value) {
  8815. if (Math.fround) {
  8816. return Math.fround(value);
  8817. }
  8818. return (Tools._tmpFloatArray[0] = value);
  8819. };
  8820. /**
  8821. * Find the next highest power of two.
  8822. * @param x Number to start search from.
  8823. * @return Next highest power of two.
  8824. */
  8825. Tools.CeilingPOT = function (x) {
  8826. x--;
  8827. x |= x >> 1;
  8828. x |= x >> 2;
  8829. x |= x >> 4;
  8830. x |= x >> 8;
  8831. x |= x >> 16;
  8832. x++;
  8833. return x;
  8834. };
  8835. /**
  8836. * Find the next lowest power of two.
  8837. * @param x Number to start search from.
  8838. * @return Next lowest power of two.
  8839. */
  8840. Tools.FloorPOT = function (x) {
  8841. x = x | (x >> 1);
  8842. x = x | (x >> 2);
  8843. x = x | (x >> 4);
  8844. x = x | (x >> 8);
  8845. x = x | (x >> 16);
  8846. return x - (x >> 1);
  8847. };
  8848. /**
  8849. * Find the nearest power of two.
  8850. * @param x Number to start search from.
  8851. * @return Next nearest power of two.
  8852. */
  8853. Tools.NearestPOT = function (x) {
  8854. var c = Tools.CeilingPOT(x);
  8855. var f = Tools.FloorPOT(x);
  8856. return (c - x) > (x - f) ? f : c;
  8857. };
  8858. Tools.GetExponentOfTwo = function (value, max, mode) {
  8859. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8860. var pot;
  8861. switch (mode) {
  8862. case BABYLON.Engine.SCALEMODE_FLOOR:
  8863. pot = Tools.FloorPOT(value);
  8864. break;
  8865. case BABYLON.Engine.SCALEMODE_NEAREST:
  8866. pot = Tools.NearestPOT(value);
  8867. break;
  8868. case BABYLON.Engine.SCALEMODE_CEILING:
  8869. default:
  8870. pot = Tools.CeilingPOT(value);
  8871. break;
  8872. }
  8873. return Math.min(pot, max);
  8874. };
  8875. Tools.GetFilename = function (path) {
  8876. var index = path.lastIndexOf("/");
  8877. if (index < 0)
  8878. return path;
  8879. return path.substring(index + 1);
  8880. };
  8881. /**
  8882. * Extracts the "folder" part of a path (everything before the filename).
  8883. * @param uri The URI to extract the info from
  8884. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8885. * @returns The "folder" part of the path
  8886. */
  8887. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8888. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8889. var index = uri.lastIndexOf("/");
  8890. if (index < 0) {
  8891. if (returnUnchangedIfNoSlash) {
  8892. return uri;
  8893. }
  8894. return "";
  8895. }
  8896. return uri.substring(0, index + 1);
  8897. };
  8898. Tools.GetDOMTextContent = function (element) {
  8899. var result = "";
  8900. var child = element.firstChild;
  8901. while (child) {
  8902. if (child.nodeType === 3) {
  8903. result += child.textContent;
  8904. }
  8905. child = child.nextSibling;
  8906. }
  8907. return result;
  8908. };
  8909. Tools.ToDegrees = function (angle) {
  8910. return angle * 180 / Math.PI;
  8911. };
  8912. Tools.ToRadians = function (angle) {
  8913. return angle * Math.PI / 180;
  8914. };
  8915. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8916. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8917. var output = "";
  8918. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8919. var i = 0;
  8920. var bytes = new Uint8Array(buffer);
  8921. while (i < bytes.length) {
  8922. chr1 = bytes[i++];
  8923. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8924. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8925. enc1 = chr1 >> 2;
  8926. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8927. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8928. enc4 = chr3 & 63;
  8929. if (isNaN(chr2)) {
  8930. enc3 = enc4 = 64;
  8931. }
  8932. else if (isNaN(chr3)) {
  8933. enc4 = 64;
  8934. }
  8935. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8936. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8937. }
  8938. return "data:image/png;base64," + output;
  8939. };
  8940. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8941. if (bias === void 0) { bias = null; }
  8942. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8943. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8944. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8945. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8946. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8947. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8948. }
  8949. if (bias) {
  8950. minimum.x -= minimum.x * bias.x + bias.y;
  8951. minimum.y -= minimum.y * bias.x + bias.y;
  8952. minimum.z -= minimum.z * bias.x + bias.y;
  8953. maximum.x += maximum.x * bias.x + bias.y;
  8954. maximum.y += maximum.y * bias.x + bias.y;
  8955. maximum.z += maximum.z * bias.x + bias.y;
  8956. }
  8957. return {
  8958. minimum: minimum,
  8959. maximum: maximum
  8960. };
  8961. };
  8962. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8963. if (bias === void 0) { bias = null; }
  8964. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8965. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8966. if (!stride) {
  8967. stride = 3;
  8968. }
  8969. for (var index = start; index < start + count; index++) {
  8970. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8971. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8972. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8973. }
  8974. if (bias) {
  8975. minimum.x -= minimum.x * bias.x + bias.y;
  8976. minimum.y -= minimum.y * bias.x + bias.y;
  8977. minimum.z -= minimum.z * bias.x + bias.y;
  8978. maximum.x += maximum.x * bias.x + bias.y;
  8979. maximum.y += maximum.y * bias.x + bias.y;
  8980. maximum.z += maximum.z * bias.x + bias.y;
  8981. }
  8982. return {
  8983. minimum: minimum,
  8984. maximum: maximum
  8985. };
  8986. };
  8987. Tools.Vector2ArrayFeeder = function (array) {
  8988. return function (index) {
  8989. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8990. var length = isFloatArray ? array.length / 2 : array.length;
  8991. if (index >= length) {
  8992. return null;
  8993. }
  8994. if (isFloatArray) {
  8995. var fa = array;
  8996. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8997. }
  8998. var a = array;
  8999. return a[index];
  9000. };
  9001. };
  9002. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  9003. if (bias === void 0) { bias = null; }
  9004. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  9005. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  9006. var i = 0;
  9007. var cur = feeder(i++);
  9008. while (cur) {
  9009. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  9010. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  9011. cur = feeder(i++);
  9012. }
  9013. if (bias) {
  9014. minimum.x -= minimum.x * bias.x + bias.y;
  9015. minimum.y -= minimum.y * bias.x + bias.y;
  9016. maximum.x += maximum.x * bias.x + bias.y;
  9017. maximum.y += maximum.y * bias.x + bias.y;
  9018. }
  9019. return {
  9020. minimum: minimum,
  9021. maximum: maximum
  9022. };
  9023. };
  9024. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9025. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9026. return null;
  9027. return Array.isArray(obj) ? obj : [obj];
  9028. };
  9029. // Misc.
  9030. Tools.GetPointerPrefix = function () {
  9031. var eventPrefix = "pointer";
  9032. // Check if pointer events are supported
  9033. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9034. eventPrefix = "mouse";
  9035. }
  9036. return eventPrefix;
  9037. };
  9038. /**
  9039. * @param func - the function to be called
  9040. * @param requester - the object that will request the next frame. Falls back to window.
  9041. */
  9042. Tools.QueueNewFrame = function (func, requester) {
  9043. if (!Tools.IsWindowObjectExist()) {
  9044. return setTimeout(func, 16);
  9045. }
  9046. if (!requester) {
  9047. requester = window;
  9048. }
  9049. if (requester.requestAnimationFrame) {
  9050. return requester.requestAnimationFrame(func);
  9051. }
  9052. else if (requester.msRequestAnimationFrame) {
  9053. return requester.msRequestAnimationFrame(func);
  9054. }
  9055. else if (requester.webkitRequestAnimationFrame) {
  9056. return requester.webkitRequestAnimationFrame(func);
  9057. }
  9058. else if (requester.mozRequestAnimationFrame) {
  9059. return requester.mozRequestAnimationFrame(func);
  9060. }
  9061. else if (requester.oRequestAnimationFrame) {
  9062. return requester.oRequestAnimationFrame(func);
  9063. }
  9064. else {
  9065. return window.setTimeout(func, 16);
  9066. }
  9067. };
  9068. Tools.RequestFullscreen = function (element) {
  9069. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9070. if (!requestFunction)
  9071. return;
  9072. requestFunction.call(element);
  9073. };
  9074. Tools.ExitFullscreen = function () {
  9075. if (document.exitFullscreen) {
  9076. document.exitFullscreen();
  9077. }
  9078. else if (document.mozCancelFullScreen) {
  9079. document.mozCancelFullScreen();
  9080. }
  9081. else if (document.webkitCancelFullScreen) {
  9082. document.webkitCancelFullScreen();
  9083. }
  9084. else if (document.msCancelFullScreen) {
  9085. document.msCancelFullScreen();
  9086. }
  9087. };
  9088. Tools.SetCorsBehavior = function (url, element) {
  9089. if (url && url.indexOf("data:") === 0) {
  9090. return;
  9091. }
  9092. if (Tools.CorsBehavior) {
  9093. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9094. element.crossOrigin = Tools.CorsBehavior;
  9095. }
  9096. else {
  9097. var result = Tools.CorsBehavior(url);
  9098. if (result) {
  9099. element.crossOrigin = result;
  9100. }
  9101. }
  9102. }
  9103. };
  9104. // External files
  9105. Tools.CleanUrl = function (url) {
  9106. url = url.replace(/#/mg, "%23");
  9107. return url;
  9108. };
  9109. /**
  9110. * Loads an image as an HTMLImageElement.
  9111. * @param input url string, ArrayBuffer, or Blob to load
  9112. * @param onLoad callback called when the image successfully loads
  9113. * @param onError callback called when the image fails to load
  9114. * @param database database for caching
  9115. * @returns the HTMLImageElement of the loaded image
  9116. */
  9117. Tools.LoadImage = function (input, onLoad, onError, database) {
  9118. var url;
  9119. var usingObjectURL = false;
  9120. if (input instanceof ArrayBuffer) {
  9121. url = URL.createObjectURL(new Blob([input]));
  9122. usingObjectURL = true;
  9123. }
  9124. else if (input instanceof Blob) {
  9125. url = URL.createObjectURL(input);
  9126. usingObjectURL = true;
  9127. }
  9128. else {
  9129. url = Tools.CleanUrl(input);
  9130. url = Tools.PreprocessUrl(input);
  9131. }
  9132. var img = new Image();
  9133. Tools.SetCorsBehavior(url, img);
  9134. var loadHandler = function () {
  9135. if (usingObjectURL && img.src) {
  9136. URL.revokeObjectURL(img.src);
  9137. }
  9138. img.removeEventListener("load", loadHandler);
  9139. img.removeEventListener("error", errorHandler);
  9140. onLoad(img);
  9141. };
  9142. var errorHandler = function (err) {
  9143. if (usingObjectURL && img.src) {
  9144. URL.revokeObjectURL(img.src);
  9145. }
  9146. img.removeEventListener("load", loadHandler);
  9147. img.removeEventListener("error", errorHandler);
  9148. Tools.Error("Error while trying to load image: " + input);
  9149. if (onError) {
  9150. onError("Error while trying to load image: " + input, err);
  9151. }
  9152. };
  9153. img.addEventListener("load", loadHandler);
  9154. img.addEventListener("error", errorHandler);
  9155. var noIndexedDB = function () {
  9156. img.src = url;
  9157. };
  9158. var loadFromIndexedDB = function () {
  9159. if (database) {
  9160. database.loadImageFromDB(url, img);
  9161. }
  9162. };
  9163. //ANY database to do!
  9164. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9165. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9166. }
  9167. else {
  9168. if (url.indexOf("file:") !== -1) {
  9169. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9170. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9171. try {
  9172. var blobURL;
  9173. try {
  9174. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9175. }
  9176. catch (ex) {
  9177. // Chrome doesn't support oneTimeOnly parameter
  9178. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9179. }
  9180. img.src = blobURL;
  9181. usingObjectURL = true;
  9182. }
  9183. catch (e) {
  9184. img.src = "";
  9185. }
  9186. return img;
  9187. }
  9188. }
  9189. noIndexedDB();
  9190. }
  9191. return img;
  9192. };
  9193. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9194. url = Tools.CleanUrl(url);
  9195. url = Tools.PreprocessUrl(url);
  9196. // If file and file input are set
  9197. if (url.indexOf("file:") !== -1) {
  9198. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9199. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9200. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9201. }
  9202. }
  9203. var loadUrl = Tools.BaseUrl + url;
  9204. var aborted = false;
  9205. var fileRequest = {
  9206. onCompleteObservable: new BABYLON.Observable(),
  9207. abort: function () { return aborted = true; },
  9208. };
  9209. var requestFile = function () {
  9210. var request = new XMLHttpRequest();
  9211. var retryHandle = null;
  9212. fileRequest.abort = function () {
  9213. aborted = true;
  9214. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9215. request.abort();
  9216. }
  9217. if (retryHandle !== null) {
  9218. clearTimeout(retryHandle);
  9219. retryHandle = null;
  9220. }
  9221. };
  9222. var retryLoop = function (retryIndex) {
  9223. request.open('GET', loadUrl, true);
  9224. if (useArrayBuffer) {
  9225. request.responseType = "arraybuffer";
  9226. }
  9227. if (onProgress) {
  9228. request.addEventListener("progress", onProgress);
  9229. }
  9230. var onLoadEnd = function () {
  9231. request.removeEventListener("loadend", onLoadEnd);
  9232. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9233. fileRequest.onCompleteObservable.clear();
  9234. };
  9235. request.addEventListener("loadend", onLoadEnd);
  9236. var onReadyStateChange = function () {
  9237. if (aborted) {
  9238. return;
  9239. }
  9240. // In case of undefined state in some browsers.
  9241. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9242. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9243. request.removeEventListener("readystatechange", onReadyStateChange);
  9244. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9245. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9246. return;
  9247. }
  9248. var retryStrategy = Tools.DefaultRetryStrategy;
  9249. if (retryStrategy) {
  9250. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9251. if (waitTime !== -1) {
  9252. // Prevent the request from completing for retry.
  9253. request.removeEventListener("loadend", onLoadEnd);
  9254. request = new XMLHttpRequest();
  9255. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9256. return;
  9257. }
  9258. }
  9259. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9260. if (onError) {
  9261. onError(request, e);
  9262. }
  9263. else {
  9264. throw e;
  9265. }
  9266. }
  9267. };
  9268. request.addEventListener("readystatechange", onReadyStateChange);
  9269. request.send();
  9270. };
  9271. retryLoop(0);
  9272. };
  9273. // Caching all files
  9274. if (database && database.enableSceneOffline) {
  9275. var noIndexedDB_1 = function (request) {
  9276. if (request && request.status > 400) {
  9277. if (onError) {
  9278. onError(request);
  9279. }
  9280. }
  9281. else {
  9282. if (!aborted) {
  9283. requestFile();
  9284. }
  9285. }
  9286. };
  9287. var loadFromIndexedDB = function () {
  9288. // TODO: database needs to support aborting and should return a IFileRequest
  9289. if (aborted) {
  9290. return;
  9291. }
  9292. if (database) {
  9293. database.loadFileFromDB(url, function (data) {
  9294. if (!aborted) {
  9295. onSuccess(data);
  9296. }
  9297. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9298. }, onProgress ? function (event) {
  9299. if (!aborted) {
  9300. onProgress(event);
  9301. }
  9302. } : undefined, noIndexedDB_1, useArrayBuffer);
  9303. }
  9304. };
  9305. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9306. }
  9307. else {
  9308. requestFile();
  9309. }
  9310. return fileRequest;
  9311. };
  9312. /**
  9313. * Load a script (identified by an url). When the url returns, the
  9314. * content of this file is added into a new script element, attached to the DOM (body element)
  9315. */
  9316. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9317. if (!Tools.IsWindowObjectExist()) {
  9318. return;
  9319. }
  9320. var head = document.getElementsByTagName('head')[0];
  9321. var script = document.createElement('script');
  9322. script.type = 'text/javascript';
  9323. script.src = scriptUrl;
  9324. script.onload = function () {
  9325. if (onSuccess) {
  9326. onSuccess();
  9327. }
  9328. };
  9329. script.onerror = function (e) {
  9330. if (onError) {
  9331. onError("Unable to load script '" + scriptUrl + "'", e);
  9332. }
  9333. };
  9334. head.appendChild(script);
  9335. };
  9336. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9337. var reader = new FileReader();
  9338. var request = {
  9339. onCompleteObservable: new BABYLON.Observable(),
  9340. abort: function () { return reader.abort(); },
  9341. };
  9342. reader.onloadend = function (e) {
  9343. request.onCompleteObservable.notifyObservers(request);
  9344. };
  9345. reader.onload = function (e) {
  9346. //target doesn't have result from ts 1.3
  9347. callback(e.target['result']);
  9348. };
  9349. reader.onprogress = progressCallback;
  9350. reader.readAsDataURL(fileToLoad);
  9351. return request;
  9352. };
  9353. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9354. var reader = new FileReader();
  9355. var request = {
  9356. onCompleteObservable: new BABYLON.Observable(),
  9357. abort: function () { return reader.abort(); },
  9358. };
  9359. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9360. reader.onerror = function (e) {
  9361. Tools.Log("Error while reading file: " + fileToLoad.name);
  9362. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9363. };
  9364. reader.onload = function (e) {
  9365. //target doesn't have result from ts 1.3
  9366. callback(e.target['result']);
  9367. };
  9368. if (progressCallBack) {
  9369. reader.onprogress = progressCallBack;
  9370. }
  9371. if (!useArrayBuffer) {
  9372. // Asynchronous read
  9373. reader.readAsText(fileToLoad);
  9374. }
  9375. else {
  9376. reader.readAsArrayBuffer(fileToLoad);
  9377. }
  9378. return request;
  9379. };
  9380. //returns a downloadable url to a file content.
  9381. Tools.FileAsURL = function (content) {
  9382. var fileBlob = new Blob([content]);
  9383. var url = window.URL || window.webkitURL;
  9384. var link = url.createObjectURL(fileBlob);
  9385. return link;
  9386. };
  9387. // Misc.
  9388. Tools.Format = function (value, decimals) {
  9389. if (decimals === void 0) { decimals = 2; }
  9390. return value.toFixed(decimals);
  9391. };
  9392. Tools.CheckExtends = function (v, min, max) {
  9393. if (v.x < min.x)
  9394. min.x = v.x;
  9395. if (v.y < min.y)
  9396. min.y = v.y;
  9397. if (v.z < min.z)
  9398. min.z = v.z;
  9399. if (v.x > max.x)
  9400. max.x = v.x;
  9401. if (v.y > max.y)
  9402. max.y = v.y;
  9403. if (v.z > max.z)
  9404. max.z = v.z;
  9405. };
  9406. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9407. for (var prop in source) {
  9408. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9409. continue;
  9410. }
  9411. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9412. continue;
  9413. }
  9414. var sourceValue = source[prop];
  9415. var typeOfSourceValue = typeof sourceValue;
  9416. if (typeOfSourceValue === "function") {
  9417. continue;
  9418. }
  9419. try {
  9420. if (typeOfSourceValue === "object") {
  9421. if (sourceValue instanceof Array) {
  9422. destination[prop] = [];
  9423. if (sourceValue.length > 0) {
  9424. if (typeof sourceValue[0] == "object") {
  9425. for (var index = 0; index < sourceValue.length; index++) {
  9426. var clonedValue = cloneValue(sourceValue[index], destination);
  9427. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9428. destination[prop].push(clonedValue);
  9429. }
  9430. }
  9431. }
  9432. else {
  9433. destination[prop] = sourceValue.slice(0);
  9434. }
  9435. }
  9436. }
  9437. else {
  9438. destination[prop] = cloneValue(sourceValue, destination);
  9439. }
  9440. }
  9441. else {
  9442. destination[prop] = sourceValue;
  9443. }
  9444. }
  9445. catch (e) {
  9446. // Just ignore error (it could be because of a read-only property)
  9447. }
  9448. }
  9449. };
  9450. Tools.IsEmpty = function (obj) {
  9451. for (var i in obj) {
  9452. if (obj.hasOwnProperty(i)) {
  9453. return false;
  9454. }
  9455. }
  9456. return true;
  9457. };
  9458. Tools.RegisterTopRootEvents = function (events) {
  9459. for (var index = 0; index < events.length; index++) {
  9460. var event = events[index];
  9461. window.addEventListener(event.name, event.handler, false);
  9462. try {
  9463. if (window.parent) {
  9464. window.parent.addEventListener(event.name, event.handler, false);
  9465. }
  9466. }
  9467. catch (e) {
  9468. // Silently fails...
  9469. }
  9470. }
  9471. };
  9472. Tools.UnregisterTopRootEvents = function (events) {
  9473. for (var index = 0; index < events.length; index++) {
  9474. var event = events[index];
  9475. window.removeEventListener(event.name, event.handler);
  9476. try {
  9477. if (window.parent) {
  9478. window.parent.removeEventListener(event.name, event.handler);
  9479. }
  9480. }
  9481. catch (e) {
  9482. // Silently fails...
  9483. }
  9484. }
  9485. };
  9486. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9487. if (mimeType === void 0) { mimeType = "image/png"; }
  9488. // Read the contents of the framebuffer
  9489. var numberOfChannelsByLine = width * 4;
  9490. var halfHeight = height / 2;
  9491. //Reading datas from WebGL
  9492. var data = engine.readPixels(0, 0, width, height);
  9493. //To flip image on Y axis.
  9494. for (var i = 0; i < halfHeight; i++) {
  9495. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9496. var currentCell = j + i * numberOfChannelsByLine;
  9497. var targetLine = height - i - 1;
  9498. var targetCell = j + targetLine * numberOfChannelsByLine;
  9499. var temp = data[currentCell];
  9500. data[currentCell] = data[targetCell];
  9501. data[targetCell] = temp;
  9502. }
  9503. }
  9504. // Create a 2D canvas to store the result
  9505. if (!screenshotCanvas) {
  9506. screenshotCanvas = document.createElement('canvas');
  9507. }
  9508. screenshotCanvas.width = width;
  9509. screenshotCanvas.height = height;
  9510. var context = screenshotCanvas.getContext('2d');
  9511. if (context) {
  9512. // Copy the pixels to a 2D canvas
  9513. var imageData = context.createImageData(width, height);
  9514. var castData = (imageData.data);
  9515. castData.set(data);
  9516. context.putImageData(imageData, 0, 0);
  9517. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9518. }
  9519. };
  9520. /**
  9521. * Converts the canvas data to blob.
  9522. * This acts as a polyfill for browsers not supporting the to blob function.
  9523. * @param canvas Defines the canvas to extract the data from
  9524. * @param successCallback Defines the callback triggered once the data are available
  9525. * @param mimeType Defines the mime type of the result
  9526. */
  9527. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9528. if (mimeType === void 0) { mimeType = "image/png"; }
  9529. // We need HTMLCanvasElement.toBlob for HD screenshots
  9530. if (!canvas.toBlob) {
  9531. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9532. canvas.toBlob = function (callback, type, quality) {
  9533. var _this = this;
  9534. setTimeout(function () {
  9535. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9536. for (var i = 0; i < len; i++) {
  9537. arr[i] = binStr.charCodeAt(i);
  9538. }
  9539. callback(new Blob([arr]));
  9540. });
  9541. };
  9542. }
  9543. canvas.toBlob(function (blob) {
  9544. successCallback(blob);
  9545. }, mimeType);
  9546. };
  9547. /**
  9548. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9549. * @param successCallback Defines the callback triggered once the data are available
  9550. * @param mimeType Defines the mime type of the result
  9551. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9552. */
  9553. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9554. if (mimeType === void 0) { mimeType = "image/png"; }
  9555. if (successCallback) {
  9556. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9557. successCallback(base64Image);
  9558. }
  9559. else {
  9560. this.ToBlob(screenshotCanvas, function (blob) {
  9561. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9562. if (("download" in document.createElement("a"))) {
  9563. if (!fileName) {
  9564. var date = new Date();
  9565. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9566. fileName = "screenshot_" + stringDate + ".png";
  9567. }
  9568. Tools.Download(blob, fileName);
  9569. }
  9570. else {
  9571. var url = URL.createObjectURL(blob);
  9572. var newWindow = window.open("");
  9573. if (!newWindow)
  9574. return;
  9575. var img = newWindow.document.createElement("img");
  9576. img.onload = function () {
  9577. // no longer need to read the blob so it's revoked
  9578. URL.revokeObjectURL(url);
  9579. };
  9580. img.src = url;
  9581. newWindow.document.body.appendChild(img);
  9582. }
  9583. }, mimeType);
  9584. }
  9585. };
  9586. /**
  9587. * Downloads a blob in the browser
  9588. * @param blob defines the blob to download
  9589. * @param fileName defines the name of the downloaded file
  9590. */
  9591. Tools.Download = function (blob, fileName) {
  9592. if (navigator && navigator.msSaveBlob) {
  9593. navigator.msSaveBlob(blob, fileName);
  9594. return;
  9595. }
  9596. var url = window.URL.createObjectURL(blob);
  9597. var a = document.createElement("a");
  9598. document.body.appendChild(a);
  9599. a.style.display = "none";
  9600. a.href = url;
  9601. a.download = fileName;
  9602. a.addEventListener("click", function () {
  9603. if (a.parentElement) {
  9604. a.parentElement.removeChild(a);
  9605. }
  9606. });
  9607. a.click();
  9608. window.URL.revokeObjectURL(url);
  9609. };
  9610. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9611. if (mimeType === void 0) { mimeType = "image/png"; }
  9612. var width;
  9613. var height;
  9614. // If a precision value is specified
  9615. if (size.precision) {
  9616. width = Math.round(engine.getRenderWidth() * size.precision);
  9617. height = Math.round(width / engine.getAspectRatio(camera));
  9618. }
  9619. else if (size.width && size.height) {
  9620. width = size.width;
  9621. height = size.height;
  9622. }
  9623. //If passing only width, computing height to keep display canvas ratio.
  9624. else if (size.width && !size.height) {
  9625. width = size.width;
  9626. height = Math.round(width / engine.getAspectRatio(camera));
  9627. }
  9628. //If passing only height, computing width to keep display canvas ratio.
  9629. else if (size.height && !size.width) {
  9630. height = size.height;
  9631. width = Math.round(height * engine.getAspectRatio(camera));
  9632. }
  9633. //Assuming here that "size" parameter is a number
  9634. else if (!isNaN(size)) {
  9635. height = size;
  9636. width = size;
  9637. }
  9638. else {
  9639. Tools.Error("Invalid 'size' parameter !");
  9640. return;
  9641. }
  9642. if (!screenshotCanvas) {
  9643. screenshotCanvas = document.createElement('canvas');
  9644. }
  9645. screenshotCanvas.width = width;
  9646. screenshotCanvas.height = height;
  9647. var renderContext = screenshotCanvas.getContext("2d");
  9648. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9649. var newWidth = width;
  9650. var newHeight = newWidth / ratio;
  9651. if (newHeight > height) {
  9652. newHeight = height;
  9653. newWidth = newHeight * ratio;
  9654. }
  9655. var offsetX = Math.max(0, width - newWidth) / 2;
  9656. var offsetY = Math.max(0, height - newHeight) / 2;
  9657. var renderingCanvas = engine.getRenderingCanvas();
  9658. if (renderContext && renderingCanvas) {
  9659. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9660. }
  9661. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9662. };
  9663. /**
  9664. * Generates an image screenshot from the specified camera.
  9665. *
  9666. * @param engine The engine to use for rendering
  9667. * @param camera The camera to use for rendering
  9668. * @param size This parameter can be set to a single number or to an object with the
  9669. * following (optional) properties: precision, width, height. If a single number is passed,
  9670. * it will be used for both width and height. If an object is passed, the screenshot size
  9671. * will be derived from the parameters. The precision property is a multiplier allowing
  9672. * rendering at a higher or lower resolution.
  9673. * @param successCallback The callback receives a single parameter which contains the
  9674. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9675. * src parameter of an <img> to display it.
  9676. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9677. * Check your browser for supported MIME types.
  9678. * @param samples Texture samples (default: 1)
  9679. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9680. * @param fileName A name for for the downloaded file.
  9681. * @constructor
  9682. */
  9683. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9684. if (mimeType === void 0) { mimeType = "image/png"; }
  9685. if (samples === void 0) { samples = 1; }
  9686. if (antialiasing === void 0) { antialiasing = false; }
  9687. var width;
  9688. var height;
  9689. //If a precision value is specified
  9690. if (size.precision) {
  9691. width = Math.round(engine.getRenderWidth() * size.precision);
  9692. height = Math.round(width / engine.getAspectRatio(camera));
  9693. size = { width: width, height: height };
  9694. }
  9695. else if (size.width && size.height) {
  9696. width = size.width;
  9697. height = size.height;
  9698. }
  9699. //If passing only width, computing height to keep display canvas ratio.
  9700. else if (size.width && !size.height) {
  9701. width = size.width;
  9702. height = Math.round(width / engine.getAspectRatio(camera));
  9703. size = { width: width, height: height };
  9704. }
  9705. //If passing only height, computing width to keep display canvas ratio.
  9706. else if (size.height && !size.width) {
  9707. height = size.height;
  9708. width = Math.round(height * engine.getAspectRatio(camera));
  9709. size = { width: width, height: height };
  9710. }
  9711. //Assuming here that "size" parameter is a number
  9712. else if (!isNaN(size)) {
  9713. height = size;
  9714. width = size;
  9715. }
  9716. else {
  9717. Tools.Error("Invalid 'size' parameter !");
  9718. return;
  9719. }
  9720. var scene = camera.getScene();
  9721. var previousCamera = null;
  9722. if (scene.activeCamera !== camera) {
  9723. previousCamera = scene.activeCamera;
  9724. scene.activeCamera = camera;
  9725. }
  9726. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9727. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9728. texture.renderList = null;
  9729. texture.samples = samples;
  9730. if (antialiasing) {
  9731. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9732. }
  9733. texture.onAfterRenderObservable.add(function () {
  9734. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9735. });
  9736. scene.incrementRenderId();
  9737. scene.resetCachedMaterial();
  9738. texture.render(true);
  9739. texture.dispose();
  9740. if (previousCamera) {
  9741. scene.activeCamera = previousCamera;
  9742. }
  9743. camera.getProjectionMatrix(true); // Force cache refresh;
  9744. };
  9745. // XHR response validator for local file scenario
  9746. Tools.ValidateXHRData = function (xhr, dataType) {
  9747. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9748. if (dataType === void 0) { dataType = 7; }
  9749. try {
  9750. if (dataType & 1) {
  9751. if (xhr.responseText && xhr.responseText.length > 0) {
  9752. return true;
  9753. }
  9754. else if (dataType === 1) {
  9755. return false;
  9756. }
  9757. }
  9758. if (dataType & 2) {
  9759. // Check header width and height since there is no "TGA" magic number
  9760. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9761. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9762. return true;
  9763. }
  9764. else if (dataType === 2) {
  9765. return false;
  9766. }
  9767. }
  9768. if (dataType & 4) {
  9769. // Check for the "DDS" magic number
  9770. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9771. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9772. return true;
  9773. }
  9774. else {
  9775. return false;
  9776. }
  9777. }
  9778. }
  9779. catch (e) {
  9780. // Global protection
  9781. }
  9782. return false;
  9783. };
  9784. /**
  9785. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9786. * Be aware Math.random() could cause collisions, but:
  9787. * "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"
  9788. */
  9789. Tools.RandomId = function () {
  9790. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9791. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9792. return v.toString(16);
  9793. });
  9794. };
  9795. /**
  9796. * Test if the given uri is a base64 string.
  9797. * @param uri The uri to test
  9798. * @return True if the uri is a base64 string or false otherwise.
  9799. */
  9800. Tools.IsBase64 = function (uri) {
  9801. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9802. };
  9803. /**
  9804. * Decode the given base64 uri.
  9805. * @param uri The uri to decode
  9806. * @return The decoded base64 data.
  9807. */
  9808. Tools.DecodeBase64 = function (uri) {
  9809. var decodedString = atob(uri.split(",")[1]);
  9810. var bufferLength = decodedString.length;
  9811. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9812. for (var i = 0; i < bufferLength; i++) {
  9813. bufferView[i] = decodedString.charCodeAt(i);
  9814. }
  9815. return bufferView.buffer;
  9816. };
  9817. Object.defineProperty(Tools, "NoneLogLevel", {
  9818. get: function () {
  9819. return Tools._NoneLogLevel;
  9820. },
  9821. enumerable: true,
  9822. configurable: true
  9823. });
  9824. Object.defineProperty(Tools, "MessageLogLevel", {
  9825. get: function () {
  9826. return Tools._MessageLogLevel;
  9827. },
  9828. enumerable: true,
  9829. configurable: true
  9830. });
  9831. Object.defineProperty(Tools, "WarningLogLevel", {
  9832. get: function () {
  9833. return Tools._WarningLogLevel;
  9834. },
  9835. enumerable: true,
  9836. configurable: true
  9837. });
  9838. Object.defineProperty(Tools, "ErrorLogLevel", {
  9839. get: function () {
  9840. return Tools._ErrorLogLevel;
  9841. },
  9842. enumerable: true,
  9843. configurable: true
  9844. });
  9845. Object.defineProperty(Tools, "AllLogLevel", {
  9846. get: function () {
  9847. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9848. },
  9849. enumerable: true,
  9850. configurable: true
  9851. });
  9852. Tools._AddLogEntry = function (entry) {
  9853. Tools._LogCache = entry + Tools._LogCache;
  9854. if (Tools.OnNewCacheEntry) {
  9855. Tools.OnNewCacheEntry(entry);
  9856. }
  9857. };
  9858. Tools._FormatMessage = function (message) {
  9859. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9860. var date = new Date();
  9861. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9862. };
  9863. Tools._LogDisabled = function (message) {
  9864. // nothing to do
  9865. };
  9866. Tools._LogEnabled = function (message) {
  9867. var formattedMessage = Tools._FormatMessage(message);
  9868. console.log("BJS - " + formattedMessage);
  9869. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9870. Tools._AddLogEntry(entry);
  9871. };
  9872. Tools._WarnDisabled = function (message) {
  9873. // nothing to do
  9874. };
  9875. Tools._WarnEnabled = function (message) {
  9876. var formattedMessage = Tools._FormatMessage(message);
  9877. console.warn("BJS - " + formattedMessage);
  9878. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9879. Tools._AddLogEntry(entry);
  9880. };
  9881. Tools._ErrorDisabled = function (message) {
  9882. // nothing to do
  9883. };
  9884. Tools._ErrorEnabled = function (message) {
  9885. Tools.errorsCount++;
  9886. var formattedMessage = Tools._FormatMessage(message);
  9887. console.error("BJS - " + formattedMessage);
  9888. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9889. Tools._AddLogEntry(entry);
  9890. };
  9891. Object.defineProperty(Tools, "LogCache", {
  9892. get: function () {
  9893. return Tools._LogCache;
  9894. },
  9895. enumerable: true,
  9896. configurable: true
  9897. });
  9898. Tools.ClearLogCache = function () {
  9899. Tools._LogCache = "";
  9900. Tools.errorsCount = 0;
  9901. };
  9902. Object.defineProperty(Tools, "LogLevels", {
  9903. set: function (level) {
  9904. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9905. Tools.Log = Tools._LogEnabled;
  9906. }
  9907. else {
  9908. Tools.Log = Tools._LogDisabled;
  9909. }
  9910. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9911. Tools.Warn = Tools._WarnEnabled;
  9912. }
  9913. else {
  9914. Tools.Warn = Tools._WarnDisabled;
  9915. }
  9916. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9917. Tools.Error = Tools._ErrorEnabled;
  9918. }
  9919. else {
  9920. Tools.Error = Tools._ErrorDisabled;
  9921. }
  9922. },
  9923. enumerable: true,
  9924. configurable: true
  9925. });
  9926. /**
  9927. * Check if the loaded document was accessed via `file:`-Protocol.
  9928. * @returns boolean
  9929. */
  9930. Tools.IsFileURL = function () {
  9931. return location.protocol === "file:";
  9932. };
  9933. Tools.IsWindowObjectExist = function () {
  9934. return (typeof window) !== "undefined";
  9935. };
  9936. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9937. get: function () {
  9938. return Tools._PerformanceNoneLogLevel;
  9939. },
  9940. enumerable: true,
  9941. configurable: true
  9942. });
  9943. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9944. get: function () {
  9945. return Tools._PerformanceUserMarkLogLevel;
  9946. },
  9947. enumerable: true,
  9948. configurable: true
  9949. });
  9950. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9951. get: function () {
  9952. return Tools._PerformanceConsoleLogLevel;
  9953. },
  9954. enumerable: true,
  9955. configurable: true
  9956. });
  9957. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9958. set: function (level) {
  9959. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9960. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9961. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9962. return;
  9963. }
  9964. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9965. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9966. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9967. return;
  9968. }
  9969. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9970. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9971. },
  9972. enumerable: true,
  9973. configurable: true
  9974. });
  9975. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9976. };
  9977. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9978. };
  9979. Tools._StartUserMark = function (counterName, condition) {
  9980. if (condition === void 0) { condition = true; }
  9981. if (!Tools._performance) {
  9982. if (!Tools.IsWindowObjectExist()) {
  9983. return;
  9984. }
  9985. Tools._performance = window.performance;
  9986. }
  9987. if (!condition || !Tools._performance.mark) {
  9988. return;
  9989. }
  9990. Tools._performance.mark(counterName + "-Begin");
  9991. };
  9992. Tools._EndUserMark = function (counterName, condition) {
  9993. if (condition === void 0) { condition = true; }
  9994. if (!condition || !Tools._performance.mark) {
  9995. return;
  9996. }
  9997. Tools._performance.mark(counterName + "-End");
  9998. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9999. };
  10000. Tools._StartPerformanceConsole = function (counterName, condition) {
  10001. if (condition === void 0) { condition = true; }
  10002. if (!condition) {
  10003. return;
  10004. }
  10005. Tools._StartUserMark(counterName, condition);
  10006. if (console.time) {
  10007. console.time(counterName);
  10008. }
  10009. };
  10010. Tools._EndPerformanceConsole = function (counterName, condition) {
  10011. if (condition === void 0) { condition = true; }
  10012. if (!condition) {
  10013. return;
  10014. }
  10015. Tools._EndUserMark(counterName, condition);
  10016. if (console.time) {
  10017. console.timeEnd(counterName);
  10018. }
  10019. };
  10020. Object.defineProperty(Tools, "Now", {
  10021. get: function () {
  10022. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10023. return window.performance.now();
  10024. }
  10025. return Date.now();
  10026. },
  10027. enumerable: true,
  10028. configurable: true
  10029. });
  10030. /**
  10031. * This method will return the name of the class used to create the instance of the given object.
  10032. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10033. * @param object the object to get the class name from
  10034. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  10035. */
  10036. Tools.GetClassName = function (object, isType) {
  10037. if (isType === void 0) { isType = false; }
  10038. var name = null;
  10039. if (!isType && object.getClassName) {
  10040. name = object.getClassName();
  10041. }
  10042. else {
  10043. if (object instanceof Object) {
  10044. var classObj = isType ? object : Object.getPrototypeOf(object);
  10045. name = classObj.constructor["__bjsclassName__"];
  10046. }
  10047. if (!name) {
  10048. name = typeof object;
  10049. }
  10050. }
  10051. return name;
  10052. };
  10053. Tools.First = function (array, predicate) {
  10054. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10055. var el = array_1[_i];
  10056. if (predicate(el)) {
  10057. return el;
  10058. }
  10059. }
  10060. return null;
  10061. };
  10062. /**
  10063. * This method will return the name of the full name of the class, including its owning module (if any).
  10064. * 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).
  10065. * @param object the object to get the class name from
  10066. * @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.
  10067. */
  10068. Tools.getFullClassName = function (object, isType) {
  10069. if (isType === void 0) { isType = false; }
  10070. var className = null;
  10071. var moduleName = null;
  10072. if (!isType && object.getClassName) {
  10073. className = object.getClassName();
  10074. }
  10075. else {
  10076. if (object instanceof Object) {
  10077. var classObj = isType ? object : Object.getPrototypeOf(object);
  10078. className = classObj.constructor["__bjsclassName__"];
  10079. moduleName = classObj.constructor["__bjsmoduleName__"];
  10080. }
  10081. if (!className) {
  10082. className = typeof object;
  10083. }
  10084. }
  10085. if (!className) {
  10086. return null;
  10087. }
  10088. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10089. };
  10090. /**
  10091. * 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.
  10092. * @param array
  10093. */
  10094. Tools.arrayOrStringFeeder = function (array) {
  10095. return function (index) {
  10096. if (index >= array.length) {
  10097. return null;
  10098. }
  10099. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10100. if (val && val.getHashCode) {
  10101. val = val.getHashCode();
  10102. }
  10103. if (typeof val === "string") {
  10104. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10105. }
  10106. return val;
  10107. };
  10108. };
  10109. /**
  10110. * Compute the hashCode of a stream of number
  10111. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10112. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10113. * @return the hash code computed
  10114. */
  10115. Tools.hashCodeFromStream = function (feeder) {
  10116. // Based from here: http://stackoverflow.com/a/7616484/802124
  10117. var hash = 0;
  10118. var index = 0;
  10119. var chr = feeder(index++);
  10120. while (chr != null) {
  10121. hash = ((hash << 5) - hash) + chr;
  10122. hash |= 0; // Convert to 32bit integer
  10123. chr = feeder(index++);
  10124. }
  10125. return hash;
  10126. };
  10127. /**
  10128. * Returns a promise that resolves after the given amount of time.
  10129. * @param delay Number of milliseconds to delay
  10130. * @returns Promise that resolves after the given amount of time
  10131. */
  10132. Tools.DelayAsync = function (delay) {
  10133. return new Promise(function (resolve) {
  10134. setTimeout(function () {
  10135. resolve();
  10136. }, delay);
  10137. });
  10138. };
  10139. /**
  10140. * Gets the current gradient from an array of IValueGradient
  10141. * @param ratio defines the current ratio to get
  10142. * @param gradients defines the array of IValueGradient
  10143. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10144. */
  10145. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10146. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10147. var currentGradient = gradients[gradientIndex];
  10148. var nextGradient = gradients[gradientIndex + 1];
  10149. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10150. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10151. updateFunc(currentGradient, nextGradient, scale);
  10152. return;
  10153. }
  10154. }
  10155. // Use last index if over
  10156. var lastIndex = gradients.length - 1;
  10157. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10158. };
  10159. Tools.BaseUrl = "";
  10160. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10161. /**
  10162. * Default behaviour for cors in the application.
  10163. * It can be a string if the expected behavior is identical in the entire app.
  10164. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10165. */
  10166. Tools.CorsBehavior = "anonymous";
  10167. Tools.UseFallbackTexture = true;
  10168. /**
  10169. * Use this object to register external classes like custom textures or material
  10170. * to allow the laoders to instantiate them
  10171. */
  10172. Tools.RegisteredExternalClasses = {};
  10173. // Used in case of a texture loading problem
  10174. 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";
  10175. Tools._tmpFloatArray = new Float32Array(1);
  10176. Tools.PreprocessUrl = function (url) {
  10177. return url;
  10178. };
  10179. // Logs
  10180. Tools._NoneLogLevel = 0;
  10181. Tools._MessageLogLevel = 1;
  10182. Tools._WarningLogLevel = 2;
  10183. Tools._ErrorLogLevel = 4;
  10184. Tools._LogCache = "";
  10185. Tools.errorsCount = 0;
  10186. Tools.Log = Tools._LogEnabled;
  10187. Tools.Warn = Tools._WarnEnabled;
  10188. Tools.Error = Tools._ErrorEnabled;
  10189. // Performances
  10190. Tools._PerformanceNoneLogLevel = 0;
  10191. Tools._PerformanceUserMarkLogLevel = 1;
  10192. Tools._PerformanceConsoleLogLevel = 2;
  10193. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10194. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10195. return Tools;
  10196. }());
  10197. BABYLON.Tools = Tools;
  10198. /**
  10199. * This class is used to track a performance counter which is number based.
  10200. * The user has access to many properties which give statistics of different nature
  10201. *
  10202. * The implementer can track two kinds of Performance Counter: time and count
  10203. * 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.
  10204. * 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.
  10205. */
  10206. var PerfCounter = /** @class */ (function () {
  10207. function PerfCounter() {
  10208. this._startMonitoringTime = 0;
  10209. this._min = 0;
  10210. this._max = 0;
  10211. this._average = 0;
  10212. this._lastSecAverage = 0;
  10213. this._current = 0;
  10214. this._totalValueCount = 0;
  10215. this._totalAccumulated = 0;
  10216. this._lastSecAccumulated = 0;
  10217. this._lastSecTime = 0;
  10218. this._lastSecValueCount = 0;
  10219. }
  10220. Object.defineProperty(PerfCounter.prototype, "min", {
  10221. /**
  10222. * Returns the smallest value ever
  10223. */
  10224. get: function () {
  10225. return this._min;
  10226. },
  10227. enumerable: true,
  10228. configurable: true
  10229. });
  10230. Object.defineProperty(PerfCounter.prototype, "max", {
  10231. /**
  10232. * Returns the biggest value ever
  10233. */
  10234. get: function () {
  10235. return this._max;
  10236. },
  10237. enumerable: true,
  10238. configurable: true
  10239. });
  10240. Object.defineProperty(PerfCounter.prototype, "average", {
  10241. /**
  10242. * Returns the average value since the performance counter is running
  10243. */
  10244. get: function () {
  10245. return this._average;
  10246. },
  10247. enumerable: true,
  10248. configurable: true
  10249. });
  10250. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10251. /**
  10252. * Returns the average value of the last second the counter was monitored
  10253. */
  10254. get: function () {
  10255. return this._lastSecAverage;
  10256. },
  10257. enumerable: true,
  10258. configurable: true
  10259. });
  10260. Object.defineProperty(PerfCounter.prototype, "current", {
  10261. /**
  10262. * Returns the current value
  10263. */
  10264. get: function () {
  10265. return this._current;
  10266. },
  10267. enumerable: true,
  10268. configurable: true
  10269. });
  10270. Object.defineProperty(PerfCounter.prototype, "total", {
  10271. get: function () {
  10272. return this._totalAccumulated;
  10273. },
  10274. enumerable: true,
  10275. configurable: true
  10276. });
  10277. Object.defineProperty(PerfCounter.prototype, "count", {
  10278. get: function () {
  10279. return this._totalValueCount;
  10280. },
  10281. enumerable: true,
  10282. configurable: true
  10283. });
  10284. /**
  10285. * Call this method to start monitoring a new frame.
  10286. * 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.
  10287. */
  10288. PerfCounter.prototype.fetchNewFrame = function () {
  10289. this._totalValueCount++;
  10290. this._current = 0;
  10291. this._lastSecValueCount++;
  10292. };
  10293. /**
  10294. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10295. * @param newCount the count value to add to the monitored count
  10296. * @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.
  10297. */
  10298. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10299. if (!PerfCounter.Enabled) {
  10300. return;
  10301. }
  10302. this._current += newCount;
  10303. if (fetchResult) {
  10304. this._fetchResult();
  10305. }
  10306. };
  10307. /**
  10308. * Start monitoring this performance counter
  10309. */
  10310. PerfCounter.prototype.beginMonitoring = function () {
  10311. if (!PerfCounter.Enabled) {
  10312. return;
  10313. }
  10314. this._startMonitoringTime = Tools.Now;
  10315. };
  10316. /**
  10317. * Compute the time lapsed since the previous beginMonitoring() call.
  10318. * @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
  10319. */
  10320. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10321. if (newFrame === void 0) { newFrame = true; }
  10322. if (!PerfCounter.Enabled) {
  10323. return;
  10324. }
  10325. if (newFrame) {
  10326. this.fetchNewFrame();
  10327. }
  10328. var currentTime = Tools.Now;
  10329. this._current = currentTime - this._startMonitoringTime;
  10330. if (newFrame) {
  10331. this._fetchResult();
  10332. }
  10333. };
  10334. PerfCounter.prototype._fetchResult = function () {
  10335. this._totalAccumulated += this._current;
  10336. this._lastSecAccumulated += this._current;
  10337. // Min/Max update
  10338. this._min = Math.min(this._min, this._current);
  10339. this._max = Math.max(this._max, this._current);
  10340. this._average = this._totalAccumulated / this._totalValueCount;
  10341. // Reset last sec?
  10342. var now = Tools.Now;
  10343. if ((now - this._lastSecTime) > 1000) {
  10344. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10345. this._lastSecTime = now;
  10346. this._lastSecAccumulated = 0;
  10347. this._lastSecValueCount = 0;
  10348. }
  10349. };
  10350. PerfCounter.Enabled = true;
  10351. return PerfCounter;
  10352. }());
  10353. BABYLON.PerfCounter = PerfCounter;
  10354. /**
  10355. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10356. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10357. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10358. * @param name The name of the class, case should be preserved
  10359. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10360. */
  10361. function className(name, module) {
  10362. return function (target) {
  10363. target["__bjsclassName__"] = name;
  10364. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10365. };
  10366. }
  10367. BABYLON.className = className;
  10368. /**
  10369. * An implementation of a loop for asynchronous functions.
  10370. */
  10371. var AsyncLoop = /** @class */ (function () {
  10372. /**
  10373. * Constroctor.
  10374. * @param iterations the number of iterations.
  10375. * @param _fn the function to run each iteration
  10376. * @param _successCallback the callback that will be called upon succesful execution
  10377. * @param offset starting offset.
  10378. */
  10379. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10380. if (offset === void 0) { offset = 0; }
  10381. this.iterations = iterations;
  10382. this._fn = _fn;
  10383. this._successCallback = _successCallback;
  10384. this.index = offset - 1;
  10385. this._done = false;
  10386. }
  10387. /**
  10388. * Execute the next iteration. Must be called after the last iteration was finished.
  10389. */
  10390. AsyncLoop.prototype.executeNext = function () {
  10391. if (!this._done) {
  10392. if (this.index + 1 < this.iterations) {
  10393. ++this.index;
  10394. this._fn(this);
  10395. }
  10396. else {
  10397. this.breakLoop();
  10398. }
  10399. }
  10400. };
  10401. /**
  10402. * Break the loop and run the success callback.
  10403. */
  10404. AsyncLoop.prototype.breakLoop = function () {
  10405. this._done = true;
  10406. this._successCallback();
  10407. };
  10408. /**
  10409. * Helper function
  10410. */
  10411. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10412. if (offset === void 0) { offset = 0; }
  10413. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10414. loop.executeNext();
  10415. return loop;
  10416. };
  10417. /**
  10418. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10419. * @param iterations total number of iterations
  10420. * @param syncedIterations number of synchronous iterations in each async iteration.
  10421. * @param fn the function to call each iteration.
  10422. * @param callback a success call back that will be called when iterating stops.
  10423. * @param breakFunction a break condition (optional)
  10424. * @param timeout timeout settings for the setTimeout function. default - 0.
  10425. * @constructor
  10426. */
  10427. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10428. if (timeout === void 0) { timeout = 0; }
  10429. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10430. if (breakFunction && breakFunction())
  10431. loop.breakLoop();
  10432. else {
  10433. setTimeout(function () {
  10434. for (var i = 0; i < syncedIterations; ++i) {
  10435. var iteration = (loop.index * syncedIterations) + i;
  10436. if (iteration >= iterations)
  10437. break;
  10438. fn(iteration);
  10439. if (breakFunction && breakFunction()) {
  10440. loop.breakLoop();
  10441. break;
  10442. }
  10443. }
  10444. loop.executeNext();
  10445. }, timeout);
  10446. }
  10447. }, callback);
  10448. };
  10449. return AsyncLoop;
  10450. }());
  10451. BABYLON.AsyncLoop = AsyncLoop;
  10452. })(BABYLON || (BABYLON = {}));
  10453. //# sourceMappingURL=babylon.tools.js.map
  10454. var BABYLON;
  10455. (function (BABYLON) {
  10456. var PromiseStates;
  10457. (function (PromiseStates) {
  10458. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10459. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10460. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10461. })(PromiseStates || (PromiseStates = {}));
  10462. var FulFillmentAgregator = /** @class */ (function () {
  10463. function FulFillmentAgregator() {
  10464. this.count = 0;
  10465. this.target = 0;
  10466. this.results = [];
  10467. }
  10468. return FulFillmentAgregator;
  10469. }());
  10470. var InternalPromise = /** @class */ (function () {
  10471. function InternalPromise(resolver) {
  10472. var _this = this;
  10473. this._state = PromiseStates.Pending;
  10474. this._children = new Array();
  10475. this._rejectWasConsumed = false;
  10476. if (!resolver) {
  10477. return;
  10478. }
  10479. try {
  10480. resolver(function (value) {
  10481. _this._resolve(value);
  10482. }, function (reason) {
  10483. _this._reject(reason);
  10484. });
  10485. }
  10486. catch (e) {
  10487. this._reject(e);
  10488. }
  10489. }
  10490. Object.defineProperty(InternalPromise.prototype, "_result", {
  10491. get: function () {
  10492. return this._resultValue;
  10493. },
  10494. set: function (value) {
  10495. this._resultValue = value;
  10496. if (this._parent && this._parent._result === undefined) {
  10497. this._parent._result = value;
  10498. }
  10499. },
  10500. enumerable: true,
  10501. configurable: true
  10502. });
  10503. InternalPromise.prototype.catch = function (onRejected) {
  10504. return this.then(undefined, onRejected);
  10505. };
  10506. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10507. var _this = this;
  10508. var newPromise = new InternalPromise();
  10509. newPromise._onFulfilled = onFulfilled;
  10510. newPromise._onRejected = onRejected;
  10511. // Composition
  10512. this._children.push(newPromise);
  10513. newPromise._parent = this;
  10514. if (this._state !== PromiseStates.Pending) {
  10515. BABYLON.Tools.SetImmediate(function () {
  10516. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10517. var returnedValue = newPromise._resolve(_this._result);
  10518. if (returnedValue !== undefined && returnedValue !== null) {
  10519. if (returnedValue._state !== undefined) {
  10520. var returnedPromise = returnedValue;
  10521. newPromise._children.push(returnedPromise);
  10522. returnedPromise._parent = newPromise;
  10523. newPromise = returnedPromise;
  10524. }
  10525. else {
  10526. newPromise._result = returnedValue;
  10527. }
  10528. }
  10529. }
  10530. else {
  10531. newPromise._reject(_this._reason);
  10532. }
  10533. });
  10534. }
  10535. return newPromise;
  10536. };
  10537. InternalPromise.prototype._moveChildren = function (children) {
  10538. var _this = this;
  10539. var _a;
  10540. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10541. this._children.forEach(function (child) {
  10542. child._parent = _this;
  10543. });
  10544. if (this._state === PromiseStates.Fulfilled) {
  10545. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10546. var child = _b[_i];
  10547. child._resolve(this._result);
  10548. }
  10549. }
  10550. else if (this._state === PromiseStates.Rejected) {
  10551. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10552. var child = _d[_c];
  10553. child._reject(this._reason);
  10554. }
  10555. }
  10556. };
  10557. InternalPromise.prototype._resolve = function (value) {
  10558. try {
  10559. this._state = PromiseStates.Fulfilled;
  10560. var returnedValue = null;
  10561. if (this._onFulfilled) {
  10562. returnedValue = this._onFulfilled(value);
  10563. }
  10564. if (returnedValue !== undefined && returnedValue !== null) {
  10565. if (returnedValue._state !== undefined) {
  10566. // Transmit children
  10567. var returnedPromise = returnedValue;
  10568. returnedPromise._parent = this;
  10569. returnedPromise._moveChildren(this._children);
  10570. value = returnedPromise._result;
  10571. }
  10572. else {
  10573. value = returnedValue;
  10574. }
  10575. }
  10576. this._result = value;
  10577. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10578. var child = _a[_i];
  10579. child._resolve(value);
  10580. }
  10581. this._children.length = 0;
  10582. delete this._onFulfilled;
  10583. delete this._onRejected;
  10584. }
  10585. catch (e) {
  10586. this._reject(e, true);
  10587. }
  10588. };
  10589. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10590. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10591. this._state = PromiseStates.Rejected;
  10592. this._reason = reason;
  10593. if (this._onRejected && !onLocalThrow) {
  10594. try {
  10595. this._onRejected(reason);
  10596. this._rejectWasConsumed = true;
  10597. }
  10598. catch (e) {
  10599. reason = e;
  10600. }
  10601. }
  10602. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10603. var child = _a[_i];
  10604. if (this._rejectWasConsumed) {
  10605. child._resolve(null);
  10606. }
  10607. else {
  10608. child._reject(reason);
  10609. }
  10610. }
  10611. this._children.length = 0;
  10612. delete this._onFulfilled;
  10613. delete this._onRejected;
  10614. };
  10615. InternalPromise.resolve = function (value) {
  10616. var newPromise = new InternalPromise();
  10617. newPromise._resolve(value);
  10618. return newPromise;
  10619. };
  10620. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10621. promise.then(function (value) {
  10622. agregator.results[index] = value;
  10623. agregator.count++;
  10624. if (agregator.count === agregator.target) {
  10625. agregator.rootPromise._resolve(agregator.results);
  10626. }
  10627. return null;
  10628. }, function (reason) {
  10629. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10630. agregator.rootPromise._reject(reason);
  10631. }
  10632. });
  10633. };
  10634. InternalPromise.all = function (promises) {
  10635. var newPromise = new InternalPromise();
  10636. var agregator = new FulFillmentAgregator();
  10637. agregator.target = promises.length;
  10638. agregator.rootPromise = newPromise;
  10639. if (promises.length) {
  10640. for (var index = 0; index < promises.length; index++) {
  10641. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10642. }
  10643. }
  10644. else {
  10645. newPromise._resolve([]);
  10646. }
  10647. return newPromise;
  10648. };
  10649. InternalPromise.race = function (promises) {
  10650. var newPromise = new InternalPromise();
  10651. if (promises.length) {
  10652. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10653. var promise = promises_1[_i];
  10654. promise.then(function (value) {
  10655. if (newPromise) {
  10656. newPromise._resolve(value);
  10657. newPromise = null;
  10658. }
  10659. return null;
  10660. }, function (reason) {
  10661. if (newPromise) {
  10662. newPromise._reject(reason);
  10663. newPromise = null;
  10664. }
  10665. });
  10666. }
  10667. }
  10668. return newPromise;
  10669. };
  10670. return InternalPromise;
  10671. }());
  10672. /**
  10673. * Helper class that provides a small promise polyfill
  10674. */
  10675. var PromisePolyfill = /** @class */ (function () {
  10676. function PromisePolyfill() {
  10677. }
  10678. /**
  10679. * Static function used to check if the polyfill is required
  10680. * If this is the case then the function will inject the polyfill to window.Promise
  10681. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10682. */
  10683. PromisePolyfill.Apply = function (force) {
  10684. if (force === void 0) { force = false; }
  10685. if (force || typeof Promise === 'undefined') {
  10686. var root = window;
  10687. root.Promise = InternalPromise;
  10688. }
  10689. };
  10690. return PromisePolyfill;
  10691. }());
  10692. BABYLON.PromisePolyfill = PromisePolyfill;
  10693. })(BABYLON || (BABYLON = {}));
  10694. //# sourceMappingURL=babylon.promise.js.map
  10695. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10696. var BABYLON;
  10697. (function (BABYLON) {
  10698. /**
  10699. * Helper class to push actions to a pool of workers.
  10700. */
  10701. var WorkerPool = /** @class */ (function () {
  10702. /**
  10703. * Constructor
  10704. * @param workers Array of workers to use for actions
  10705. */
  10706. function WorkerPool(workers) {
  10707. this._pendingActions = new Array();
  10708. this._workerInfos = workers.map(function (worker) { return ({
  10709. worker: worker,
  10710. active: false
  10711. }); });
  10712. }
  10713. /**
  10714. * Terminates all workers and clears any pending actions.
  10715. */
  10716. WorkerPool.prototype.dispose = function () {
  10717. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10718. var workerInfo = _a[_i];
  10719. workerInfo.worker.terminate();
  10720. }
  10721. delete this._workerInfos;
  10722. delete this._pendingActions;
  10723. };
  10724. /**
  10725. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10726. * pended until a worker has completed its action.
  10727. * @param action The action to perform. Call onComplete when the action is complete.
  10728. */
  10729. WorkerPool.prototype.push = function (action) {
  10730. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10731. var workerInfo = _a[_i];
  10732. if (!workerInfo.active) {
  10733. this._execute(workerInfo, action);
  10734. return;
  10735. }
  10736. }
  10737. this._pendingActions.push(action);
  10738. };
  10739. WorkerPool.prototype._execute = function (workerInfo, action) {
  10740. var _this = this;
  10741. workerInfo.active = true;
  10742. action(workerInfo.worker, function () {
  10743. workerInfo.active = false;
  10744. var nextAction = _this._pendingActions.shift();
  10745. if (nextAction) {
  10746. _this._execute(workerInfo, nextAction);
  10747. }
  10748. });
  10749. };
  10750. return WorkerPool;
  10751. }());
  10752. BABYLON.WorkerPool = WorkerPool;
  10753. })(BABYLON || (BABYLON = {}));
  10754. //# sourceMappingURL=babylon.workerPool.js.map
  10755. var BABYLON;
  10756. (function (BABYLON) {
  10757. /**
  10758. * @hidden
  10759. **/
  10760. var _AlphaState = /** @class */ (function () {
  10761. /**
  10762. * Initializes the state.
  10763. */
  10764. function _AlphaState() {
  10765. this._isAlphaBlendDirty = false;
  10766. this._isBlendFunctionParametersDirty = false;
  10767. this._isBlendEquationParametersDirty = false;
  10768. this._isBlendConstantsDirty = false;
  10769. this._alphaBlend = false;
  10770. this._blendFunctionParameters = new Array(4);
  10771. this._blendEquationParameters = new Array(2);
  10772. this._blendConstants = new Array(4);
  10773. this.reset();
  10774. }
  10775. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10776. get: function () {
  10777. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10778. },
  10779. enumerable: true,
  10780. configurable: true
  10781. });
  10782. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10783. get: function () {
  10784. return this._alphaBlend;
  10785. },
  10786. set: function (value) {
  10787. if (this._alphaBlend === value) {
  10788. return;
  10789. }
  10790. this._alphaBlend = value;
  10791. this._isAlphaBlendDirty = true;
  10792. },
  10793. enumerable: true,
  10794. configurable: true
  10795. });
  10796. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10797. if (this._blendConstants[0] === r &&
  10798. this._blendConstants[1] === g &&
  10799. this._blendConstants[2] === b &&
  10800. this._blendConstants[3] === a) {
  10801. return;
  10802. }
  10803. this._blendConstants[0] = r;
  10804. this._blendConstants[1] = g;
  10805. this._blendConstants[2] = b;
  10806. this._blendConstants[3] = a;
  10807. this._isBlendConstantsDirty = true;
  10808. };
  10809. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10810. if (this._blendFunctionParameters[0] === value0 &&
  10811. this._blendFunctionParameters[1] === value1 &&
  10812. this._blendFunctionParameters[2] === value2 &&
  10813. this._blendFunctionParameters[3] === value3) {
  10814. return;
  10815. }
  10816. this._blendFunctionParameters[0] = value0;
  10817. this._blendFunctionParameters[1] = value1;
  10818. this._blendFunctionParameters[2] = value2;
  10819. this._blendFunctionParameters[3] = value3;
  10820. this._isBlendFunctionParametersDirty = true;
  10821. };
  10822. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10823. if (this._blendEquationParameters[0] === rgb &&
  10824. this._blendEquationParameters[1] === alpha) {
  10825. return;
  10826. }
  10827. this._blendEquationParameters[0] = rgb;
  10828. this._blendEquationParameters[1] = alpha;
  10829. this._isBlendEquationParametersDirty = true;
  10830. };
  10831. _AlphaState.prototype.reset = function () {
  10832. this._alphaBlend = false;
  10833. this._blendFunctionParameters[0] = null;
  10834. this._blendFunctionParameters[1] = null;
  10835. this._blendFunctionParameters[2] = null;
  10836. this._blendFunctionParameters[3] = null;
  10837. this._blendEquationParameters[0] = null;
  10838. this._blendEquationParameters[1] = null;
  10839. this._blendConstants[0] = null;
  10840. this._blendConstants[1] = null;
  10841. this._blendConstants[2] = null;
  10842. this._blendConstants[3] = null;
  10843. this._isAlphaBlendDirty = true;
  10844. this._isBlendFunctionParametersDirty = false;
  10845. this._isBlendEquationParametersDirty = false;
  10846. this._isBlendConstantsDirty = false;
  10847. };
  10848. _AlphaState.prototype.apply = function (gl) {
  10849. if (!this.isDirty) {
  10850. return;
  10851. }
  10852. // Alpha blend
  10853. if (this._isAlphaBlendDirty) {
  10854. if (this._alphaBlend) {
  10855. gl.enable(gl.BLEND);
  10856. }
  10857. else {
  10858. gl.disable(gl.BLEND);
  10859. }
  10860. this._isAlphaBlendDirty = false;
  10861. }
  10862. // Alpha function
  10863. if (this._isBlendFunctionParametersDirty) {
  10864. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10865. this._isBlendFunctionParametersDirty = false;
  10866. }
  10867. // Alpha equation
  10868. if (this._isBlendEquationParametersDirty) {
  10869. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10870. this._isBlendEquationParametersDirty = false;
  10871. }
  10872. // Constants
  10873. if (this._isBlendConstantsDirty) {
  10874. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10875. this._isBlendConstantsDirty = false;
  10876. }
  10877. };
  10878. return _AlphaState;
  10879. }());
  10880. BABYLON._AlphaState = _AlphaState;
  10881. })(BABYLON || (BABYLON = {}));
  10882. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10883. var BABYLON;
  10884. (function (BABYLON) {
  10885. /**
  10886. * @hidden
  10887. **/
  10888. var _DepthCullingState = /** @class */ (function () {
  10889. /**
  10890. * Initializes the state.
  10891. */
  10892. function _DepthCullingState() {
  10893. this._isDepthTestDirty = false;
  10894. this._isDepthMaskDirty = false;
  10895. this._isDepthFuncDirty = false;
  10896. this._isCullFaceDirty = false;
  10897. this._isCullDirty = false;
  10898. this._isZOffsetDirty = false;
  10899. this._isFrontFaceDirty = false;
  10900. this.reset();
  10901. }
  10902. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10903. get: function () {
  10904. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10905. },
  10906. enumerable: true,
  10907. configurable: true
  10908. });
  10909. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10910. get: function () {
  10911. return this._zOffset;
  10912. },
  10913. set: function (value) {
  10914. if (this._zOffset === value) {
  10915. return;
  10916. }
  10917. this._zOffset = value;
  10918. this._isZOffsetDirty = true;
  10919. },
  10920. enumerable: true,
  10921. configurable: true
  10922. });
  10923. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10924. get: function () {
  10925. return this._cullFace;
  10926. },
  10927. set: function (value) {
  10928. if (this._cullFace === value) {
  10929. return;
  10930. }
  10931. this._cullFace = value;
  10932. this._isCullFaceDirty = true;
  10933. },
  10934. enumerable: true,
  10935. configurable: true
  10936. });
  10937. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10938. get: function () {
  10939. return this._cull;
  10940. },
  10941. set: function (value) {
  10942. if (this._cull === value) {
  10943. return;
  10944. }
  10945. this._cull = value;
  10946. this._isCullDirty = true;
  10947. },
  10948. enumerable: true,
  10949. configurable: true
  10950. });
  10951. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10952. get: function () {
  10953. return this._depthFunc;
  10954. },
  10955. set: function (value) {
  10956. if (this._depthFunc === value) {
  10957. return;
  10958. }
  10959. this._depthFunc = value;
  10960. this._isDepthFuncDirty = true;
  10961. },
  10962. enumerable: true,
  10963. configurable: true
  10964. });
  10965. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10966. get: function () {
  10967. return this._depthMask;
  10968. },
  10969. set: function (value) {
  10970. if (this._depthMask === value) {
  10971. return;
  10972. }
  10973. this._depthMask = value;
  10974. this._isDepthMaskDirty = true;
  10975. },
  10976. enumerable: true,
  10977. configurable: true
  10978. });
  10979. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10980. get: function () {
  10981. return this._depthTest;
  10982. },
  10983. set: function (value) {
  10984. if (this._depthTest === value) {
  10985. return;
  10986. }
  10987. this._depthTest = value;
  10988. this._isDepthTestDirty = true;
  10989. },
  10990. enumerable: true,
  10991. configurable: true
  10992. });
  10993. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10994. get: function () {
  10995. return this._frontFace;
  10996. },
  10997. set: function (value) {
  10998. if (this._frontFace === value) {
  10999. return;
  11000. }
  11001. this._frontFace = value;
  11002. this._isFrontFaceDirty = true;
  11003. },
  11004. enumerable: true,
  11005. configurable: true
  11006. });
  11007. _DepthCullingState.prototype.reset = function () {
  11008. this._depthMask = true;
  11009. this._depthTest = true;
  11010. this._depthFunc = null;
  11011. this._cullFace = null;
  11012. this._cull = null;
  11013. this._zOffset = 0;
  11014. this._frontFace = null;
  11015. this._isDepthTestDirty = true;
  11016. this._isDepthMaskDirty = true;
  11017. this._isDepthFuncDirty = false;
  11018. this._isCullFaceDirty = false;
  11019. this._isCullDirty = false;
  11020. this._isZOffsetDirty = false;
  11021. this._isFrontFaceDirty = false;
  11022. };
  11023. _DepthCullingState.prototype.apply = function (gl) {
  11024. if (!this.isDirty) {
  11025. return;
  11026. }
  11027. // Cull
  11028. if (this._isCullDirty) {
  11029. if (this.cull) {
  11030. gl.enable(gl.CULL_FACE);
  11031. }
  11032. else {
  11033. gl.disable(gl.CULL_FACE);
  11034. }
  11035. this._isCullDirty = false;
  11036. }
  11037. // Cull face
  11038. if (this._isCullFaceDirty) {
  11039. gl.cullFace(this.cullFace);
  11040. this._isCullFaceDirty = false;
  11041. }
  11042. // Depth mask
  11043. if (this._isDepthMaskDirty) {
  11044. gl.depthMask(this.depthMask);
  11045. this._isDepthMaskDirty = false;
  11046. }
  11047. // Depth test
  11048. if (this._isDepthTestDirty) {
  11049. if (this.depthTest) {
  11050. gl.enable(gl.DEPTH_TEST);
  11051. }
  11052. else {
  11053. gl.disable(gl.DEPTH_TEST);
  11054. }
  11055. this._isDepthTestDirty = false;
  11056. }
  11057. // Depth func
  11058. if (this._isDepthFuncDirty) {
  11059. gl.depthFunc(this.depthFunc);
  11060. this._isDepthFuncDirty = false;
  11061. }
  11062. // zOffset
  11063. if (this._isZOffsetDirty) {
  11064. if (this.zOffset) {
  11065. gl.enable(gl.POLYGON_OFFSET_FILL);
  11066. gl.polygonOffset(this.zOffset, 0);
  11067. }
  11068. else {
  11069. gl.disable(gl.POLYGON_OFFSET_FILL);
  11070. }
  11071. this._isZOffsetDirty = false;
  11072. }
  11073. // Front face
  11074. if (this._isFrontFaceDirty) {
  11075. gl.frontFace(this.frontFace);
  11076. this._isFrontFaceDirty = false;
  11077. }
  11078. };
  11079. return _DepthCullingState;
  11080. }());
  11081. BABYLON._DepthCullingState = _DepthCullingState;
  11082. })(BABYLON || (BABYLON = {}));
  11083. //# sourceMappingURL=babylon.depthCullingState.js.map
  11084. var BABYLON;
  11085. (function (BABYLON) {
  11086. /**
  11087. * @hidden
  11088. **/
  11089. var _StencilState = /** @class */ (function () {
  11090. function _StencilState() {
  11091. this._isStencilTestDirty = false;
  11092. this._isStencilMaskDirty = false;
  11093. this._isStencilFuncDirty = false;
  11094. this._isStencilOpDirty = false;
  11095. this.reset();
  11096. }
  11097. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11098. get: function () {
  11099. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11100. },
  11101. enumerable: true,
  11102. configurable: true
  11103. });
  11104. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11105. get: function () {
  11106. return this._stencilFunc;
  11107. },
  11108. set: function (value) {
  11109. if (this._stencilFunc === value) {
  11110. return;
  11111. }
  11112. this._stencilFunc = value;
  11113. this._isStencilFuncDirty = true;
  11114. },
  11115. enumerable: true,
  11116. configurable: true
  11117. });
  11118. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11119. get: function () {
  11120. return this._stencilFuncRef;
  11121. },
  11122. set: function (value) {
  11123. if (this._stencilFuncRef === value) {
  11124. return;
  11125. }
  11126. this._stencilFuncRef = value;
  11127. this._isStencilFuncDirty = true;
  11128. },
  11129. enumerable: true,
  11130. configurable: true
  11131. });
  11132. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11133. get: function () {
  11134. return this._stencilFuncMask;
  11135. },
  11136. set: function (value) {
  11137. if (this._stencilFuncMask === value) {
  11138. return;
  11139. }
  11140. this._stencilFuncMask = value;
  11141. this._isStencilFuncDirty = true;
  11142. },
  11143. enumerable: true,
  11144. configurable: true
  11145. });
  11146. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11147. get: function () {
  11148. return this._stencilOpStencilFail;
  11149. },
  11150. set: function (value) {
  11151. if (this._stencilOpStencilFail === value) {
  11152. return;
  11153. }
  11154. this._stencilOpStencilFail = value;
  11155. this._isStencilOpDirty = true;
  11156. },
  11157. enumerable: true,
  11158. configurable: true
  11159. });
  11160. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11161. get: function () {
  11162. return this._stencilOpDepthFail;
  11163. },
  11164. set: function (value) {
  11165. if (this._stencilOpDepthFail === value) {
  11166. return;
  11167. }
  11168. this._stencilOpDepthFail = value;
  11169. this._isStencilOpDirty = true;
  11170. },
  11171. enumerable: true,
  11172. configurable: true
  11173. });
  11174. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11175. get: function () {
  11176. return this._stencilOpStencilDepthPass;
  11177. },
  11178. set: function (value) {
  11179. if (this._stencilOpStencilDepthPass === value) {
  11180. return;
  11181. }
  11182. this._stencilOpStencilDepthPass = value;
  11183. this._isStencilOpDirty = true;
  11184. },
  11185. enumerable: true,
  11186. configurable: true
  11187. });
  11188. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11189. get: function () {
  11190. return this._stencilMask;
  11191. },
  11192. set: function (value) {
  11193. if (this._stencilMask === value) {
  11194. return;
  11195. }
  11196. this._stencilMask = value;
  11197. this._isStencilMaskDirty = true;
  11198. },
  11199. enumerable: true,
  11200. configurable: true
  11201. });
  11202. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11203. get: function () {
  11204. return this._stencilTest;
  11205. },
  11206. set: function (value) {
  11207. if (this._stencilTest === value) {
  11208. return;
  11209. }
  11210. this._stencilTest = value;
  11211. this._isStencilTestDirty = true;
  11212. },
  11213. enumerable: true,
  11214. configurable: true
  11215. });
  11216. _StencilState.prototype.reset = function () {
  11217. this._stencilTest = false;
  11218. this._stencilMask = 0xFF;
  11219. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11220. this._stencilFuncRef = 1;
  11221. this._stencilFuncMask = 0xFF;
  11222. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11223. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11224. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11225. this._isStencilTestDirty = true;
  11226. this._isStencilMaskDirty = true;
  11227. this._isStencilFuncDirty = true;
  11228. this._isStencilOpDirty = true;
  11229. };
  11230. _StencilState.prototype.apply = function (gl) {
  11231. if (!this.isDirty) {
  11232. return;
  11233. }
  11234. // Stencil test
  11235. if (this._isStencilTestDirty) {
  11236. if (this.stencilTest) {
  11237. gl.enable(gl.STENCIL_TEST);
  11238. }
  11239. else {
  11240. gl.disable(gl.STENCIL_TEST);
  11241. }
  11242. this._isStencilTestDirty = false;
  11243. }
  11244. // Stencil mask
  11245. if (this._isStencilMaskDirty) {
  11246. gl.stencilMask(this.stencilMask);
  11247. this._isStencilMaskDirty = false;
  11248. }
  11249. // Stencil func
  11250. if (this._isStencilFuncDirty) {
  11251. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11252. this._isStencilFuncDirty = false;
  11253. }
  11254. // Stencil op
  11255. if (this._isStencilOpDirty) {
  11256. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11257. this._isStencilOpDirty = false;
  11258. }
  11259. };
  11260. return _StencilState;
  11261. }());
  11262. BABYLON._StencilState = _StencilState;
  11263. })(BABYLON || (BABYLON = {}));
  11264. //# sourceMappingURL=babylon.stencilState.js.map
  11265. var __assign = (this && this.__assign) || function () {
  11266. __assign = Object.assign || function(t) {
  11267. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11268. s = arguments[i];
  11269. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11270. t[p] = s[p];
  11271. }
  11272. return t;
  11273. };
  11274. return __assign.apply(this, arguments);
  11275. };
  11276. var BABYLON;
  11277. (function (BABYLON) {
  11278. /**
  11279. * Keeps track of all the buffer info used in engine.
  11280. */
  11281. var BufferPointer = /** @class */ (function () {
  11282. function BufferPointer() {
  11283. }
  11284. return BufferPointer;
  11285. }());
  11286. /**
  11287. * Interface for attribute information associated with buffer instanciation
  11288. */
  11289. var InstancingAttributeInfo = /** @class */ (function () {
  11290. function InstancingAttributeInfo() {
  11291. }
  11292. return InstancingAttributeInfo;
  11293. }());
  11294. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11295. /**
  11296. * Define options used to create a render target texture
  11297. */
  11298. var RenderTargetCreationOptions = /** @class */ (function () {
  11299. function RenderTargetCreationOptions() {
  11300. }
  11301. return RenderTargetCreationOptions;
  11302. }());
  11303. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11304. /**
  11305. * Define options used to create a depth texture
  11306. */
  11307. var DepthTextureCreationOptions = /** @class */ (function () {
  11308. function DepthTextureCreationOptions() {
  11309. }
  11310. return DepthTextureCreationOptions;
  11311. }());
  11312. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11313. /**
  11314. * Class used to describe the capabilities of the engine relatively to the current browser
  11315. */
  11316. var EngineCapabilities = /** @class */ (function () {
  11317. function EngineCapabilities() {
  11318. }
  11319. return EngineCapabilities;
  11320. }());
  11321. BABYLON.EngineCapabilities = EngineCapabilities;
  11322. /**
  11323. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11324. */
  11325. var Engine = /** @class */ (function () {
  11326. /**
  11327. * Creates a new engine
  11328. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  11329. * @param antialias defines enable antialiasing (default: false)
  11330. * @param options defines further options to be sent to the getContext() function
  11331. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11332. */
  11333. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11334. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11335. var _this = this;
  11336. // Public members
  11337. /**
  11338. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11339. */
  11340. this.forcePOTTextures = false;
  11341. /**
  11342. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11343. */
  11344. this.isFullscreen = false;
  11345. /**
  11346. * Gets a boolean indicating if the pointer is currently locked
  11347. */
  11348. this.isPointerLock = false;
  11349. /**
  11350. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11351. */
  11352. this.cullBackFaces = true;
  11353. /**
  11354. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11355. */
  11356. this.renderEvenInBackground = true;
  11357. /**
  11358. * Gets or sets a boolean indicating that cache can be kept between frames
  11359. */
  11360. this.preventCacheWipeBetweenFrames = false;
  11361. /**
  11362. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11363. **/
  11364. this.enableOfflineSupport = false;
  11365. /**
  11366. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11367. **/
  11368. this.disableManifestCheck = false;
  11369. /**
  11370. * Gets the list of created scenes
  11371. */
  11372. this.scenes = new Array();
  11373. /**
  11374. * Gets the list of created postprocesses
  11375. */
  11376. this.postProcesses = new Array();
  11377. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11378. this.validateShaderPrograms = false;
  11379. // Observables
  11380. /**
  11381. * Observable event triggered each time the rendering canvas is resized
  11382. */
  11383. this.onResizeObservable = new BABYLON.Observable();
  11384. /**
  11385. * Observable event triggered each time the canvas loses focus
  11386. */
  11387. this.onCanvasBlurObservable = new BABYLON.Observable();
  11388. /**
  11389. * Observable event triggered each time the canvas gains focus
  11390. */
  11391. this.onCanvasFocusObservable = new BABYLON.Observable();
  11392. /**
  11393. * Observable event triggered each time the canvas receives pointerout event
  11394. */
  11395. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11396. /**
  11397. * Observable event triggered before each texture is initialized
  11398. */
  11399. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11400. //WebVR
  11401. this._vrDisplay = undefined;
  11402. this._vrSupported = false;
  11403. this._vrExclusivePointerMode = false;
  11404. // Uniform buffers list
  11405. /**
  11406. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11407. */
  11408. this.disableUniformBuffers = false;
  11409. /** @hidden */
  11410. this._uniformBuffers = new Array();
  11411. // Observables
  11412. /**
  11413. * Observable raised when the engine begins a new frame
  11414. */
  11415. this.onBeginFrameObservable = new BABYLON.Observable();
  11416. /**
  11417. * Observable raised when the engine ends the current frame
  11418. */
  11419. this.onEndFrameObservable = new BABYLON.Observable();
  11420. /**
  11421. * Observable raised when the engine is about to compile a shader
  11422. */
  11423. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11424. /**
  11425. * Observable raised when the engine has jsut compiled a shader
  11426. */
  11427. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11428. this._windowIsBackground = false;
  11429. this._webGLVersion = 1.0;
  11430. /** @hidden */
  11431. this._badOS = false;
  11432. /** @hidden */
  11433. this._badDesktopOS = false;
  11434. /**
  11435. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11436. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11437. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11438. */
  11439. this.disableTextureBindingOptimization = false;
  11440. /**
  11441. * Observable signaled when VR display mode changes
  11442. */
  11443. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11444. /**
  11445. * Observable signaled when VR request present is complete
  11446. */
  11447. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11448. /**
  11449. * Observable signaled when VR request present starts
  11450. */
  11451. this.onVRRequestPresentStart = new BABYLON.Observable();
  11452. this._colorWrite = true;
  11453. /** @hidden */
  11454. this._drawCalls = new BABYLON.PerfCounter();
  11455. /** @hidden */
  11456. this._textureCollisions = new BABYLON.PerfCounter();
  11457. this._renderingQueueLaunched = false;
  11458. this._activeRenderLoops = new Array();
  11459. // Deterministic lockstepMaxSteps
  11460. this._deterministicLockstep = false;
  11461. this._lockstepMaxSteps = 4;
  11462. // Lost context
  11463. /**
  11464. * Observable signaled when a context lost event is raised
  11465. */
  11466. this.onContextLostObservable = new BABYLON.Observable();
  11467. /**
  11468. * Observable signaled when a context restored event is raised
  11469. */
  11470. this.onContextRestoredObservable = new BABYLON.Observable();
  11471. this._contextWasLost = false;
  11472. this._doNotHandleContextLost = false;
  11473. // FPS
  11474. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11475. this._fps = 60;
  11476. this._deltaTime = 0;
  11477. /**
  11478. * Turn this value on if you want to pause FPS computation when in background
  11479. */
  11480. this.disablePerformanceMonitorInBackground = false;
  11481. // States
  11482. /** @hidden */
  11483. this._depthCullingState = new BABYLON._DepthCullingState();
  11484. /** @hidden */
  11485. this._stencilState = new BABYLON._StencilState();
  11486. /** @hidden */
  11487. this._alphaState = new BABYLON._AlphaState();
  11488. /** @hidden */
  11489. this._alphaMode = Engine.ALPHA_DISABLE;
  11490. // Cache
  11491. this._internalTexturesCache = new Array();
  11492. /** @hidden */
  11493. this._activeChannel = 0;
  11494. this._currentTextureChannel = -1;
  11495. /** @hidden */
  11496. this._boundTexturesCache = {};
  11497. this._compiledEffects = {};
  11498. this._vertexAttribArraysEnabled = [];
  11499. this._uintIndicesCurrentlySet = false;
  11500. this._currentBoundBuffer = new Array();
  11501. /** @hidden */
  11502. this._currentFramebuffer = null;
  11503. this._currentBufferPointers = new Array();
  11504. this._currentInstanceLocations = new Array();
  11505. this._currentInstanceBuffers = new Array();
  11506. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11507. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11508. this._vaoRecordInProgress = false;
  11509. this._mustWipeVertexAttributes = false;
  11510. this._nextFreeTextureSlots = new Array();
  11511. this._maxSimultaneousTextures = 0;
  11512. this._activeRequests = new Array();
  11513. // Hardware supported Compressed Textures
  11514. this._texturesSupported = new Array();
  11515. /**
  11516. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11517. */
  11518. this.premultipliedAlpha = true;
  11519. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11520. this._onVRFullScreenTriggered = function () {
  11521. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11522. //get the old size before we change
  11523. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11524. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11525. //get the width and height, change the render size
  11526. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11527. _this.setHardwareScalingLevel(1);
  11528. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11529. }
  11530. else {
  11531. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11532. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11533. }
  11534. };
  11535. this._unpackFlipYCached = null;
  11536. /**
  11537. * In case you are sharing the context with other applications, it might
  11538. * be interested to not cache the unpack flip y state to ensure a consistent
  11539. * value would be set.
  11540. */
  11541. this.enableUnpackFlipYCached = true;
  11542. this._boundUniforms = {};
  11543. // Register promises
  11544. BABYLON.PromisePolyfill.Apply();
  11545. var canvas = null;
  11546. Engine.Instances.push(this);
  11547. if (!canvasOrContext) {
  11548. return;
  11549. }
  11550. options = options || {};
  11551. if (canvasOrContext.getContext) {
  11552. canvas = canvasOrContext;
  11553. this._renderingCanvas = canvas;
  11554. if (antialias != null) {
  11555. options.antialias = antialias;
  11556. }
  11557. if (options.deterministicLockstep === undefined) {
  11558. options.deterministicLockstep = false;
  11559. }
  11560. if (options.lockstepMaxSteps === undefined) {
  11561. options.lockstepMaxSteps = 4;
  11562. }
  11563. if (options.preserveDrawingBuffer === undefined) {
  11564. options.preserveDrawingBuffer = false;
  11565. }
  11566. if (options.audioEngine === undefined) {
  11567. options.audioEngine = true;
  11568. }
  11569. if (options.stencil === undefined) {
  11570. options.stencil = true;
  11571. }
  11572. if (options.premultipliedAlpha === false) {
  11573. this.premultipliedAlpha = false;
  11574. }
  11575. this._deterministicLockstep = options.deterministicLockstep;
  11576. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11577. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11578. // Exceptions
  11579. if (navigator && navigator.userAgent) {
  11580. var ua = navigator.userAgent;
  11581. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11582. var exception = _a[_i];
  11583. var key = exception.key;
  11584. var targets = exception.targets;
  11585. if (ua.indexOf(key) > -1) {
  11586. if (exception.capture && exception.captureConstraint) {
  11587. var capture = exception.capture;
  11588. var constraint = exception.captureConstraint;
  11589. var regex = new RegExp(capture);
  11590. var matches = regex.exec(ua);
  11591. if (matches && matches.length > 0) {
  11592. var capturedValue = parseInt(matches[matches.length - 1]);
  11593. if (capturedValue >= constraint) {
  11594. continue;
  11595. }
  11596. }
  11597. }
  11598. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11599. var target = targets_1[_b];
  11600. switch (target) {
  11601. case "uniformBuffer":
  11602. this.disableUniformBuffers = true;
  11603. break;
  11604. case "textureBindingOptimization":
  11605. this.disableTextureBindingOptimization = true;
  11606. break;
  11607. }
  11608. }
  11609. }
  11610. }
  11611. }
  11612. // GL
  11613. if (!options.disableWebGL2Support) {
  11614. try {
  11615. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11616. if (this._gl) {
  11617. this._webGLVersion = 2.0;
  11618. }
  11619. }
  11620. catch (e) {
  11621. // Do nothing
  11622. }
  11623. }
  11624. if (!this._gl) {
  11625. if (!canvas) {
  11626. throw new Error("The provided canvas is null or undefined.");
  11627. }
  11628. try {
  11629. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11630. }
  11631. catch (e) {
  11632. throw new Error("WebGL not supported");
  11633. }
  11634. }
  11635. if (!this._gl) {
  11636. throw new Error("WebGL not supported");
  11637. }
  11638. this._onCanvasFocus = function () {
  11639. _this.onCanvasFocusObservable.notifyObservers(_this);
  11640. };
  11641. this._onCanvasBlur = function () {
  11642. _this.onCanvasBlurObservable.notifyObservers(_this);
  11643. };
  11644. canvas.addEventListener("focus", this._onCanvasFocus);
  11645. canvas.addEventListener("blur", this._onCanvasBlur);
  11646. this._onBlur = function () {
  11647. if (_this.disablePerformanceMonitorInBackground) {
  11648. _this._performanceMonitor.disable();
  11649. }
  11650. _this._windowIsBackground = true;
  11651. };
  11652. this._onFocus = function () {
  11653. if (_this.disablePerformanceMonitorInBackground) {
  11654. _this._performanceMonitor.enable();
  11655. }
  11656. _this._windowIsBackground = false;
  11657. };
  11658. this._onCanvasPointerOut = function (ev) {
  11659. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11660. };
  11661. window.addEventListener("blur", this._onBlur);
  11662. window.addEventListener("focus", this._onFocus);
  11663. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11664. // Context lost
  11665. if (!this._doNotHandleContextLost) {
  11666. this._onContextLost = function (evt) {
  11667. evt.preventDefault();
  11668. _this._contextWasLost = true;
  11669. BABYLON.Tools.Warn("WebGL context lost.");
  11670. _this.onContextLostObservable.notifyObservers(_this);
  11671. };
  11672. this._onContextRestored = function (evt) {
  11673. // Adding a timeout to avoid race condition at browser level
  11674. setTimeout(function () {
  11675. // Rebuild gl context
  11676. _this._initGLContext();
  11677. // Rebuild effects
  11678. _this._rebuildEffects();
  11679. // Rebuild textures
  11680. _this._rebuildInternalTextures();
  11681. // Rebuild buffers
  11682. _this._rebuildBuffers();
  11683. // Cache
  11684. _this.wipeCaches(true);
  11685. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11686. _this.onContextRestoredObservable.notifyObservers(_this);
  11687. _this._contextWasLost = false;
  11688. }, 0);
  11689. };
  11690. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11691. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11692. }
  11693. }
  11694. else {
  11695. this._gl = canvasOrContext;
  11696. this._renderingCanvas = this._gl.canvas;
  11697. if (this._gl.renderbufferStorageMultisample) {
  11698. this._webGLVersion = 2.0;
  11699. }
  11700. options.stencil = this._gl.getContextAttributes().stencil;
  11701. }
  11702. // Viewport
  11703. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11704. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11705. this.resize();
  11706. this._isStencilEnable = options.stencil ? true : false;
  11707. this._initGLContext();
  11708. if (canvas) {
  11709. // Fullscreen
  11710. this._onFullscreenChange = function () {
  11711. if (document.fullscreen !== undefined) {
  11712. _this.isFullscreen = document.fullscreen;
  11713. }
  11714. else if (document.mozFullScreen !== undefined) {
  11715. _this.isFullscreen = document.mozFullScreen;
  11716. }
  11717. else if (document.webkitIsFullScreen !== undefined) {
  11718. _this.isFullscreen = document.webkitIsFullScreen;
  11719. }
  11720. else if (document.msIsFullScreen !== undefined) {
  11721. _this.isFullscreen = document.msIsFullScreen;
  11722. }
  11723. // Pointer lock
  11724. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11725. canvas.requestPointerLock = canvas.requestPointerLock ||
  11726. canvas.msRequestPointerLock ||
  11727. canvas.mozRequestPointerLock ||
  11728. canvas.webkitRequestPointerLock;
  11729. if (canvas.requestPointerLock) {
  11730. canvas.requestPointerLock();
  11731. }
  11732. }
  11733. };
  11734. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11735. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11736. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11737. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11738. // Pointer lock
  11739. this._onPointerLockChange = function () {
  11740. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11741. document.webkitPointerLockElement === canvas ||
  11742. document.msPointerLockElement === canvas ||
  11743. document.pointerLockElement === canvas);
  11744. };
  11745. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11746. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11747. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11748. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11749. this._onVRDisplayPointerRestricted = function () {
  11750. if (canvas) {
  11751. canvas.requestPointerLock();
  11752. }
  11753. };
  11754. this._onVRDisplayPointerUnrestricted = function () {
  11755. document.exitPointerLock();
  11756. };
  11757. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11758. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11759. }
  11760. // Create Audio Engine if needed.
  11761. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  11762. Engine.audioEngine = Engine.AudioEngineFactory();
  11763. }
  11764. // Prepare buffer pointers
  11765. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11766. this._currentBufferPointers[i] = new BufferPointer();
  11767. }
  11768. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11769. // Load WebVR Devices
  11770. if (options.autoEnableWebVR) {
  11771. this.initWebVR();
  11772. }
  11773. // Detect if we are running on a faulty buggy OS.
  11774. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11775. // Detect if we are running on a faulty buggy desktop OS.
  11776. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11777. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11778. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11779. }
  11780. Object.defineProperty(Engine, "LastCreatedEngine", {
  11781. /**
  11782. * Gets the latest created engine
  11783. */
  11784. get: function () {
  11785. if (Engine.Instances.length === 0) {
  11786. return null;
  11787. }
  11788. return Engine.Instances[Engine.Instances.length - 1];
  11789. },
  11790. enumerable: true,
  11791. configurable: true
  11792. });
  11793. Object.defineProperty(Engine, "LastCreatedScene", {
  11794. /**
  11795. * Gets the latest created scene
  11796. */
  11797. get: function () {
  11798. var lastCreatedEngine = Engine.LastCreatedEngine;
  11799. if (!lastCreatedEngine) {
  11800. return null;
  11801. }
  11802. if (lastCreatedEngine.scenes.length === 0) {
  11803. return null;
  11804. }
  11805. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11806. },
  11807. enumerable: true,
  11808. configurable: true
  11809. });
  11810. /**
  11811. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11812. * @param flag defines which part of the materials must be marked as dirty
  11813. * @param predicate defines a predicate used to filter which materials should be affected
  11814. */
  11815. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11816. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11817. var engine = Engine.Instances[engineIndex];
  11818. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11819. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11820. }
  11821. }
  11822. };
  11823. Object.defineProperty(Engine, "Version", {
  11824. /**
  11825. * Returns the current version of the framework
  11826. */
  11827. get: function () {
  11828. return "3.3.0-beta.5";
  11829. },
  11830. enumerable: true,
  11831. configurable: true
  11832. });
  11833. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11834. /**
  11835. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11836. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11837. */
  11838. get: function () {
  11839. return this._vrExclusivePointerMode;
  11840. },
  11841. enumerable: true,
  11842. configurable: true
  11843. });
  11844. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11845. /**
  11846. * Gets a boolean indicating that the engine supports uniform buffers
  11847. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11848. */
  11849. get: function () {
  11850. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11851. },
  11852. enumerable: true,
  11853. configurable: true
  11854. });
  11855. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11856. /**
  11857. * Gets a boolean indicating that only power of 2 textures are supported
  11858. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11859. */
  11860. get: function () {
  11861. return this._webGLVersion < 2 || this.forcePOTTextures;
  11862. },
  11863. enumerable: true,
  11864. configurable: true
  11865. });
  11866. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11867. /**
  11868. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11869. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11870. */
  11871. get: function () {
  11872. return this._doNotHandleContextLost;
  11873. },
  11874. set: function (value) {
  11875. this._doNotHandleContextLost = value;
  11876. },
  11877. enumerable: true,
  11878. configurable: true
  11879. });
  11880. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11881. /**
  11882. * Gets the performance monitor attached to this engine
  11883. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11884. */
  11885. get: function () {
  11886. return this._performanceMonitor;
  11887. },
  11888. enumerable: true,
  11889. configurable: true
  11890. });
  11891. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11892. /**
  11893. * Gets the list of texture formats supported
  11894. */
  11895. get: function () {
  11896. return this._texturesSupported;
  11897. },
  11898. enumerable: true,
  11899. configurable: true
  11900. });
  11901. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11902. /**
  11903. * Gets the list of texture formats in use
  11904. */
  11905. get: function () {
  11906. return this._textureFormatInUse;
  11907. },
  11908. enumerable: true,
  11909. configurable: true
  11910. });
  11911. Object.defineProperty(Engine.prototype, "currentViewport", {
  11912. /**
  11913. * Gets the current viewport
  11914. */
  11915. get: function () {
  11916. return this._cachedViewport;
  11917. },
  11918. enumerable: true,
  11919. configurable: true
  11920. });
  11921. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11922. /**
  11923. * Gets the default empty texture
  11924. */
  11925. get: function () {
  11926. if (!this._emptyTexture) {
  11927. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11928. }
  11929. return this._emptyTexture;
  11930. },
  11931. enumerable: true,
  11932. configurable: true
  11933. });
  11934. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11935. /**
  11936. * Gets the default empty 3D texture
  11937. */
  11938. get: function () {
  11939. if (!this._emptyTexture3D) {
  11940. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11941. }
  11942. return this._emptyTexture3D;
  11943. },
  11944. enumerable: true,
  11945. configurable: true
  11946. });
  11947. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11948. /**
  11949. * Gets the default empty cube texture
  11950. */
  11951. get: function () {
  11952. if (!this._emptyCubeTexture) {
  11953. var faceData = new Uint8Array(4);
  11954. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11955. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11956. }
  11957. return this._emptyCubeTexture;
  11958. },
  11959. enumerable: true,
  11960. configurable: true
  11961. });
  11962. Engine.prototype._rebuildInternalTextures = function () {
  11963. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11964. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11965. var internalTexture = currentState_1[_i];
  11966. internalTexture._rebuild();
  11967. }
  11968. };
  11969. Engine.prototype._rebuildEffects = function () {
  11970. for (var key in this._compiledEffects) {
  11971. var effect = this._compiledEffects[key];
  11972. effect._prepareEffect();
  11973. }
  11974. BABYLON.Effect.ResetCache();
  11975. };
  11976. Engine.prototype._rebuildBuffers = function () {
  11977. // Index / Vertex
  11978. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11979. var scene = _a[_i];
  11980. scene.resetCachedMaterial();
  11981. scene._rebuildGeometries();
  11982. scene._rebuildTextures();
  11983. }
  11984. // Uniforms
  11985. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11986. var uniformBuffer = _c[_b];
  11987. uniformBuffer._rebuild();
  11988. }
  11989. };
  11990. Engine.prototype._initGLContext = function () {
  11991. // Caps
  11992. this._caps = new EngineCapabilities();
  11993. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11994. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11995. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11996. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11997. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11998. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11999. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12000. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12001. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12002. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12003. // Infos
  12004. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12005. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12006. if (rendererInfo != null) {
  12007. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12008. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12009. }
  12010. if (!this._glVendor) {
  12011. this._glVendor = "Unknown vendor";
  12012. }
  12013. if (!this._glRenderer) {
  12014. this._glRenderer = "Unknown renderer";
  12015. }
  12016. // Constants
  12017. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12018. if (this._gl.RGBA16F !== 0x881A) {
  12019. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12020. }
  12021. if (this._gl.RGBA32F !== 0x8814) {
  12022. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12023. }
  12024. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12025. this._gl.DEPTH24_STENCIL8 = 35056;
  12026. }
  12027. // Extensions
  12028. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12029. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12030. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12031. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12032. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12033. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12034. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12035. 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');
  12036. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12037. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12038. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12039. this._caps.highPrecisionShaderSupported = true;
  12040. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12041. if (this._caps.timerQuery) {
  12042. if (this._webGLVersion === 1) {
  12043. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12044. }
  12045. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12046. }
  12047. // Checks if some of the format renders first to allow the use of webgl inspector.
  12048. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12049. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12050. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12051. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12052. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12053. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12054. if (this._webGLVersion > 1) {
  12055. this._gl.HALF_FLOAT_OES = 0x140B;
  12056. }
  12057. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12058. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12059. // Draw buffers
  12060. if (this._webGLVersion > 1) {
  12061. this._caps.drawBuffersExtension = true;
  12062. }
  12063. else {
  12064. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12065. if (drawBuffersExtension !== null) {
  12066. this._caps.drawBuffersExtension = true;
  12067. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12068. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12069. for (var i = 0; i < 16; i++) {
  12070. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12071. }
  12072. }
  12073. else {
  12074. this._caps.drawBuffersExtension = false;
  12075. }
  12076. }
  12077. // Depth Texture
  12078. if (this._webGLVersion > 1) {
  12079. this._caps.depthTextureExtension = true;
  12080. }
  12081. else {
  12082. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12083. if (depthTextureExtension != null) {
  12084. this._caps.depthTextureExtension = true;
  12085. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12086. }
  12087. }
  12088. // Vertex array object
  12089. if (this._webGLVersion > 1) {
  12090. this._caps.vertexArrayObject = true;
  12091. }
  12092. else {
  12093. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12094. if (vertexArrayObjectExtension != null) {
  12095. this._caps.vertexArrayObject = true;
  12096. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12097. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12098. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12099. }
  12100. else {
  12101. this._caps.vertexArrayObject = false;
  12102. }
  12103. }
  12104. // Instances count
  12105. if (this._webGLVersion > 1) {
  12106. this._caps.instancedArrays = true;
  12107. }
  12108. else {
  12109. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12110. if (instanceExtension != null) {
  12111. this._caps.instancedArrays = true;
  12112. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12113. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12114. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12115. }
  12116. else {
  12117. this._caps.instancedArrays = false;
  12118. }
  12119. }
  12120. // Intelligently add supported compressed formats in order to check for.
  12121. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12122. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12123. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12124. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12125. if (this._caps.astc)
  12126. this.texturesSupported.push('-astc.ktx');
  12127. if (this._caps.s3tc)
  12128. this.texturesSupported.push('-dxt.ktx');
  12129. if (this._caps.pvrtc)
  12130. this.texturesSupported.push('-pvrtc.ktx');
  12131. if (this._caps.etc2)
  12132. this.texturesSupported.push('-etc2.ktx');
  12133. if (this._caps.etc1)
  12134. this.texturesSupported.push('-etc1.ktx');
  12135. if (this._gl.getShaderPrecisionFormat) {
  12136. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12137. if (highp) {
  12138. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12139. }
  12140. }
  12141. // Depth buffer
  12142. this.setDepthBuffer(true);
  12143. this.setDepthFunctionToLessOrEqual();
  12144. this.setDepthWrite(true);
  12145. // Texture maps
  12146. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12147. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12148. this._nextFreeTextureSlots.push(slot);
  12149. }
  12150. };
  12151. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12152. /**
  12153. * Gets version of the current webGL context
  12154. */
  12155. get: function () {
  12156. return this._webGLVersion;
  12157. },
  12158. enumerable: true,
  12159. configurable: true
  12160. });
  12161. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12162. /**
  12163. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12164. */
  12165. get: function () {
  12166. return this._isStencilEnable;
  12167. },
  12168. enumerable: true,
  12169. configurable: true
  12170. });
  12171. Engine.prototype._prepareWorkingCanvas = function () {
  12172. if (this._workingCanvas) {
  12173. return;
  12174. }
  12175. this._workingCanvas = document.createElement("canvas");
  12176. var context = this._workingCanvas.getContext("2d");
  12177. if (context) {
  12178. this._workingContext = context;
  12179. }
  12180. };
  12181. /**
  12182. * Reset the texture cache to empty state
  12183. */
  12184. Engine.prototype.resetTextureCache = function () {
  12185. for (var key in this._boundTexturesCache) {
  12186. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12187. continue;
  12188. }
  12189. var boundTexture = this._boundTexturesCache[key];
  12190. if (boundTexture) {
  12191. this._removeDesignatedSlot(boundTexture);
  12192. }
  12193. this._boundTexturesCache[key] = null;
  12194. }
  12195. if (!this.disableTextureBindingOptimization) {
  12196. this._nextFreeTextureSlots = [];
  12197. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12198. this._nextFreeTextureSlots.push(slot);
  12199. }
  12200. }
  12201. this._currentTextureChannel = -1;
  12202. };
  12203. /**
  12204. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12205. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12206. * @returns true if engine is in deterministic lock step mode
  12207. */
  12208. Engine.prototype.isDeterministicLockStep = function () {
  12209. return this._deterministicLockstep;
  12210. };
  12211. /**
  12212. * Gets the max steps when engine is running in deterministic lock step
  12213. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12214. * @returns the max steps
  12215. */
  12216. Engine.prototype.getLockstepMaxSteps = function () {
  12217. return this._lockstepMaxSteps;
  12218. };
  12219. /**
  12220. * Gets an object containing information about the current webGL context
  12221. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12222. */
  12223. Engine.prototype.getGlInfo = function () {
  12224. return {
  12225. vendor: this._glVendor,
  12226. renderer: this._glRenderer,
  12227. version: this._glVersion
  12228. };
  12229. };
  12230. /**
  12231. * Gets current aspect ratio
  12232. * @param camera defines the camera to use to get the aspect ratio
  12233. * @param useScreen defines if screen size must be used (or the current render target if any)
  12234. * @returns a number defining the aspect ratio
  12235. */
  12236. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12237. if (useScreen === void 0) { useScreen = false; }
  12238. var viewport = camera.viewport;
  12239. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12240. };
  12241. /**
  12242. * Gets current screen aspect ratio
  12243. * @returns a number defining the aspect ratio
  12244. */
  12245. Engine.prototype.getScreenAspectRatio = function () {
  12246. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12247. };
  12248. /**
  12249. * Gets the current render width
  12250. * @param useScreen defines if screen size must be used (or the current render target if any)
  12251. * @returns a number defining the current render width
  12252. */
  12253. Engine.prototype.getRenderWidth = function (useScreen) {
  12254. if (useScreen === void 0) { useScreen = false; }
  12255. if (!useScreen && this._currentRenderTarget) {
  12256. return this._currentRenderTarget.width;
  12257. }
  12258. return this._gl.drawingBufferWidth;
  12259. };
  12260. /**
  12261. * Gets the current render height
  12262. * @param useScreen defines if screen size must be used (or the current render target if any)
  12263. * @returns a number defining the current render height
  12264. */
  12265. Engine.prototype.getRenderHeight = function (useScreen) {
  12266. if (useScreen === void 0) { useScreen = false; }
  12267. if (!useScreen && this._currentRenderTarget) {
  12268. return this._currentRenderTarget.height;
  12269. }
  12270. return this._gl.drawingBufferHeight;
  12271. };
  12272. /**
  12273. * Gets the HTML canvas attached with the current webGL context
  12274. * @returns a HTML canvas
  12275. */
  12276. Engine.prototype.getRenderingCanvas = function () {
  12277. return this._renderingCanvas;
  12278. };
  12279. /**
  12280. * Gets the client rect of the HTML canvas attached with the current webGL context
  12281. * @returns a client rectanglee
  12282. */
  12283. Engine.prototype.getRenderingCanvasClientRect = function () {
  12284. if (!this._renderingCanvas) {
  12285. return null;
  12286. }
  12287. return this._renderingCanvas.getBoundingClientRect();
  12288. };
  12289. /**
  12290. * Defines the hardware scaling level.
  12291. * By default the hardware scaling level is computed from the window device ratio.
  12292. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12293. * @param level defines the level to use
  12294. */
  12295. Engine.prototype.setHardwareScalingLevel = function (level) {
  12296. this._hardwareScalingLevel = level;
  12297. this.resize();
  12298. };
  12299. /**
  12300. * Gets the current hardware scaling level.
  12301. * By default the hardware scaling level is computed from the window device ratio.
  12302. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12303. * @returns a number indicating the current hardware scaling level
  12304. */
  12305. Engine.prototype.getHardwareScalingLevel = function () {
  12306. return this._hardwareScalingLevel;
  12307. };
  12308. /**
  12309. * Gets the list of loaded textures
  12310. * @returns an array containing all loaded textures
  12311. */
  12312. Engine.prototype.getLoadedTexturesCache = function () {
  12313. return this._internalTexturesCache;
  12314. };
  12315. /**
  12316. * Gets the object containing all engine capabilities
  12317. * @returns the EngineCapabilities object
  12318. */
  12319. Engine.prototype.getCaps = function () {
  12320. return this._caps;
  12321. };
  12322. Object.defineProperty(Engine.prototype, "drawCalls", {
  12323. /** @hidden */
  12324. get: function () {
  12325. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12326. return 0;
  12327. },
  12328. enumerable: true,
  12329. configurable: true
  12330. });
  12331. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12332. /** @hidden */
  12333. get: function () {
  12334. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12335. return null;
  12336. },
  12337. enumerable: true,
  12338. configurable: true
  12339. });
  12340. /**
  12341. * Gets the current depth function
  12342. * @returns a number defining the depth function
  12343. */
  12344. Engine.prototype.getDepthFunction = function () {
  12345. return this._depthCullingState.depthFunc;
  12346. };
  12347. /**
  12348. * Sets the current depth function
  12349. * @param depthFunc defines the function to use
  12350. */
  12351. Engine.prototype.setDepthFunction = function (depthFunc) {
  12352. this._depthCullingState.depthFunc = depthFunc;
  12353. };
  12354. /**
  12355. * Sets the current depth function to GREATER
  12356. */
  12357. Engine.prototype.setDepthFunctionToGreater = function () {
  12358. this._depthCullingState.depthFunc = this._gl.GREATER;
  12359. };
  12360. /**
  12361. * Sets the current depth function to GEQUAL
  12362. */
  12363. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12364. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12365. };
  12366. /**
  12367. * Sets the current depth function to LESS
  12368. */
  12369. Engine.prototype.setDepthFunctionToLess = function () {
  12370. this._depthCullingState.depthFunc = this._gl.LESS;
  12371. };
  12372. /**
  12373. * Sets the current depth function to LEQUAL
  12374. */
  12375. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12376. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12377. };
  12378. /**
  12379. * Gets a boolean indicating if stencil buffer is enabled
  12380. * @returns the current stencil buffer state
  12381. */
  12382. Engine.prototype.getStencilBuffer = function () {
  12383. return this._stencilState.stencilTest;
  12384. };
  12385. /**
  12386. * Enable or disable the stencil buffer
  12387. * @param enable defines if the stencil buffer must be enabled or disabled
  12388. */
  12389. Engine.prototype.setStencilBuffer = function (enable) {
  12390. this._stencilState.stencilTest = enable;
  12391. };
  12392. /**
  12393. * Gets the current stencil mask
  12394. * @returns a number defining the new stencil mask to use
  12395. */
  12396. Engine.prototype.getStencilMask = function () {
  12397. return this._stencilState.stencilMask;
  12398. };
  12399. /**
  12400. * Sets the current stencil mask
  12401. * @param mask defines the new stencil mask to use
  12402. */
  12403. Engine.prototype.setStencilMask = function (mask) {
  12404. this._stencilState.stencilMask = mask;
  12405. };
  12406. /**
  12407. * Gets the current stencil function
  12408. * @returns a number defining the stencil function to use
  12409. */
  12410. Engine.prototype.getStencilFunction = function () {
  12411. return this._stencilState.stencilFunc;
  12412. };
  12413. /**
  12414. * Gets the current stencil reference value
  12415. * @returns a number defining the stencil reference value to use
  12416. */
  12417. Engine.prototype.getStencilFunctionReference = function () {
  12418. return this._stencilState.stencilFuncRef;
  12419. };
  12420. /**
  12421. * Gets the current stencil mask
  12422. * @returns a number defining the stencil mask to use
  12423. */
  12424. Engine.prototype.getStencilFunctionMask = function () {
  12425. return this._stencilState.stencilFuncMask;
  12426. };
  12427. /**
  12428. * Sets the current stencil function
  12429. * @param stencilFunc defines the new stencil function to use
  12430. */
  12431. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12432. this._stencilState.stencilFunc = stencilFunc;
  12433. };
  12434. /**
  12435. * Sets the current stencil reference
  12436. * @param reference defines the new stencil reference to use
  12437. */
  12438. Engine.prototype.setStencilFunctionReference = function (reference) {
  12439. this._stencilState.stencilFuncRef = reference;
  12440. };
  12441. /**
  12442. * Sets the current stencil mask
  12443. * @param mask defines the new stencil mask to use
  12444. */
  12445. Engine.prototype.setStencilFunctionMask = function (mask) {
  12446. this._stencilState.stencilFuncMask = mask;
  12447. };
  12448. /**
  12449. * Gets the current stencil operation when stencil fails
  12450. * @returns a number defining stencil operation to use when stencil fails
  12451. */
  12452. Engine.prototype.getStencilOperationFail = function () {
  12453. return this._stencilState.stencilOpStencilFail;
  12454. };
  12455. /**
  12456. * Gets the current stencil operation when depth fails
  12457. * @returns a number defining stencil operation to use when depth fails
  12458. */
  12459. Engine.prototype.getStencilOperationDepthFail = function () {
  12460. return this._stencilState.stencilOpDepthFail;
  12461. };
  12462. /**
  12463. * Gets the current stencil operation when stencil passes
  12464. * @returns a number defining stencil operation to use when stencil passes
  12465. */
  12466. Engine.prototype.getStencilOperationPass = function () {
  12467. return this._stencilState.stencilOpStencilDepthPass;
  12468. };
  12469. /**
  12470. * Sets the stencil operation to use when stencil fails
  12471. * @param operation defines the stencil operation to use when stencil fails
  12472. */
  12473. Engine.prototype.setStencilOperationFail = function (operation) {
  12474. this._stencilState.stencilOpStencilFail = operation;
  12475. };
  12476. /**
  12477. * Sets the stencil operation to use when depth fails
  12478. * @param operation defines the stencil operation to use when depth fails
  12479. */
  12480. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12481. this._stencilState.stencilOpDepthFail = operation;
  12482. };
  12483. /**
  12484. * Sets the stencil operation to use when stencil passes
  12485. * @param operation defines the stencil operation to use when stencil passes
  12486. */
  12487. Engine.prototype.setStencilOperationPass = function (operation) {
  12488. this._stencilState.stencilOpStencilDepthPass = operation;
  12489. };
  12490. /**
  12491. * Sets a boolean indicating if the dithering state is enabled or disabled
  12492. * @param value defines the dithering state
  12493. */
  12494. Engine.prototype.setDitheringState = function (value) {
  12495. if (value) {
  12496. this._gl.enable(this._gl.DITHER);
  12497. }
  12498. else {
  12499. this._gl.disable(this._gl.DITHER);
  12500. }
  12501. };
  12502. /**
  12503. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12504. * @param value defines the rasterizer state
  12505. */
  12506. Engine.prototype.setRasterizerState = function (value) {
  12507. if (value) {
  12508. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12509. }
  12510. else {
  12511. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12512. }
  12513. };
  12514. /**
  12515. * stop executing a render loop function and remove it from the execution array
  12516. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12517. */
  12518. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12519. if (!renderFunction) {
  12520. this._activeRenderLoops = [];
  12521. return;
  12522. }
  12523. var index = this._activeRenderLoops.indexOf(renderFunction);
  12524. if (index >= 0) {
  12525. this._activeRenderLoops.splice(index, 1);
  12526. }
  12527. };
  12528. /** @hidden */
  12529. Engine.prototype._renderLoop = function () {
  12530. if (!this._contextWasLost) {
  12531. var shouldRender = true;
  12532. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12533. shouldRender = false;
  12534. }
  12535. if (shouldRender) {
  12536. // Start new frame
  12537. this.beginFrame();
  12538. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12539. var renderFunction = this._activeRenderLoops[index];
  12540. renderFunction();
  12541. }
  12542. // Present
  12543. this.endFrame();
  12544. }
  12545. }
  12546. if (this._activeRenderLoops.length > 0) {
  12547. // Register new frame
  12548. var requester = null;
  12549. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12550. requester = this._vrDisplay;
  12551. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12552. }
  12553. else {
  12554. this._renderingQueueLaunched = false;
  12555. }
  12556. };
  12557. /**
  12558. * Register and execute a render loop. The engine can have more than one render function
  12559. * @param renderFunction defines the function to continuously execute
  12560. */
  12561. Engine.prototype.runRenderLoop = function (renderFunction) {
  12562. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12563. return;
  12564. }
  12565. this._activeRenderLoops.push(renderFunction);
  12566. if (!this._renderingQueueLaunched) {
  12567. this._renderingQueueLaunched = true;
  12568. this._bindedRenderFunction = this._renderLoop.bind(this);
  12569. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12570. }
  12571. };
  12572. /**
  12573. * Toggle full screen mode
  12574. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12575. * @param options defines an option object to be sent to the requestFullscreen function
  12576. */
  12577. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12578. if (this.isFullscreen) {
  12579. BABYLON.Tools.ExitFullscreen();
  12580. }
  12581. else {
  12582. this._pointerLockRequested = requestPointerLock;
  12583. if (this._renderingCanvas) {
  12584. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12585. }
  12586. }
  12587. };
  12588. /**
  12589. * Clear the current render buffer or the current render target (if any is set up)
  12590. * @param color defines the color to use
  12591. * @param backBuffer defines if the back buffer must be cleared
  12592. * @param depth defines if the depth buffer must be cleared
  12593. * @param stencil defines if the stencil buffer must be cleared
  12594. */
  12595. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12596. if (stencil === void 0) { stencil = false; }
  12597. this.applyStates();
  12598. var mode = 0;
  12599. if (backBuffer && color) {
  12600. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12601. mode |= this._gl.COLOR_BUFFER_BIT;
  12602. }
  12603. if (depth) {
  12604. this._gl.clearDepth(1.0);
  12605. mode |= this._gl.DEPTH_BUFFER_BIT;
  12606. }
  12607. if (stencil) {
  12608. this._gl.clearStencil(0);
  12609. mode |= this._gl.STENCIL_BUFFER_BIT;
  12610. }
  12611. this._gl.clear(mode);
  12612. };
  12613. /**
  12614. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12615. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12616. * @param y defines the y-coordinate of the corner of the clear rectangle
  12617. * @param width defines the width of the clear rectangle
  12618. * @param height defines the height of the clear rectangle
  12619. * @param clearColor defines the clear color
  12620. */
  12621. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12622. var gl = this._gl;
  12623. // Save state
  12624. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12625. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12626. // Change state
  12627. gl.enable(gl.SCISSOR_TEST);
  12628. gl.scissor(x, y, width, height);
  12629. // Clear
  12630. this.clear(clearColor, true, true, true);
  12631. // Restore state
  12632. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12633. if (curScissor === true) {
  12634. gl.enable(gl.SCISSOR_TEST);
  12635. }
  12636. else {
  12637. gl.disable(gl.SCISSOR_TEST);
  12638. }
  12639. };
  12640. /** @hidden */
  12641. Engine.prototype._viewport = function (x, y, width, height) {
  12642. if (x !== this._viewportCached.x ||
  12643. y !== this._viewportCached.y ||
  12644. width !== this._viewportCached.z ||
  12645. height !== this._viewportCached.w) {
  12646. this._viewportCached.x = x;
  12647. this._viewportCached.y = y;
  12648. this._viewportCached.z = width;
  12649. this._viewportCached.w = height;
  12650. this._gl.viewport(x, y, width, height);
  12651. }
  12652. };
  12653. /**
  12654. * Set the WebGL's viewport
  12655. * @param viewport defines the viewport element to be used
  12656. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12657. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12658. */
  12659. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12660. var width = requiredWidth || this.getRenderWidth();
  12661. var height = requiredHeight || this.getRenderHeight();
  12662. var x = viewport.x || 0;
  12663. var y = viewport.y || 0;
  12664. this._cachedViewport = viewport;
  12665. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12666. };
  12667. /**
  12668. * Directly set the WebGL Viewport
  12669. * @param x defines the x coordinate of the viewport (in screen space)
  12670. * @param y defines the y coordinate of the viewport (in screen space)
  12671. * @param width defines the width of the viewport (in screen space)
  12672. * @param height defines the height of the viewport (in screen space)
  12673. * @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
  12674. */
  12675. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12676. var currentViewport = this._cachedViewport;
  12677. this._cachedViewport = null;
  12678. this._viewport(x, y, width, height);
  12679. return currentViewport;
  12680. };
  12681. /**
  12682. * Begin a new frame
  12683. */
  12684. Engine.prototype.beginFrame = function () {
  12685. this.onBeginFrameObservable.notifyObservers(this);
  12686. this._measureFps();
  12687. };
  12688. /**
  12689. * Enf the current frame
  12690. */
  12691. Engine.prototype.endFrame = function () {
  12692. // Force a flush in case we are using a bad OS.
  12693. if (this._badOS) {
  12694. this.flushFramebuffer();
  12695. }
  12696. // Submit frame to the vr device, if enabled
  12697. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12698. // TODO: We should only submit the frame if we read frameData successfully.
  12699. this._vrDisplay.submitFrame();
  12700. }
  12701. this.onEndFrameObservable.notifyObservers(this);
  12702. };
  12703. /**
  12704. * Resize the view according to the canvas' size
  12705. */
  12706. Engine.prototype.resize = function () {
  12707. // We're not resizing the size of the canvas while in VR mode & presenting
  12708. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12709. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12710. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12711. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12712. }
  12713. };
  12714. /**
  12715. * Force a specific size of the canvas
  12716. * @param width defines the new canvas' width
  12717. * @param height defines the new canvas' height
  12718. */
  12719. Engine.prototype.setSize = function (width, height) {
  12720. if (!this._renderingCanvas) {
  12721. return;
  12722. }
  12723. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12724. return;
  12725. }
  12726. this._renderingCanvas.width = width;
  12727. this._renderingCanvas.height = height;
  12728. for (var index = 0; index < this.scenes.length; index++) {
  12729. var scene = this.scenes[index];
  12730. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12731. var cam = scene.cameras[camIndex];
  12732. cam._currentRenderId = 0;
  12733. }
  12734. }
  12735. if (this.onResizeObservable.hasObservers) {
  12736. this.onResizeObservable.notifyObservers(this);
  12737. }
  12738. };
  12739. // WebVR functions
  12740. /**
  12741. * Gets a boolean indicating if a webVR device was detected
  12742. * @returns true if a webVR device was detected
  12743. */
  12744. Engine.prototype.isVRDevicePresent = function () {
  12745. return !!this._vrDisplay;
  12746. };
  12747. /**
  12748. * Gets the current webVR device
  12749. * @returns the current webVR device (or null)
  12750. */
  12751. Engine.prototype.getVRDevice = function () {
  12752. return this._vrDisplay;
  12753. };
  12754. /**
  12755. * Initializes a webVR display and starts listening to display change events
  12756. * The onVRDisplayChangedObservable will be notified upon these changes
  12757. * @returns The onVRDisplayChangedObservable
  12758. */
  12759. Engine.prototype.initWebVR = function () {
  12760. this.initWebVRAsync();
  12761. return this.onVRDisplayChangedObservable;
  12762. };
  12763. /**
  12764. * Initializes a webVR display and starts listening to display change events
  12765. * The onVRDisplayChangedObservable will be notified upon these changes
  12766. * @returns A promise containing a VRDisplay and if vr is supported
  12767. */
  12768. Engine.prototype.initWebVRAsync = function () {
  12769. var _this = this;
  12770. var notifyObservers = function () {
  12771. var eventArgs = {
  12772. vrDisplay: _this._vrDisplay,
  12773. vrSupported: _this._vrSupported
  12774. };
  12775. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12776. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12777. };
  12778. if (!this._onVrDisplayConnect) {
  12779. this._onVrDisplayConnect = function (event) {
  12780. _this._vrDisplay = event.display;
  12781. notifyObservers();
  12782. };
  12783. this._onVrDisplayDisconnect = function () {
  12784. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12785. _this._vrDisplay = undefined;
  12786. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12787. notifyObservers();
  12788. };
  12789. this._onVrDisplayPresentChange = function () {
  12790. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12791. };
  12792. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12793. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12794. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12795. }
  12796. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12797. this._webVRInitPromise.then(notifyObservers);
  12798. return this._webVRInitPromise;
  12799. };
  12800. /**
  12801. * Call this function to switch to webVR mode
  12802. * Will do nothing if webVR is not supported or if there is no webVR device
  12803. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12804. */
  12805. Engine.prototype.enableVR = function () {
  12806. var _this = this;
  12807. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12808. var onResolved = function () {
  12809. _this.onVRRequestPresentComplete.notifyObservers(true);
  12810. _this._onVRFullScreenTriggered();
  12811. };
  12812. var onRejected = function () {
  12813. _this.onVRRequestPresentComplete.notifyObservers(false);
  12814. };
  12815. this.onVRRequestPresentStart.notifyObservers(this);
  12816. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12817. }
  12818. };
  12819. /**
  12820. * Call this function to leave webVR mode
  12821. * Will do nothing if webVR is not supported or if there is no webVR device
  12822. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12823. */
  12824. Engine.prototype.disableVR = function () {
  12825. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12826. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12827. }
  12828. };
  12829. Engine.prototype._getVRDisplaysAsync = function () {
  12830. var _this = this;
  12831. return new Promise(function (res, rej) {
  12832. if (navigator.getVRDisplays) {
  12833. navigator.getVRDisplays().then(function (devices) {
  12834. _this._vrSupported = true;
  12835. // note that devices may actually be an empty array. This is fine;
  12836. // we expect this._vrDisplay to be undefined in this case.
  12837. _this._vrDisplay = devices[0];
  12838. res({
  12839. vrDisplay: _this._vrDisplay,
  12840. vrSupported: _this._vrSupported
  12841. });
  12842. });
  12843. }
  12844. else {
  12845. _this._vrDisplay = undefined;
  12846. _this._vrSupported = false;
  12847. res({
  12848. vrDisplay: _this._vrDisplay,
  12849. vrSupported: _this._vrSupported
  12850. });
  12851. }
  12852. });
  12853. };
  12854. /**
  12855. * Binds the frame buffer to the specified texture.
  12856. * @param texture The texture to render to or null for the default canvas
  12857. * @param faceIndex The face of the texture to render to in case of cube texture
  12858. * @param requiredWidth The width of the target to render to
  12859. * @param requiredHeight The height of the target to render to
  12860. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12861. * @param depthStencilTexture The depth stencil texture to use to render
  12862. * @param lodLevel defines le lod level to bind to the frame buffer
  12863. */
  12864. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12865. if (lodLevel === void 0) { lodLevel = 0; }
  12866. if (this._currentRenderTarget) {
  12867. this.unBindFramebuffer(this._currentRenderTarget);
  12868. }
  12869. this._currentRenderTarget = texture;
  12870. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12871. var gl = this._gl;
  12872. if (texture.isCube) {
  12873. if (faceIndex === undefined) {
  12874. faceIndex = 0;
  12875. }
  12876. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12877. if (depthStencilTexture) {
  12878. if (depthStencilTexture._generateStencilBuffer) {
  12879. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12880. }
  12881. else {
  12882. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12883. }
  12884. }
  12885. }
  12886. if (this._cachedViewport && !forceFullscreenViewport) {
  12887. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12888. }
  12889. else {
  12890. if (!requiredWidth) {
  12891. requiredWidth = texture.width;
  12892. if (lodLevel) {
  12893. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12894. }
  12895. }
  12896. if (!requiredHeight) {
  12897. requiredHeight = texture.height;
  12898. if (lodLevel) {
  12899. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12900. }
  12901. }
  12902. this._viewport(0, 0, requiredWidth, requiredHeight);
  12903. }
  12904. this.wipeCaches();
  12905. };
  12906. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12907. if (this._currentFramebuffer !== framebuffer) {
  12908. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12909. this._currentFramebuffer = framebuffer;
  12910. }
  12911. };
  12912. /**
  12913. * Unbind the current render target texture from the webGL context
  12914. * @param texture defines the render target texture to unbind
  12915. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12916. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12917. */
  12918. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12919. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12920. this._currentRenderTarget = null;
  12921. // If MSAA, we need to bitblt back to main texture
  12922. var gl = this._gl;
  12923. if (texture._MSAAFramebuffer) {
  12924. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12925. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12926. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12927. }
  12928. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12929. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12930. gl.generateMipmap(gl.TEXTURE_2D);
  12931. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12932. }
  12933. if (onBeforeUnbind) {
  12934. if (texture._MSAAFramebuffer) {
  12935. // Bind the correct framebuffer
  12936. this.bindUnboundFramebuffer(texture._framebuffer);
  12937. }
  12938. onBeforeUnbind();
  12939. }
  12940. this.bindUnboundFramebuffer(null);
  12941. };
  12942. /**
  12943. * Unbind a list of render target textures from the webGL context
  12944. * This is used only when drawBuffer extension or webGL2 are active
  12945. * @param textures defines the render target textures to unbind
  12946. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12947. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12948. */
  12949. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12950. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12951. this._currentRenderTarget = null;
  12952. // If MSAA, we need to bitblt back to main texture
  12953. var gl = this._gl;
  12954. if (textures[0]._MSAAFramebuffer) {
  12955. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12956. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12957. var attachments = textures[0]._attachments;
  12958. if (!attachments) {
  12959. attachments = new Array(textures.length);
  12960. textures[0]._attachments = attachments;
  12961. }
  12962. for (var i = 0; i < textures.length; i++) {
  12963. var texture = textures[i];
  12964. for (var j = 0; j < attachments.length; j++) {
  12965. attachments[j] = gl.NONE;
  12966. }
  12967. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12968. gl.readBuffer(attachments[i]);
  12969. gl.drawBuffers(attachments);
  12970. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12971. }
  12972. for (var i = 0; i < attachments.length; i++) {
  12973. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12974. }
  12975. gl.drawBuffers(attachments);
  12976. }
  12977. for (var i = 0; i < textures.length; i++) {
  12978. var texture = textures[i];
  12979. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12980. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12981. gl.generateMipmap(gl.TEXTURE_2D);
  12982. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12983. }
  12984. }
  12985. if (onBeforeUnbind) {
  12986. if (textures[0]._MSAAFramebuffer) {
  12987. // Bind the correct framebuffer
  12988. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12989. }
  12990. onBeforeUnbind();
  12991. }
  12992. this.bindUnboundFramebuffer(null);
  12993. };
  12994. /**
  12995. * Force the mipmap generation for the given render target texture
  12996. * @param texture defines the render target texture to use
  12997. */
  12998. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12999. if (texture.generateMipMaps) {
  13000. var gl = this._gl;
  13001. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13002. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13003. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13004. }
  13005. };
  13006. /**
  13007. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13008. */
  13009. Engine.prototype.flushFramebuffer = function () {
  13010. this._gl.flush();
  13011. };
  13012. /**
  13013. * Unbind the current render target and bind the default framebuffer
  13014. */
  13015. Engine.prototype.restoreDefaultFramebuffer = function () {
  13016. if (this._currentRenderTarget) {
  13017. this.unBindFramebuffer(this._currentRenderTarget);
  13018. }
  13019. else {
  13020. this.bindUnboundFramebuffer(null);
  13021. }
  13022. if (this._cachedViewport) {
  13023. this.setViewport(this._cachedViewport);
  13024. }
  13025. this.wipeCaches();
  13026. };
  13027. // UBOs
  13028. /**
  13029. * Create an uniform buffer
  13030. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13031. * @param elements defines the content of the uniform buffer
  13032. * @returns the webGL uniform buffer
  13033. */
  13034. Engine.prototype.createUniformBuffer = function (elements) {
  13035. var ubo = this._gl.createBuffer();
  13036. if (!ubo) {
  13037. throw new Error("Unable to create uniform buffer");
  13038. }
  13039. this.bindUniformBuffer(ubo);
  13040. if (elements instanceof Float32Array) {
  13041. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13042. }
  13043. else {
  13044. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13045. }
  13046. this.bindUniformBuffer(null);
  13047. ubo.references = 1;
  13048. return ubo;
  13049. };
  13050. /**
  13051. * Create a dynamic uniform buffer
  13052. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13053. * @param elements defines the content of the uniform buffer
  13054. * @returns the webGL uniform buffer
  13055. */
  13056. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13057. var ubo = this._gl.createBuffer();
  13058. if (!ubo) {
  13059. throw new Error("Unable to create dynamic uniform buffer");
  13060. }
  13061. this.bindUniformBuffer(ubo);
  13062. if (elements instanceof Float32Array) {
  13063. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13064. }
  13065. else {
  13066. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13067. }
  13068. this.bindUniformBuffer(null);
  13069. ubo.references = 1;
  13070. return ubo;
  13071. };
  13072. /**
  13073. * Update an existing uniform buffer
  13074. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13075. * @param uniformBuffer defines the target uniform buffer
  13076. * @param elements defines the content to update
  13077. * @param offset defines the offset in the uniform buffer where update should start
  13078. * @param count defines the size of the data to update
  13079. */
  13080. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13081. this.bindUniformBuffer(uniformBuffer);
  13082. if (offset === undefined) {
  13083. offset = 0;
  13084. }
  13085. if (count === undefined) {
  13086. if (elements instanceof Float32Array) {
  13087. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13088. }
  13089. else {
  13090. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13091. }
  13092. }
  13093. else {
  13094. if (elements instanceof Float32Array) {
  13095. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13096. }
  13097. else {
  13098. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13099. }
  13100. }
  13101. this.bindUniformBuffer(null);
  13102. };
  13103. // VBOs
  13104. Engine.prototype._resetVertexBufferBinding = function () {
  13105. this.bindArrayBuffer(null);
  13106. this._cachedVertexBuffers = null;
  13107. };
  13108. /**
  13109. * Creates a vertex buffer
  13110. * @param data the data for the vertex buffer
  13111. * @returns the new WebGL static buffer
  13112. */
  13113. Engine.prototype.createVertexBuffer = function (data) {
  13114. var vbo = this._gl.createBuffer();
  13115. if (!vbo) {
  13116. throw new Error("Unable to create vertex buffer");
  13117. }
  13118. this.bindArrayBuffer(vbo);
  13119. if (data instanceof Array) {
  13120. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13121. }
  13122. else {
  13123. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13124. }
  13125. this._resetVertexBufferBinding();
  13126. vbo.references = 1;
  13127. return vbo;
  13128. };
  13129. /**
  13130. * Creates a dynamic vertex buffer
  13131. * @param data the data for the dynamic vertex buffer
  13132. * @returns the new WebGL dynamic buffer
  13133. */
  13134. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13135. var vbo = this._gl.createBuffer();
  13136. if (!vbo) {
  13137. throw new Error("Unable to create dynamic vertex buffer");
  13138. }
  13139. this.bindArrayBuffer(vbo);
  13140. if (data instanceof Array) {
  13141. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13142. }
  13143. else {
  13144. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13145. }
  13146. this._resetVertexBufferBinding();
  13147. vbo.references = 1;
  13148. return vbo;
  13149. };
  13150. /**
  13151. * Update a dynamic index buffer
  13152. * @param indexBuffer defines the target index buffer
  13153. * @param indices defines the data to update
  13154. * @param offset defines the offset in the target index buffer where update should start
  13155. */
  13156. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13157. if (offset === void 0) { offset = 0; }
  13158. // Force cache update
  13159. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13160. this.bindIndexBuffer(indexBuffer);
  13161. var arrayBuffer;
  13162. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13163. arrayBuffer = indices;
  13164. }
  13165. else {
  13166. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13167. }
  13168. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13169. this._resetIndexBufferBinding();
  13170. };
  13171. /**
  13172. * Updates a dynamic vertex buffer.
  13173. * @param vertexBuffer the vertex buffer to update
  13174. * @param data the data used to update the vertex buffer
  13175. * @param byteOffset the byte offset of the data
  13176. * @param byteLength the byte length of the data
  13177. */
  13178. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13179. this.bindArrayBuffer(vertexBuffer);
  13180. if (byteOffset === undefined) {
  13181. byteOffset = 0;
  13182. }
  13183. if (byteLength === undefined) {
  13184. if (data instanceof Array) {
  13185. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13186. }
  13187. else {
  13188. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13189. }
  13190. }
  13191. else {
  13192. if (data instanceof Array) {
  13193. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13194. }
  13195. else {
  13196. if (data instanceof ArrayBuffer) {
  13197. data = new Uint8Array(data, byteOffset, byteLength);
  13198. }
  13199. else {
  13200. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13201. }
  13202. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13203. }
  13204. }
  13205. this._resetVertexBufferBinding();
  13206. };
  13207. Engine.prototype._resetIndexBufferBinding = function () {
  13208. this.bindIndexBuffer(null);
  13209. this._cachedIndexBuffer = null;
  13210. };
  13211. /**
  13212. * Creates a new index buffer
  13213. * @param indices defines the content of the index buffer
  13214. * @param updatable defines if the index buffer must be updatable
  13215. * @returns a new webGL buffer
  13216. */
  13217. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13218. var vbo = this._gl.createBuffer();
  13219. if (!vbo) {
  13220. throw new Error("Unable to create index buffer");
  13221. }
  13222. this.bindIndexBuffer(vbo);
  13223. // Check for 32 bits indices
  13224. var arrayBuffer;
  13225. var need32Bits = false;
  13226. if (indices instanceof Uint16Array) {
  13227. arrayBuffer = indices;
  13228. }
  13229. else {
  13230. //check 32 bit support
  13231. if (this._caps.uintIndices) {
  13232. if (indices instanceof Uint32Array) {
  13233. arrayBuffer = indices;
  13234. need32Bits = true;
  13235. }
  13236. else {
  13237. //number[] or Int32Array, check if 32 bit is necessary
  13238. for (var index = 0; index < indices.length; index++) {
  13239. if (indices[index] > 65535) {
  13240. need32Bits = true;
  13241. break;
  13242. }
  13243. }
  13244. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13245. }
  13246. }
  13247. else {
  13248. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13249. arrayBuffer = new Uint16Array(indices);
  13250. }
  13251. }
  13252. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13253. this._resetIndexBufferBinding();
  13254. vbo.references = 1;
  13255. vbo.is32Bits = need32Bits;
  13256. return vbo;
  13257. };
  13258. /**
  13259. * Bind a webGL buffer to the webGL context
  13260. * @param buffer defines the buffer to bind
  13261. */
  13262. Engine.prototype.bindArrayBuffer = function (buffer) {
  13263. if (!this._vaoRecordInProgress) {
  13264. this._unbindVertexArrayObject();
  13265. }
  13266. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13267. };
  13268. /**
  13269. * Bind an uniform buffer to the current webGL context
  13270. * @param buffer defines the buffer to bind
  13271. */
  13272. Engine.prototype.bindUniformBuffer = function (buffer) {
  13273. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13274. };
  13275. /**
  13276. * Bind a buffer to the current webGL context at a given location
  13277. * @param buffer defines the buffer to bind
  13278. * @param location defines the index where to bind the buffer
  13279. */
  13280. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13281. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13282. };
  13283. /**
  13284. * Bind a specific block at a given index in a specific shader program
  13285. * @param shaderProgram defines the shader program
  13286. * @param blockName defines the block name
  13287. * @param index defines the index where to bind the block
  13288. */
  13289. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13290. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13291. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13292. };
  13293. ;
  13294. Engine.prototype.bindIndexBuffer = function (buffer) {
  13295. if (!this._vaoRecordInProgress) {
  13296. this._unbindVertexArrayObject();
  13297. }
  13298. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13299. };
  13300. Engine.prototype.bindBuffer = function (buffer, target) {
  13301. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13302. this._gl.bindBuffer(target, buffer);
  13303. this._currentBoundBuffer[target] = buffer;
  13304. }
  13305. };
  13306. /**
  13307. * update the bound buffer with the given data
  13308. * @param data defines the data to update
  13309. */
  13310. Engine.prototype.updateArrayBuffer = function (data) {
  13311. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13312. };
  13313. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13314. var pointer = this._currentBufferPointers[indx];
  13315. var changed = false;
  13316. if (!pointer.active) {
  13317. changed = true;
  13318. pointer.active = true;
  13319. pointer.index = indx;
  13320. pointer.size = size;
  13321. pointer.type = type;
  13322. pointer.normalized = normalized;
  13323. pointer.stride = stride;
  13324. pointer.offset = offset;
  13325. pointer.buffer = buffer;
  13326. }
  13327. else {
  13328. if (pointer.buffer !== buffer) {
  13329. pointer.buffer = buffer;
  13330. changed = true;
  13331. }
  13332. if (pointer.size !== size) {
  13333. pointer.size = size;
  13334. changed = true;
  13335. }
  13336. if (pointer.type !== type) {
  13337. pointer.type = type;
  13338. changed = true;
  13339. }
  13340. if (pointer.normalized !== normalized) {
  13341. pointer.normalized = normalized;
  13342. changed = true;
  13343. }
  13344. if (pointer.stride !== stride) {
  13345. pointer.stride = stride;
  13346. changed = true;
  13347. }
  13348. if (pointer.offset !== offset) {
  13349. pointer.offset = offset;
  13350. changed = true;
  13351. }
  13352. }
  13353. if (changed || this._vaoRecordInProgress) {
  13354. this.bindArrayBuffer(buffer);
  13355. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13356. }
  13357. };
  13358. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13359. if (indexBuffer == null) {
  13360. return;
  13361. }
  13362. if (this._cachedIndexBuffer !== indexBuffer) {
  13363. this._cachedIndexBuffer = indexBuffer;
  13364. this.bindIndexBuffer(indexBuffer);
  13365. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13366. }
  13367. };
  13368. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13369. var attributes = effect.getAttributesNames();
  13370. if (!this._vaoRecordInProgress) {
  13371. this._unbindVertexArrayObject();
  13372. }
  13373. this.unbindAllAttributes();
  13374. for (var index = 0; index < attributes.length; index++) {
  13375. var order = effect.getAttributeLocation(index);
  13376. if (order >= 0) {
  13377. var vertexBuffer = vertexBuffers[attributes[index]];
  13378. if (!vertexBuffer) {
  13379. continue;
  13380. }
  13381. this._gl.enableVertexAttribArray(order);
  13382. if (!this._vaoRecordInProgress) {
  13383. this._vertexAttribArraysEnabled[order] = true;
  13384. }
  13385. var buffer = vertexBuffer.getBuffer();
  13386. if (buffer) {
  13387. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13388. if (vertexBuffer.getIsInstanced()) {
  13389. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13390. if (!this._vaoRecordInProgress) {
  13391. this._currentInstanceLocations.push(order);
  13392. this._currentInstanceBuffers.push(buffer);
  13393. }
  13394. }
  13395. }
  13396. }
  13397. }
  13398. };
  13399. /**
  13400. * Records a vertex array object
  13401. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13402. * @param vertexBuffers defines the list of vertex buffers to store
  13403. * @param indexBuffer defines the index buffer to store
  13404. * @param effect defines the effect to store
  13405. * @returns the new vertex array object
  13406. */
  13407. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13408. var vao = this._gl.createVertexArray();
  13409. this._vaoRecordInProgress = true;
  13410. this._gl.bindVertexArray(vao);
  13411. this._mustWipeVertexAttributes = true;
  13412. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13413. this.bindIndexBuffer(indexBuffer);
  13414. this._vaoRecordInProgress = false;
  13415. this._gl.bindVertexArray(null);
  13416. return vao;
  13417. };
  13418. /**
  13419. * Bind a specific vertex array object
  13420. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13421. * @param vertexArrayObject defines the vertex array object to bind
  13422. * @param indexBuffer defines the index buffer to bind
  13423. */
  13424. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13425. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13426. this._cachedVertexArrayObject = vertexArrayObject;
  13427. this._gl.bindVertexArray(vertexArrayObject);
  13428. this._cachedVertexBuffers = null;
  13429. this._cachedIndexBuffer = null;
  13430. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13431. this._mustWipeVertexAttributes = true;
  13432. }
  13433. };
  13434. /**
  13435. * Bind webGl buffers directly to the webGL context
  13436. * @param vertexBuffer defines the vertex buffer to bind
  13437. * @param indexBuffer defines the index buffer to bind
  13438. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13439. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13440. * @param effect defines the effect associated with the vertex buffer
  13441. */
  13442. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13443. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13444. this._cachedVertexBuffers = vertexBuffer;
  13445. this._cachedEffectForVertexBuffers = effect;
  13446. var attributesCount = effect.getAttributesCount();
  13447. this._unbindVertexArrayObject();
  13448. this.unbindAllAttributes();
  13449. var offset = 0;
  13450. for (var index = 0; index < attributesCount; index++) {
  13451. if (index < vertexDeclaration.length) {
  13452. var order = effect.getAttributeLocation(index);
  13453. if (order >= 0) {
  13454. this._gl.enableVertexAttribArray(order);
  13455. this._vertexAttribArraysEnabled[order] = true;
  13456. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13457. }
  13458. offset += vertexDeclaration[index] * 4;
  13459. }
  13460. }
  13461. }
  13462. this._bindIndexBufferWithCache(indexBuffer);
  13463. };
  13464. Engine.prototype._unbindVertexArrayObject = function () {
  13465. if (!this._cachedVertexArrayObject) {
  13466. return;
  13467. }
  13468. this._cachedVertexArrayObject = null;
  13469. this._gl.bindVertexArray(null);
  13470. };
  13471. /**
  13472. * Bind a list of vertex buffers to the webGL context
  13473. * @param vertexBuffers defines the list of vertex buffers to bind
  13474. * @param indexBuffer defines the index buffer to bind
  13475. * @param effect defines the effect associated with the vertex buffers
  13476. */
  13477. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13478. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13479. this._cachedVertexBuffers = vertexBuffers;
  13480. this._cachedEffectForVertexBuffers = effect;
  13481. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13482. }
  13483. this._bindIndexBufferWithCache(indexBuffer);
  13484. };
  13485. /**
  13486. * Unbind all instance attributes
  13487. */
  13488. Engine.prototype.unbindInstanceAttributes = function () {
  13489. var boundBuffer;
  13490. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13491. var instancesBuffer = this._currentInstanceBuffers[i];
  13492. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13493. boundBuffer = instancesBuffer;
  13494. this.bindArrayBuffer(instancesBuffer);
  13495. }
  13496. var offsetLocation = this._currentInstanceLocations[i];
  13497. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13498. }
  13499. this._currentInstanceBuffers.length = 0;
  13500. this._currentInstanceLocations.length = 0;
  13501. };
  13502. /**
  13503. * Release and free the memory of a vertex array object
  13504. * @param vao defines the vertex array object to delete
  13505. */
  13506. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13507. this._gl.deleteVertexArray(vao);
  13508. };
  13509. /** @hidden */
  13510. Engine.prototype._releaseBuffer = function (buffer) {
  13511. buffer.references--;
  13512. if (buffer.references === 0) {
  13513. this._gl.deleteBuffer(buffer);
  13514. return true;
  13515. }
  13516. return false;
  13517. };
  13518. /**
  13519. * Creates a webGL buffer to use with instanciation
  13520. * @param capacity defines the size of the buffer
  13521. * @returns the webGL buffer
  13522. */
  13523. Engine.prototype.createInstancesBuffer = function (capacity) {
  13524. var buffer = this._gl.createBuffer();
  13525. if (!buffer) {
  13526. throw new Error("Unable to create instance buffer");
  13527. }
  13528. buffer.capacity = capacity;
  13529. this.bindArrayBuffer(buffer);
  13530. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13531. return buffer;
  13532. };
  13533. /**
  13534. * Delete a webGL buffer used with instanciation
  13535. * @param buffer defines the webGL buffer to delete
  13536. */
  13537. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13538. this._gl.deleteBuffer(buffer);
  13539. };
  13540. /**
  13541. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13542. * @param instancesBuffer defines the webGL buffer to update and bind
  13543. * @param data defines the data to store in the buffer
  13544. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13545. */
  13546. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13547. this.bindArrayBuffer(instancesBuffer);
  13548. if (data) {
  13549. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13550. }
  13551. if (offsetLocations[0].index !== undefined) {
  13552. var stride = 0;
  13553. for (var i = 0; i < offsetLocations.length; i++) {
  13554. var ai = offsetLocations[i];
  13555. stride += ai.attributeSize * 4;
  13556. }
  13557. for (var i = 0; i < offsetLocations.length; i++) {
  13558. var ai = offsetLocations[i];
  13559. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13560. this._gl.enableVertexAttribArray(ai.index);
  13561. this._vertexAttribArraysEnabled[ai.index] = true;
  13562. }
  13563. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13564. this._gl.vertexAttribDivisor(ai.index, 1);
  13565. this._currentInstanceLocations.push(ai.index);
  13566. this._currentInstanceBuffers.push(instancesBuffer);
  13567. }
  13568. }
  13569. else {
  13570. for (var index = 0; index < 4; index++) {
  13571. var offsetLocation = offsetLocations[index];
  13572. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13573. this._gl.enableVertexAttribArray(offsetLocation);
  13574. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13575. }
  13576. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13577. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13578. this._currentInstanceLocations.push(offsetLocation);
  13579. this._currentInstanceBuffers.push(instancesBuffer);
  13580. }
  13581. }
  13582. };
  13583. /**
  13584. * Apply all cached states (depth, culling, stencil and alpha)
  13585. */
  13586. Engine.prototype.applyStates = function () {
  13587. this._depthCullingState.apply(this._gl);
  13588. this._stencilState.apply(this._gl);
  13589. this._alphaState.apply(this._gl);
  13590. };
  13591. /**
  13592. * Send a draw order
  13593. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13594. * @param indexStart defines the starting index
  13595. * @param indexCount defines the number of index to draw
  13596. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13597. */
  13598. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13599. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13600. };
  13601. /**
  13602. * Draw a list of points
  13603. * @param verticesStart defines the index of first vertex to draw
  13604. * @param verticesCount defines the count of vertices to draw
  13605. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13606. */
  13607. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13608. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13609. };
  13610. /**
  13611. * Draw a list of unindexed primitives
  13612. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13613. * @param verticesStart defines the index of first vertex to draw
  13614. * @param verticesCount defines the count of vertices to draw
  13615. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13616. */
  13617. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13618. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13619. };
  13620. /**
  13621. * Draw a list of indexed primitives
  13622. * @param fillMode defines the primitive to use
  13623. * @param indexStart defines the starting index
  13624. * @param indexCount defines the number of index to draw
  13625. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13626. */
  13627. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13628. // Apply states
  13629. this.applyStates();
  13630. this._drawCalls.addCount(1, false);
  13631. // Render
  13632. var drawMode = this._drawMode(fillMode);
  13633. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13634. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13635. if (instancesCount) {
  13636. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13637. }
  13638. else {
  13639. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13640. }
  13641. };
  13642. /**
  13643. * Draw a list of unindexed primitives
  13644. * @param fillMode defines the primitive to use
  13645. * @param verticesStart defines the index of first vertex to draw
  13646. * @param verticesCount defines the count of vertices to draw
  13647. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13648. */
  13649. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13650. // Apply states
  13651. this.applyStates();
  13652. this._drawCalls.addCount(1, false);
  13653. var drawMode = this._drawMode(fillMode);
  13654. if (instancesCount) {
  13655. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13656. }
  13657. else {
  13658. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13659. }
  13660. };
  13661. Engine.prototype._drawMode = function (fillMode) {
  13662. switch (fillMode) {
  13663. // Triangle views
  13664. case BABYLON.Material.TriangleFillMode:
  13665. return this._gl.TRIANGLES;
  13666. case BABYLON.Material.PointFillMode:
  13667. return this._gl.POINTS;
  13668. case BABYLON.Material.WireFrameFillMode:
  13669. return this._gl.LINES;
  13670. // Draw modes
  13671. case BABYLON.Material.PointListDrawMode:
  13672. return this._gl.POINTS;
  13673. case BABYLON.Material.LineListDrawMode:
  13674. return this._gl.LINES;
  13675. case BABYLON.Material.LineLoopDrawMode:
  13676. return this._gl.LINE_LOOP;
  13677. case BABYLON.Material.LineStripDrawMode:
  13678. return this._gl.LINE_STRIP;
  13679. case BABYLON.Material.TriangleStripDrawMode:
  13680. return this._gl.TRIANGLE_STRIP;
  13681. case BABYLON.Material.TriangleFanDrawMode:
  13682. return this._gl.TRIANGLE_FAN;
  13683. default:
  13684. return this._gl.TRIANGLES;
  13685. }
  13686. };
  13687. // Shaders
  13688. /** @hidden */
  13689. Engine.prototype._releaseEffect = function (effect) {
  13690. if (this._compiledEffects[effect._key]) {
  13691. delete this._compiledEffects[effect._key];
  13692. this._deleteProgram(effect.getProgram());
  13693. }
  13694. };
  13695. /** @hidden */
  13696. Engine.prototype._deleteProgram = function (program) {
  13697. if (program) {
  13698. program.__SPECTOR_rebuildProgram = null;
  13699. if (program.transformFeedback) {
  13700. this.deleteTransformFeedback(program.transformFeedback);
  13701. program.transformFeedback = null;
  13702. }
  13703. this._gl.deleteProgram(program);
  13704. }
  13705. };
  13706. /**
  13707. * Create a new effect (used to store vertex/fragment shaders)
  13708. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13709. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13710. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13711. * @param samplers defines an array of string used to represent textures
  13712. * @param defines defines the string containing the defines to use to compile the shaders
  13713. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13714. * @param onCompiled defines a function to call when the effect creation is successful
  13715. * @param onError defines a function to call when the effect creation has failed
  13716. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13717. * @returns the new Effect
  13718. */
  13719. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13720. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13721. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13722. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13723. if (this._compiledEffects[name]) {
  13724. var compiledEffect = this._compiledEffects[name];
  13725. if (onCompiled && compiledEffect.isReady()) {
  13726. onCompiled(compiledEffect);
  13727. }
  13728. return compiledEffect;
  13729. }
  13730. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13731. effect._key = name;
  13732. this._compiledEffects[name] = effect;
  13733. return effect;
  13734. };
  13735. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13736. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13737. };
  13738. ;
  13739. Engine.prototype._compileRawShader = function (source, type) {
  13740. var gl = this._gl;
  13741. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13742. gl.shaderSource(shader, source);
  13743. gl.compileShader(shader);
  13744. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13745. var log = gl.getShaderInfoLog(shader);
  13746. if (log) {
  13747. throw new Error(log);
  13748. }
  13749. }
  13750. if (!shader) {
  13751. throw new Error("Something went wrong while compile the shader.");
  13752. }
  13753. return shader;
  13754. };
  13755. ;
  13756. /**
  13757. * Directly creates a webGL program
  13758. * @param vertexCode defines the vertex shader code to use
  13759. * @param fragmentCode defines the fragment shader code to use
  13760. * @param context defines the webGL context to use (if not set, the current one will be used)
  13761. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13762. * @returns the new webGL program
  13763. */
  13764. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13765. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13766. context = context || this._gl;
  13767. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13768. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13769. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13770. };
  13771. /**
  13772. * Creates a webGL program
  13773. * @param vertexCode defines the vertex shader code to use
  13774. * @param fragmentCode defines the fragment shader code to use
  13775. * @param defines defines the string containing the defines to use to compile the shaders
  13776. * @param context defines the webGL context to use (if not set, the current one will be used)
  13777. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13778. * @returns the new webGL program
  13779. */
  13780. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13781. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13782. context = context || this._gl;
  13783. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13784. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13785. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13786. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13787. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13788. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13789. return program;
  13790. };
  13791. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13792. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13793. var shaderProgram = context.createProgram();
  13794. if (!shaderProgram) {
  13795. throw new Error("Unable to create program");
  13796. }
  13797. context.attachShader(shaderProgram, vertexShader);
  13798. context.attachShader(shaderProgram, fragmentShader);
  13799. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13800. var transformFeedback = this.createTransformFeedback();
  13801. this.bindTransformFeedback(transformFeedback);
  13802. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13803. shaderProgram.transformFeedback = transformFeedback;
  13804. }
  13805. context.linkProgram(shaderProgram);
  13806. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13807. this.bindTransformFeedback(null);
  13808. }
  13809. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13810. if (!linked) {
  13811. var error = context.getProgramInfoLog(shaderProgram);
  13812. if (error) {
  13813. throw new Error(error);
  13814. }
  13815. }
  13816. if (this.validateShaderPrograms) {
  13817. context.validateProgram(shaderProgram);
  13818. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13819. if (!validated) {
  13820. var error = context.getProgramInfoLog(shaderProgram);
  13821. if (error) {
  13822. throw new Error(error);
  13823. }
  13824. }
  13825. }
  13826. context.deleteShader(vertexShader);
  13827. context.deleteShader(fragmentShader);
  13828. return shaderProgram;
  13829. };
  13830. /**
  13831. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13832. * @param shaderProgram defines the webGL program to use
  13833. * @param uniformsNames defines the list of uniform names
  13834. * @returns an array of webGL uniform locations
  13835. */
  13836. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13837. var results = new Array();
  13838. for (var index = 0; index < uniformsNames.length; index++) {
  13839. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13840. }
  13841. return results;
  13842. };
  13843. /**
  13844. * Gets the lsit of active attributes for a given webGL program
  13845. * @param shaderProgram defines the webGL program to use
  13846. * @param attributesNames defines the list of attribute names to get
  13847. * @returns an array of indices indicating the offset of each attribute
  13848. */
  13849. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13850. var results = [];
  13851. for (var index = 0; index < attributesNames.length; index++) {
  13852. try {
  13853. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13854. }
  13855. catch (e) {
  13856. results.push(-1);
  13857. }
  13858. }
  13859. return results;
  13860. };
  13861. /**
  13862. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13863. * @param effect defines the effect to activate
  13864. */
  13865. Engine.prototype.enableEffect = function (effect) {
  13866. if (!effect || effect === this._currentEffect) {
  13867. return;
  13868. }
  13869. // Use program
  13870. this.bindSamplers(effect);
  13871. this._currentEffect = effect;
  13872. if (effect.onBind) {
  13873. effect.onBind(effect);
  13874. }
  13875. if (effect._onBindObservable) {
  13876. effect._onBindObservable.notifyObservers(effect);
  13877. }
  13878. };
  13879. /**
  13880. * Set the value of an uniform to an array of int32
  13881. * @param uniform defines the webGL uniform location where to store the value
  13882. * @param array defines the array of int32 to store
  13883. */
  13884. Engine.prototype.setIntArray = function (uniform, array) {
  13885. if (!uniform)
  13886. return;
  13887. this._gl.uniform1iv(uniform, array);
  13888. };
  13889. /**
  13890. * Set the value of an uniform to an array of int32 (stored as vec2)
  13891. * @param uniform defines the webGL uniform location where to store the value
  13892. * @param array defines the array of int32 to store
  13893. */
  13894. Engine.prototype.setIntArray2 = function (uniform, array) {
  13895. if (!uniform || array.length % 2 !== 0)
  13896. return;
  13897. this._gl.uniform2iv(uniform, array);
  13898. };
  13899. /**
  13900. * Set the value of an uniform to an array of int32 (stored as vec3)
  13901. * @param uniform defines the webGL uniform location where to store the value
  13902. * @param array defines the array of int32 to store
  13903. */
  13904. Engine.prototype.setIntArray3 = function (uniform, array) {
  13905. if (!uniform || array.length % 3 !== 0)
  13906. return;
  13907. this._gl.uniform3iv(uniform, array);
  13908. };
  13909. /**
  13910. * Set the value of an uniform to an array of int32 (stored as vec4)
  13911. * @param uniform defines the webGL uniform location where to store the value
  13912. * @param array defines the array of int32 to store
  13913. */
  13914. Engine.prototype.setIntArray4 = function (uniform, array) {
  13915. if (!uniform || array.length % 4 !== 0)
  13916. return;
  13917. this._gl.uniform4iv(uniform, array);
  13918. };
  13919. /**
  13920. * Set the value of an uniform to an array of float32
  13921. * @param uniform defines the webGL uniform location where to store the value
  13922. * @param array defines the array of float32 to store
  13923. */
  13924. Engine.prototype.setFloatArray = function (uniform, array) {
  13925. if (!uniform)
  13926. return;
  13927. this._gl.uniform1fv(uniform, array);
  13928. };
  13929. /**
  13930. * Set the value of an uniform to an array of float32 (stored as vec2)
  13931. * @param uniform defines the webGL uniform location where to store the value
  13932. * @param array defines the array of float32 to store
  13933. */
  13934. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13935. if (!uniform || array.length % 2 !== 0)
  13936. return;
  13937. this._gl.uniform2fv(uniform, array);
  13938. };
  13939. /**
  13940. * Set the value of an uniform to an array of float32 (stored as vec3)
  13941. * @param uniform defines the webGL uniform location where to store the value
  13942. * @param array defines the array of float32 to store
  13943. */
  13944. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13945. if (!uniform || array.length % 3 !== 0)
  13946. return;
  13947. this._gl.uniform3fv(uniform, array);
  13948. };
  13949. /**
  13950. * Set the value of an uniform to an array of float32 (stored as vec4)
  13951. * @param uniform defines the webGL uniform location where to store the value
  13952. * @param array defines the array of float32 to store
  13953. */
  13954. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13955. if (!uniform || array.length % 4 !== 0)
  13956. return;
  13957. this._gl.uniform4fv(uniform, array);
  13958. };
  13959. /**
  13960. * Set the value of an uniform to an array of number
  13961. * @param uniform defines the webGL uniform location where to store the value
  13962. * @param array defines the array of number to store
  13963. */
  13964. Engine.prototype.setArray = function (uniform, array) {
  13965. if (!uniform)
  13966. return;
  13967. this._gl.uniform1fv(uniform, array);
  13968. };
  13969. /**
  13970. * Set the value of an uniform to an array of number (stored as vec2)
  13971. * @param uniform defines the webGL uniform location where to store the value
  13972. * @param array defines the array of number to store
  13973. */
  13974. Engine.prototype.setArray2 = function (uniform, array) {
  13975. if (!uniform || array.length % 2 !== 0)
  13976. return;
  13977. this._gl.uniform2fv(uniform, array);
  13978. };
  13979. /**
  13980. * Set the value of an uniform to an array of number (stored as vec3)
  13981. * @param uniform defines the webGL uniform location where to store the value
  13982. * @param array defines the array of number to store
  13983. */
  13984. Engine.prototype.setArray3 = function (uniform, array) {
  13985. if (!uniform || array.length % 3 !== 0)
  13986. return;
  13987. this._gl.uniform3fv(uniform, array);
  13988. };
  13989. /**
  13990. * Set the value of an uniform to an array of number (stored as vec4)
  13991. * @param uniform defines the webGL uniform location where to store the value
  13992. * @param array defines the array of number to store
  13993. */
  13994. Engine.prototype.setArray4 = function (uniform, array) {
  13995. if (!uniform || array.length % 4 !== 0)
  13996. return;
  13997. this._gl.uniform4fv(uniform, array);
  13998. };
  13999. /**
  14000. * Set the value of an uniform to an array of float32 (stored as matrices)
  14001. * @param uniform defines the webGL uniform location where to store the value
  14002. * @param matrices defines the array of float32 to store
  14003. */
  14004. Engine.prototype.setMatrices = function (uniform, matrices) {
  14005. if (!uniform)
  14006. return;
  14007. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14008. };
  14009. /**
  14010. * Set the value of an uniform to a matrix
  14011. * @param uniform defines the webGL uniform location where to store the value
  14012. * @param matrix defines the matrix to store
  14013. */
  14014. Engine.prototype.setMatrix = function (uniform, matrix) {
  14015. if (!uniform)
  14016. return;
  14017. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14018. };
  14019. /**
  14020. * Set the value of an uniform to a matrix (3x3)
  14021. * @param uniform defines the webGL uniform location where to store the value
  14022. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14023. */
  14024. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14025. if (!uniform)
  14026. return;
  14027. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14028. };
  14029. /**
  14030. * Set the value of an uniform to a matrix (2x2)
  14031. * @param uniform defines the webGL uniform location where to store the value
  14032. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14033. */
  14034. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14035. if (!uniform)
  14036. return;
  14037. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14038. };
  14039. /**
  14040. * Set the value of an uniform to a number (int)
  14041. * @param uniform defines the webGL uniform location where to store the value
  14042. * @param value defines the int number to store
  14043. */
  14044. Engine.prototype.setInt = function (uniform, value) {
  14045. if (!uniform)
  14046. return;
  14047. this._gl.uniform1i(uniform, value);
  14048. };
  14049. /**
  14050. * Set the value of an uniform to a number (float)
  14051. * @param uniform defines the webGL uniform location where to store the value
  14052. * @param value defines the float number to store
  14053. */
  14054. Engine.prototype.setFloat = function (uniform, value) {
  14055. if (!uniform)
  14056. return;
  14057. this._gl.uniform1f(uniform, value);
  14058. };
  14059. /**
  14060. * Set the value of an uniform to a vec2
  14061. * @param uniform defines the webGL uniform location where to store the value
  14062. * @param x defines the 1st component of the value
  14063. * @param y defines the 2nd component of the value
  14064. */
  14065. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14066. if (!uniform)
  14067. return;
  14068. this._gl.uniform2f(uniform, x, y);
  14069. };
  14070. /**
  14071. * Set the value of an uniform to a vec3
  14072. * @param uniform defines the webGL uniform location where to store the value
  14073. * @param x defines the 1st component of the value
  14074. * @param y defines the 2nd component of the value
  14075. * @param z defines the 3rd component of the value
  14076. */
  14077. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14078. if (!uniform)
  14079. return;
  14080. this._gl.uniform3f(uniform, x, y, z);
  14081. };
  14082. /**
  14083. * Set the value of an uniform to a boolean
  14084. * @param uniform defines the webGL uniform location where to store the value
  14085. * @param bool defines the boolean to store
  14086. */
  14087. Engine.prototype.setBool = function (uniform, bool) {
  14088. if (!uniform)
  14089. return;
  14090. this._gl.uniform1i(uniform, bool);
  14091. };
  14092. /**
  14093. * Set the value of an uniform to a vec4
  14094. * @param uniform defines the webGL uniform location where to store the value
  14095. * @param x defines the 1st component of the value
  14096. * @param y defines the 2nd component of the value
  14097. * @param z defines the 3rd component of the value
  14098. * @param w defines the 4th component of the value
  14099. */
  14100. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14101. if (!uniform)
  14102. return;
  14103. this._gl.uniform4f(uniform, x, y, z, w);
  14104. };
  14105. /**
  14106. * Set the value of an uniform to a Color3
  14107. * @param uniform defines the webGL uniform location where to store the value
  14108. * @param color3 defines the color to store
  14109. */
  14110. Engine.prototype.setColor3 = function (uniform, color3) {
  14111. if (!uniform)
  14112. return;
  14113. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14114. };
  14115. /**
  14116. * Set the value of an uniform to a Color3 and an alpha value
  14117. * @param uniform defines the webGL uniform location where to store the value
  14118. * @param color3 defines the color to store
  14119. * @param alpha defines the alpha component to store
  14120. */
  14121. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14122. if (!uniform)
  14123. return;
  14124. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14125. };
  14126. /**
  14127. * Sets a Color4 on a uniform variable
  14128. * @param uniform defines the uniform location
  14129. * @param color4 defines the value to be set
  14130. */
  14131. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14132. if (!uniform)
  14133. return;
  14134. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14135. };
  14136. // States
  14137. /**
  14138. * Set various states to the webGL context
  14139. * @param culling defines backface culling state
  14140. * @param zOffset defines the value to apply to zOffset (0 by default)
  14141. * @param force defines if states must be applied even if cache is up to date
  14142. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14143. */
  14144. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14145. if (zOffset === void 0) { zOffset = 0; }
  14146. if (reverseSide === void 0) { reverseSide = false; }
  14147. // Culling
  14148. if (this._depthCullingState.cull !== culling || force) {
  14149. this._depthCullingState.cull = culling;
  14150. }
  14151. // Cull face
  14152. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14153. if (this._depthCullingState.cullFace !== cullFace || force) {
  14154. this._depthCullingState.cullFace = cullFace;
  14155. }
  14156. // Z offset
  14157. this.setZOffset(zOffset);
  14158. // Front face
  14159. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14160. if (this._depthCullingState.frontFace !== frontFace || force) {
  14161. this._depthCullingState.frontFace = frontFace;
  14162. }
  14163. };
  14164. /**
  14165. * Set the z offset to apply to current rendering
  14166. * @param value defines the offset to apply
  14167. */
  14168. Engine.prototype.setZOffset = function (value) {
  14169. this._depthCullingState.zOffset = value;
  14170. };
  14171. /**
  14172. * Gets the current value of the zOffset
  14173. * @returns the current zOffset state
  14174. */
  14175. Engine.prototype.getZOffset = function () {
  14176. return this._depthCullingState.zOffset;
  14177. };
  14178. /**
  14179. * Enable or disable depth buffering
  14180. * @param enable defines the state to set
  14181. */
  14182. Engine.prototype.setDepthBuffer = function (enable) {
  14183. this._depthCullingState.depthTest = enable;
  14184. };
  14185. /**
  14186. * Gets a boolean indicating if depth writing is enabled
  14187. * @returns the current depth writing state
  14188. */
  14189. Engine.prototype.getDepthWrite = function () {
  14190. return this._depthCullingState.depthMask;
  14191. };
  14192. /**
  14193. * Enable or disable depth writing
  14194. * @param enable defines the state to set
  14195. */
  14196. Engine.prototype.setDepthWrite = function (enable) {
  14197. this._depthCullingState.depthMask = enable;
  14198. };
  14199. /**
  14200. * Enable or disable color writing
  14201. * @param enable defines the state to set
  14202. */
  14203. Engine.prototype.setColorWrite = function (enable) {
  14204. this._gl.colorMask(enable, enable, enable, enable);
  14205. this._colorWrite = enable;
  14206. };
  14207. /**
  14208. * Gets a boolean indicating if color writing is enabled
  14209. * @returns the current color writing state
  14210. */
  14211. Engine.prototype.getColorWrite = function () {
  14212. return this._colorWrite;
  14213. };
  14214. /**
  14215. * Sets alpha constants used by some alpha blending modes
  14216. * @param r defines the red component
  14217. * @param g defines the green component
  14218. * @param b defines the blue component
  14219. * @param a defines the alpha component
  14220. */
  14221. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14222. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14223. };
  14224. /**
  14225. * Sets the current alpha mode
  14226. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14227. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14228. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14229. */
  14230. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14231. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14232. if (this._alphaMode === mode) {
  14233. return;
  14234. }
  14235. switch (mode) {
  14236. case Engine.ALPHA_DISABLE:
  14237. this._alphaState.alphaBlend = false;
  14238. break;
  14239. case Engine.ALPHA_PREMULTIPLIED:
  14240. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14241. this._alphaState.alphaBlend = true;
  14242. break;
  14243. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14244. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14245. this._alphaState.alphaBlend = true;
  14246. break;
  14247. case Engine.ALPHA_COMBINE:
  14248. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14249. this._alphaState.alphaBlend = true;
  14250. break;
  14251. case Engine.ALPHA_ONEONE:
  14252. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14253. this._alphaState.alphaBlend = true;
  14254. break;
  14255. case Engine.ALPHA_ADD:
  14256. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14257. this._alphaState.alphaBlend = true;
  14258. break;
  14259. case Engine.ALPHA_SUBTRACT:
  14260. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14261. this._alphaState.alphaBlend = true;
  14262. break;
  14263. case Engine.ALPHA_MULTIPLY:
  14264. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14265. this._alphaState.alphaBlend = true;
  14266. break;
  14267. case Engine.ALPHA_MAXIMIZED:
  14268. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14269. this._alphaState.alphaBlend = true;
  14270. break;
  14271. case Engine.ALPHA_INTERPOLATE:
  14272. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14273. this._alphaState.alphaBlend = true;
  14274. break;
  14275. case Engine.ALPHA_SCREENMODE:
  14276. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14277. this._alphaState.alphaBlend = true;
  14278. break;
  14279. }
  14280. if (!noDepthWriteChange) {
  14281. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14282. }
  14283. this._alphaMode = mode;
  14284. };
  14285. /**
  14286. * Gets the current alpha mode
  14287. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14288. * @returns the current alpha mode
  14289. */
  14290. Engine.prototype.getAlphaMode = function () {
  14291. return this._alphaMode;
  14292. };
  14293. // Textures
  14294. /**
  14295. * Clears the list of texture accessible through engine.
  14296. * This can help preventing texture load conflict due to name collision.
  14297. */
  14298. Engine.prototype.clearInternalTexturesCache = function () {
  14299. this._internalTexturesCache = [];
  14300. };
  14301. /**
  14302. * Force the entire cache to be cleared
  14303. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14304. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14305. */
  14306. Engine.prototype.wipeCaches = function (bruteForce) {
  14307. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14308. return;
  14309. }
  14310. this._currentEffect = null;
  14311. this._viewportCached.x = 0;
  14312. this._viewportCached.y = 0;
  14313. this._viewportCached.z = 0;
  14314. this._viewportCached.w = 0;
  14315. if (bruteForce) {
  14316. this.resetTextureCache();
  14317. this._currentProgram = null;
  14318. this._stencilState.reset();
  14319. this._depthCullingState.reset();
  14320. this.setDepthFunctionToLessOrEqual();
  14321. this._alphaState.reset();
  14322. this._unpackFlipYCached = null;
  14323. }
  14324. this._resetVertexBufferBinding();
  14325. this._cachedIndexBuffer = null;
  14326. this._cachedEffectForVertexBuffers = null;
  14327. this._unbindVertexArrayObject();
  14328. this.bindIndexBuffer(null);
  14329. };
  14330. /**
  14331. * Set the compressed texture format to use, based on the formats you have, and the formats
  14332. * supported by the hardware / browser.
  14333. *
  14334. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14335. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14336. * to API arguments needed to compressed textures. This puts the burden on the container
  14337. * generator to house the arcane code for determining these for current & future formats.
  14338. *
  14339. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14340. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14341. *
  14342. * Note: The result of this call is not taken into account when a texture is base64.
  14343. *
  14344. * @param formatsAvailable defines the list of those format families you have created
  14345. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14346. *
  14347. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14348. * @returns The extension selected.
  14349. */
  14350. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14351. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14352. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14353. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14354. return this._textureFormatInUse = this._texturesSupported[i];
  14355. }
  14356. }
  14357. }
  14358. // actively set format to nothing, to allow this to be called more than once
  14359. // and possibly fail the 2nd time
  14360. this._textureFormatInUse = null;
  14361. return null;
  14362. };
  14363. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14364. var gl = this._gl;
  14365. var magFilter = gl.NEAREST;
  14366. var minFilter = gl.NEAREST;
  14367. switch (samplingMode) {
  14368. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14369. magFilter = gl.LINEAR;
  14370. if (generateMipMaps) {
  14371. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14372. }
  14373. else {
  14374. minFilter = gl.LINEAR;
  14375. }
  14376. break;
  14377. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14378. magFilter = gl.LINEAR;
  14379. if (generateMipMaps) {
  14380. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14381. }
  14382. else {
  14383. minFilter = gl.LINEAR;
  14384. }
  14385. break;
  14386. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14387. magFilter = gl.NEAREST;
  14388. if (generateMipMaps) {
  14389. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14390. }
  14391. else {
  14392. minFilter = gl.NEAREST;
  14393. }
  14394. break;
  14395. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14396. magFilter = gl.NEAREST;
  14397. if (generateMipMaps) {
  14398. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14399. }
  14400. else {
  14401. minFilter = gl.NEAREST;
  14402. }
  14403. break;
  14404. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14405. magFilter = gl.NEAREST;
  14406. if (generateMipMaps) {
  14407. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14408. }
  14409. else {
  14410. minFilter = gl.LINEAR;
  14411. }
  14412. break;
  14413. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14414. magFilter = gl.NEAREST;
  14415. if (generateMipMaps) {
  14416. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14417. }
  14418. else {
  14419. minFilter = gl.LINEAR;
  14420. }
  14421. break;
  14422. case Engine.TEXTURE_NEAREST_LINEAR:
  14423. magFilter = gl.NEAREST;
  14424. minFilter = gl.LINEAR;
  14425. break;
  14426. case Engine.TEXTURE_NEAREST_NEAREST:
  14427. magFilter = gl.NEAREST;
  14428. minFilter = gl.NEAREST;
  14429. break;
  14430. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14431. magFilter = gl.LINEAR;
  14432. if (generateMipMaps) {
  14433. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14434. }
  14435. else {
  14436. minFilter = gl.NEAREST;
  14437. }
  14438. break;
  14439. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14440. magFilter = gl.LINEAR;
  14441. if (generateMipMaps) {
  14442. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14443. }
  14444. else {
  14445. minFilter = gl.NEAREST;
  14446. }
  14447. break;
  14448. case Engine.TEXTURE_LINEAR_LINEAR:
  14449. magFilter = gl.LINEAR;
  14450. minFilter = gl.LINEAR;
  14451. break;
  14452. case Engine.TEXTURE_LINEAR_NEAREST:
  14453. magFilter = gl.LINEAR;
  14454. minFilter = gl.NEAREST;
  14455. break;
  14456. }
  14457. return {
  14458. min: minFilter,
  14459. mag: magFilter
  14460. };
  14461. };
  14462. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14463. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14464. var img;
  14465. var onload = function () {
  14466. loadedImages[index] = img;
  14467. loadedImages._internalCount++;
  14468. if (scene) {
  14469. scene._removePendingData(img);
  14470. }
  14471. if (loadedImages._internalCount === 6) {
  14472. onfinish(loadedImages);
  14473. }
  14474. };
  14475. var onerror = function (message, exception) {
  14476. if (scene) {
  14477. scene._removePendingData(img);
  14478. }
  14479. if (onErrorCallBack) {
  14480. onErrorCallBack(message, exception);
  14481. }
  14482. };
  14483. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14484. if (scene) {
  14485. scene._addPendingData(img);
  14486. }
  14487. };
  14488. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14489. if (onError === void 0) { onError = null; }
  14490. var loadedImages = [];
  14491. loadedImages._internalCount = 0;
  14492. for (var index = 0; index < 6; index++) {
  14493. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14494. }
  14495. };
  14496. ;
  14497. /** @hidden */
  14498. Engine.prototype._createTexture = function () {
  14499. var texture = this._gl.createTexture();
  14500. if (!texture) {
  14501. throw new Error("Unable to create texture");
  14502. }
  14503. return texture;
  14504. };
  14505. /**
  14506. * Usually called from BABYLON.Texture.ts.
  14507. * Passed information to create a WebGLTexture
  14508. * @param urlArg defines a value which contains one of the following:
  14509. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14510. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14511. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14512. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14513. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14514. * @param scene needed for loading to the correct scene
  14515. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14516. * @param onLoad optional callback to be called upon successful completion
  14517. * @param onError optional callback to be called upon failure
  14518. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14519. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14520. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14521. * @param forcedExtension defines the extension to use to pick the right loader
  14522. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14523. */
  14524. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14525. var _this = this;
  14526. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14527. if (onLoad === void 0) { onLoad = null; }
  14528. if (onError === void 0) { onError = null; }
  14529. if (buffer === void 0) { buffer = null; }
  14530. if (fallback === void 0) { fallback = null; }
  14531. if (format === void 0) { format = null; }
  14532. if (forcedExtension === void 0) { forcedExtension = null; }
  14533. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14534. var fromData = url.substr(0, 5) === "data:";
  14535. var fromBlob = url.substr(0, 5) === "blob:";
  14536. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14537. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14538. // establish the file extension, if possible
  14539. var lastDot = url.lastIndexOf('.');
  14540. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14541. var loader = null;
  14542. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14543. var availableLoader = _a[_i];
  14544. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14545. loader = availableLoader;
  14546. break;
  14547. }
  14548. }
  14549. if (loader) {
  14550. url = loader.transformUrl(url, this._textureFormatInUse);
  14551. }
  14552. if (scene) {
  14553. scene._addPendingData(texture);
  14554. }
  14555. texture.url = url;
  14556. texture.generateMipMaps = !noMipmap;
  14557. texture.samplingMode = samplingMode;
  14558. texture.invertY = invertY;
  14559. if (!this._doNotHandleContextLost) {
  14560. // Keep a link to the buffer only if we plan to handle context lost
  14561. texture._buffer = buffer;
  14562. }
  14563. var onLoadObserver = null;
  14564. if (onLoad && !fallback) {
  14565. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14566. }
  14567. if (!fallback)
  14568. this._internalTexturesCache.push(texture);
  14569. var onInternalError = function (message, exception) {
  14570. if (scene) {
  14571. scene._removePendingData(texture);
  14572. }
  14573. var customFallback = false;
  14574. if (loader) {
  14575. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14576. if (fallbackUrl) {
  14577. // Add Back
  14578. customFallback = true;
  14579. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14580. }
  14581. }
  14582. if (!customFallback) {
  14583. if (onLoadObserver) {
  14584. texture.onLoadedObservable.remove(onLoadObserver);
  14585. }
  14586. if (BABYLON.Tools.UseFallbackTexture) {
  14587. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14588. }
  14589. }
  14590. if (onError) {
  14591. onError(message || "Unknown error", exception);
  14592. }
  14593. };
  14594. // processing for non-image formats
  14595. if (loader) {
  14596. var callback = function (data) {
  14597. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14598. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14599. done();
  14600. return false;
  14601. }, samplingMode);
  14602. });
  14603. };
  14604. if (!buffer) {
  14605. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14606. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14607. });
  14608. }
  14609. else {
  14610. callback(buffer);
  14611. }
  14612. }
  14613. else {
  14614. var onload = function (img) {
  14615. if (fromBlob && !_this._doNotHandleContextLost) {
  14616. // We need to store the image if we need to rebuild the texture
  14617. // in case of a webgl context lost
  14618. texture._buffer = img;
  14619. }
  14620. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14621. var gl = _this._gl;
  14622. var isPot = (img.width === potWidth && img.height === potHeight);
  14623. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14624. if (isPot) {
  14625. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14626. return false;
  14627. }
  14628. var maxTextureSize = _this._caps.maxTextureSize;
  14629. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14630. _this._prepareWorkingCanvas();
  14631. if (!_this._workingCanvas || !_this._workingContext) {
  14632. return false;
  14633. }
  14634. _this._workingCanvas.width = potWidth;
  14635. _this._workingCanvas.height = potHeight;
  14636. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14637. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14638. texture.width = potWidth;
  14639. texture.height = potHeight;
  14640. return false;
  14641. }
  14642. else {
  14643. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14644. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14645. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14646. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14647. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14648. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14649. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14650. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14651. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14652. _this._releaseTexture(source_1);
  14653. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14654. continuationCallback();
  14655. });
  14656. }
  14657. return true;
  14658. }, samplingMode);
  14659. };
  14660. if (!fromData || isBase64) {
  14661. if (buffer instanceof HTMLImageElement) {
  14662. onload(buffer);
  14663. }
  14664. else {
  14665. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14666. }
  14667. }
  14668. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14669. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14670. }
  14671. else {
  14672. onload(buffer);
  14673. }
  14674. }
  14675. return texture;
  14676. };
  14677. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14678. var _this = this;
  14679. var rtt = this.createRenderTargetTexture({
  14680. width: destination.width,
  14681. height: destination.height,
  14682. }, {
  14683. generateMipMaps: false,
  14684. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14685. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14686. generateDepthBuffer: false,
  14687. generateStencilBuffer: false
  14688. });
  14689. if (!this._rescalePostProcess) {
  14690. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14691. }
  14692. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14693. _this._rescalePostProcess.onApply = function (effect) {
  14694. effect._bindTexture("textureSampler", source);
  14695. };
  14696. var hostingScene = scene;
  14697. if (!hostingScene) {
  14698. hostingScene = _this.scenes[_this.scenes.length - 1];
  14699. }
  14700. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14701. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14702. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14703. _this.unBindFramebuffer(rtt);
  14704. _this._releaseTexture(rtt);
  14705. if (onComplete) {
  14706. onComplete();
  14707. }
  14708. });
  14709. };
  14710. /**
  14711. * Update a raw texture
  14712. * @param texture defines the texture to update
  14713. * @param data defines the data to store in the texture
  14714. * @param format defines the format of the data
  14715. * @param invertY defines if data must be stored with Y axis inverted
  14716. * @param compression defines the compression used (null by default)
  14717. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14718. */
  14719. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14720. if (compression === void 0) { compression = null; }
  14721. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14722. if (!texture) {
  14723. return;
  14724. }
  14725. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14726. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14727. // babylon's internalFormat but gl's texImage2D format
  14728. var internalFormat = this._getInternalFormat(format);
  14729. var textureType = this._getWebGLTextureType(type);
  14730. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14731. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14732. if (!this._doNotHandleContextLost) {
  14733. texture._bufferView = data;
  14734. texture.format = format;
  14735. texture.type = type;
  14736. texture.invertY = invertY;
  14737. texture._compression = compression;
  14738. }
  14739. if (texture.width % 4 !== 0) {
  14740. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14741. }
  14742. if (compression && data) {
  14743. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14744. }
  14745. else {
  14746. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14747. }
  14748. if (texture.generateMipMaps) {
  14749. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14750. }
  14751. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14752. // this.resetTextureCache();
  14753. texture.isReady = true;
  14754. };
  14755. /**
  14756. * Creates a raw texture
  14757. * @param data defines the data to store in the texture
  14758. * @param width defines the width of the texture
  14759. * @param height defines the height of the texture
  14760. * @param format defines the format of the data
  14761. * @param generateMipMaps defines if the engine should generate the mip levels
  14762. * @param invertY defines if data must be stored with Y axis inverted
  14763. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14764. * @param compression defines the compression used (null by default)
  14765. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14766. * @returns the raw texture inside an InternalTexture
  14767. */
  14768. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14769. if (compression === void 0) { compression = null; }
  14770. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14771. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14772. texture.baseWidth = width;
  14773. texture.baseHeight = height;
  14774. texture.width = width;
  14775. texture.height = height;
  14776. texture.format = format;
  14777. texture.generateMipMaps = generateMipMaps;
  14778. texture.samplingMode = samplingMode;
  14779. texture.invertY = invertY;
  14780. texture._compression = compression;
  14781. texture.type = type;
  14782. if (!this._doNotHandleContextLost) {
  14783. texture._bufferView = data;
  14784. }
  14785. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14786. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14787. // Filters
  14788. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14789. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14790. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14791. if (generateMipMaps) {
  14792. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14793. }
  14794. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14795. this._internalTexturesCache.push(texture);
  14796. return texture;
  14797. };
  14798. /** @hidden */
  14799. Engine.prototype._unpackFlipY = function (value) {
  14800. if (this._unpackFlipYCached !== value) {
  14801. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14802. if (this.enableUnpackFlipYCached) {
  14803. this._unpackFlipYCached = value;
  14804. }
  14805. }
  14806. };
  14807. /** @hidden */
  14808. Engine.prototype._getUnpackAlignement = function () {
  14809. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14810. };
  14811. /**
  14812. * Creates a dynamic texture
  14813. * @param width defines the width of the texture
  14814. * @param height defines the height of the texture
  14815. * @param generateMipMaps defines if the engine should generate the mip levels
  14816. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14817. * @returns the dynamic texture inside an InternalTexture
  14818. */
  14819. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14820. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14821. texture.baseWidth = width;
  14822. texture.baseHeight = height;
  14823. if (generateMipMaps) {
  14824. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14825. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14826. }
  14827. // this.resetTextureCache();
  14828. texture.width = width;
  14829. texture.height = height;
  14830. texture.isReady = false;
  14831. texture.generateMipMaps = generateMipMaps;
  14832. texture.samplingMode = samplingMode;
  14833. this.updateTextureSamplingMode(samplingMode, texture);
  14834. this._internalTexturesCache.push(texture);
  14835. return texture;
  14836. };
  14837. /**
  14838. * Update the sampling mode of a given texture
  14839. * @param samplingMode defines the required sampling mode
  14840. * @param texture defines the texture to update
  14841. */
  14842. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14843. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14844. if (texture.isCube) {
  14845. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14846. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14847. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14848. }
  14849. else if (texture.is3D) {
  14850. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14851. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14852. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14853. }
  14854. else {
  14855. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14856. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14857. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14858. }
  14859. texture.samplingMode = samplingMode;
  14860. };
  14861. /**
  14862. * Update the content of a dynamic texture
  14863. * @param texture defines the texture to update
  14864. * @param canvas defines the canvas containing the source
  14865. * @param invertY defines if data must be stored with Y axis inverted
  14866. * @param premulAlpha defines if alpha is stored as premultiplied
  14867. * @param format defines the format of the data
  14868. */
  14869. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14870. if (premulAlpha === void 0) { premulAlpha = false; }
  14871. if (!texture) {
  14872. return;
  14873. }
  14874. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14875. this._unpackFlipY(invertY);
  14876. if (premulAlpha) {
  14877. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14878. }
  14879. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14880. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14881. if (texture.generateMipMaps) {
  14882. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14883. }
  14884. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14885. if (premulAlpha) {
  14886. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14887. }
  14888. texture.isReady = true;
  14889. };
  14890. /**
  14891. * Update a video texture
  14892. * @param texture defines the texture to update
  14893. * @param video defines the video element to use
  14894. * @param invertY defines if data must be stored with Y axis inverted
  14895. */
  14896. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14897. if (!texture || texture._isDisabled) {
  14898. return;
  14899. }
  14900. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14901. this._unpackFlipY(!invertY); // Video are upside down by default
  14902. try {
  14903. // Testing video texture support
  14904. if (this._videoTextureSupported === undefined) {
  14905. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14906. if (this._gl.getError() !== 0) {
  14907. this._videoTextureSupported = false;
  14908. }
  14909. else {
  14910. this._videoTextureSupported = true;
  14911. }
  14912. }
  14913. // Copy video through the current working canvas if video texture is not supported
  14914. if (!this._videoTextureSupported) {
  14915. if (!texture._workingCanvas) {
  14916. texture._workingCanvas = document.createElement("canvas");
  14917. var context = texture._workingCanvas.getContext("2d");
  14918. if (!context) {
  14919. throw new Error("Unable to get 2d context");
  14920. }
  14921. texture._workingContext = context;
  14922. texture._workingCanvas.width = texture.width;
  14923. texture._workingCanvas.height = texture.height;
  14924. }
  14925. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14926. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14927. }
  14928. else {
  14929. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14930. }
  14931. if (texture.generateMipMaps) {
  14932. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14933. }
  14934. if (!wasPreviouslyBound) {
  14935. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14936. }
  14937. // this.resetTextureCache();
  14938. texture.isReady = true;
  14939. }
  14940. catch (ex) {
  14941. // Something unexpected
  14942. // Let's disable the texture
  14943. texture._isDisabled = true;
  14944. }
  14945. };
  14946. /**
  14947. * Updates a depth texture Comparison Mode and Function.
  14948. * If the comparison Function is equal to 0, the mode will be set to none.
  14949. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14950. * @param texture The texture to set the comparison function for
  14951. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14952. */
  14953. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14954. if (this.webGLVersion === 1) {
  14955. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14956. return;
  14957. }
  14958. var gl = this._gl;
  14959. if (texture.isCube) {
  14960. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14961. if (comparisonFunction === 0) {
  14962. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14963. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14964. }
  14965. else {
  14966. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14967. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14968. }
  14969. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14970. }
  14971. else {
  14972. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14973. if (comparisonFunction === 0) {
  14974. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14975. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14976. }
  14977. else {
  14978. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14979. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14980. }
  14981. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14982. }
  14983. texture._comparisonFunction = comparisonFunction;
  14984. };
  14985. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14986. var width = size.width || size;
  14987. var height = size.height || size;
  14988. internalTexture.baseWidth = width;
  14989. internalTexture.baseHeight = height;
  14990. internalTexture.width = width;
  14991. internalTexture.height = height;
  14992. internalTexture.isReady = true;
  14993. internalTexture.samples = 1;
  14994. internalTexture.generateMipMaps = false;
  14995. internalTexture._generateDepthBuffer = true;
  14996. internalTexture._generateStencilBuffer = generateStencil;
  14997. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14998. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14999. internalTexture._comparisonFunction = comparisonFunction;
  15000. var gl = this._gl;
  15001. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15002. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15003. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15004. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15005. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15006. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15007. if (comparisonFunction === 0) {
  15008. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15009. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15010. }
  15011. else {
  15012. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15013. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15014. }
  15015. };
  15016. /**
  15017. * Creates a depth stencil texture.
  15018. * This is only available in WebGL 2 or with the depth texture extension available.
  15019. * @param size The size of face edge in the texture.
  15020. * @param options The options defining the texture.
  15021. * @returns The texture
  15022. */
  15023. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15024. if (options.isCube) {
  15025. var width = size.width || size;
  15026. return this._createDepthStencilCubeTexture(width, options);
  15027. }
  15028. else {
  15029. return this._createDepthStencilTexture(size, options);
  15030. }
  15031. };
  15032. /**
  15033. * Creates a depth stencil texture.
  15034. * This is only available in WebGL 2 or with the depth texture extension available.
  15035. * @param size The size of face edge in the texture.
  15036. * @param options The options defining the texture.
  15037. * @returns The texture
  15038. */
  15039. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15040. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15041. if (!this._caps.depthTextureExtension) {
  15042. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15043. return internalTexture;
  15044. }
  15045. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15046. var gl = this._gl;
  15047. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15048. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15049. if (this.webGLVersion > 1) {
  15050. if (internalOptions.generateStencil) {
  15051. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15052. }
  15053. else {
  15054. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15055. }
  15056. }
  15057. else {
  15058. if (internalOptions.generateStencil) {
  15059. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15060. }
  15061. else {
  15062. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15063. }
  15064. }
  15065. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15066. return internalTexture;
  15067. };
  15068. /**
  15069. * Creates a depth stencil cube texture.
  15070. * This is only available in WebGL 2.
  15071. * @param size The size of face edge in the cube texture.
  15072. * @param options The options defining the cube texture.
  15073. * @returns The cube texture
  15074. */
  15075. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15076. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15077. internalTexture.isCube = true;
  15078. if (this.webGLVersion === 1) {
  15079. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15080. return internalTexture;
  15081. }
  15082. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15083. var gl = this._gl;
  15084. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15085. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15086. // Create the depth/stencil buffer
  15087. for (var face = 0; face < 6; face++) {
  15088. if (internalOptions.generateStencil) {
  15089. 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);
  15090. }
  15091. else {
  15092. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15093. }
  15094. }
  15095. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15096. return internalTexture;
  15097. };
  15098. /**
  15099. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15100. * @param renderTarget The render target to set the frame buffer for
  15101. */
  15102. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15103. // Create the framebuffer
  15104. var internalTexture = renderTarget.getInternalTexture();
  15105. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15106. return;
  15107. }
  15108. var gl = this._gl;
  15109. var depthStencilTexture = renderTarget.depthStencilTexture;
  15110. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15111. if (depthStencilTexture.isCube) {
  15112. if (depthStencilTexture._generateStencilBuffer) {
  15113. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15114. }
  15115. else {
  15116. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15117. }
  15118. }
  15119. else {
  15120. if (depthStencilTexture._generateStencilBuffer) {
  15121. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15122. }
  15123. else {
  15124. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15125. }
  15126. }
  15127. this.bindUnboundFramebuffer(null);
  15128. };
  15129. /**
  15130. * Creates a new render target texture
  15131. * @param size defines the size of the texture
  15132. * @param options defines the options used to create the texture
  15133. * @returns a new render target texture stored in an InternalTexture
  15134. */
  15135. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15136. var fullOptions = new RenderTargetCreationOptions();
  15137. if (options !== undefined && typeof options === "object") {
  15138. fullOptions.generateMipMaps = options.generateMipMaps;
  15139. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15140. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15141. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15142. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15143. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15144. }
  15145. else {
  15146. fullOptions.generateMipMaps = options;
  15147. fullOptions.generateDepthBuffer = true;
  15148. fullOptions.generateStencilBuffer = false;
  15149. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15150. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15151. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15152. }
  15153. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15154. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15155. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15156. }
  15157. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15158. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15159. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15160. }
  15161. var gl = this._gl;
  15162. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15163. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15164. var width = size.width || size;
  15165. var height = size.height || size;
  15166. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15167. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15168. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15169. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15170. }
  15171. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15172. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15173. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15175. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15176. // Create the framebuffer
  15177. var currentFrameBuffer = this._currentFramebuffer;
  15178. var framebuffer = gl.createFramebuffer();
  15179. this.bindUnboundFramebuffer(framebuffer);
  15180. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15181. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15182. if (fullOptions.generateMipMaps) {
  15183. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15184. }
  15185. // Unbind
  15186. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15187. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15188. this.bindUnboundFramebuffer(currentFrameBuffer);
  15189. texture._framebuffer = framebuffer;
  15190. texture.baseWidth = width;
  15191. texture.baseHeight = height;
  15192. texture.width = width;
  15193. texture.height = height;
  15194. texture.isReady = true;
  15195. texture.samples = 1;
  15196. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15197. texture.samplingMode = fullOptions.samplingMode;
  15198. texture.type = fullOptions.type;
  15199. texture.format = fullOptions.format;
  15200. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15201. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15202. // this.resetTextureCache();
  15203. this._internalTexturesCache.push(texture);
  15204. return texture;
  15205. };
  15206. /**
  15207. * Create a multi render target texture
  15208. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15209. * @param size defines the size of the texture
  15210. * @param options defines the creation options
  15211. * @returns the cube texture as an InternalTexture
  15212. */
  15213. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15214. var generateMipMaps = false;
  15215. var generateDepthBuffer = true;
  15216. var generateStencilBuffer = false;
  15217. var generateDepthTexture = false;
  15218. var textureCount = 1;
  15219. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15220. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15221. var types = new Array();
  15222. var samplingModes = new Array();
  15223. if (options !== undefined) {
  15224. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15225. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15226. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15227. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15228. textureCount = options.textureCount || 1;
  15229. if (options.types) {
  15230. types = options.types;
  15231. }
  15232. if (options.samplingModes) {
  15233. samplingModes = options.samplingModes;
  15234. }
  15235. }
  15236. var gl = this._gl;
  15237. // Create the framebuffer
  15238. var framebuffer = gl.createFramebuffer();
  15239. this.bindUnboundFramebuffer(framebuffer);
  15240. var width = size.width || size;
  15241. var height = size.height || size;
  15242. var textures = [];
  15243. var attachments = [];
  15244. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15245. for (var i = 0; i < textureCount; i++) {
  15246. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15247. var type = types[i] || defaultType;
  15248. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15249. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15250. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15251. }
  15252. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15253. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15254. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15255. }
  15256. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15257. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15258. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15259. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15260. }
  15261. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15262. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15263. textures.push(texture);
  15264. attachments.push(attachment);
  15265. gl.activeTexture(gl["TEXTURE" + i]);
  15266. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15267. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15268. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15270. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15271. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15272. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15273. if (generateMipMaps) {
  15274. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15275. }
  15276. // Unbind
  15277. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15278. texture._framebuffer = framebuffer;
  15279. texture._depthStencilBuffer = depthStencilBuffer;
  15280. texture.baseWidth = width;
  15281. texture.baseHeight = height;
  15282. texture.width = width;
  15283. texture.height = height;
  15284. texture.isReady = true;
  15285. texture.samples = 1;
  15286. texture.generateMipMaps = generateMipMaps;
  15287. texture.samplingMode = samplingMode;
  15288. texture.type = type;
  15289. texture._generateDepthBuffer = generateDepthBuffer;
  15290. texture._generateStencilBuffer = generateStencilBuffer;
  15291. texture._attachments = attachments;
  15292. this._internalTexturesCache.push(texture);
  15293. }
  15294. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15295. // Depth texture
  15296. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15297. gl.activeTexture(gl.TEXTURE0);
  15298. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15299. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15300. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15301. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15302. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15303. 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);
  15304. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15305. depthTexture._framebuffer = framebuffer;
  15306. depthTexture.baseWidth = width;
  15307. depthTexture.baseHeight = height;
  15308. depthTexture.width = width;
  15309. depthTexture.height = height;
  15310. depthTexture.isReady = true;
  15311. depthTexture.samples = 1;
  15312. depthTexture.generateMipMaps = generateMipMaps;
  15313. depthTexture.samplingMode = gl.NEAREST;
  15314. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15315. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15316. textures.push(depthTexture);
  15317. this._internalTexturesCache.push(depthTexture);
  15318. }
  15319. gl.drawBuffers(attachments);
  15320. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15321. this.bindUnboundFramebuffer(null);
  15322. this.resetTextureCache();
  15323. return textures;
  15324. };
  15325. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15326. if (samples === void 0) { samples = 1; }
  15327. var depthStencilBuffer = null;
  15328. var gl = this._gl;
  15329. // Create the depth/stencil buffer
  15330. if (generateStencilBuffer) {
  15331. depthStencilBuffer = gl.createRenderbuffer();
  15332. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15333. if (samples > 1) {
  15334. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15335. }
  15336. else {
  15337. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15338. }
  15339. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15340. }
  15341. else if (generateDepthBuffer) {
  15342. depthStencilBuffer = gl.createRenderbuffer();
  15343. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15344. if (samples > 1) {
  15345. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15346. }
  15347. else {
  15348. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15349. }
  15350. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15351. }
  15352. return depthStencilBuffer;
  15353. };
  15354. /**
  15355. * Updates the sample count of a render target texture
  15356. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15357. * @param texture defines the texture to update
  15358. * @param samples defines the sample count to set
  15359. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15360. */
  15361. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15362. if (this.webGLVersion < 2 || !texture) {
  15363. return 1;
  15364. }
  15365. if (texture.samples === samples) {
  15366. return samples;
  15367. }
  15368. var gl = this._gl;
  15369. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15370. // Dispose previous render buffers
  15371. if (texture._depthStencilBuffer) {
  15372. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15373. texture._depthStencilBuffer = null;
  15374. }
  15375. if (texture._MSAAFramebuffer) {
  15376. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15377. texture._MSAAFramebuffer = null;
  15378. }
  15379. if (texture._MSAARenderBuffer) {
  15380. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15381. texture._MSAARenderBuffer = null;
  15382. }
  15383. if (samples > 1) {
  15384. var framebuffer = gl.createFramebuffer();
  15385. if (!framebuffer) {
  15386. throw new Error("Unable to create multi sampled framebuffer");
  15387. }
  15388. texture._MSAAFramebuffer = framebuffer;
  15389. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15390. var colorRenderbuffer = gl.createRenderbuffer();
  15391. if (!colorRenderbuffer) {
  15392. throw new Error("Unable to create multi sampled framebuffer");
  15393. }
  15394. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15395. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15396. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15397. texture._MSAARenderBuffer = colorRenderbuffer;
  15398. }
  15399. else {
  15400. this.bindUnboundFramebuffer(texture._framebuffer);
  15401. }
  15402. texture.samples = samples;
  15403. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15404. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15405. this.bindUnboundFramebuffer(null);
  15406. return samples;
  15407. };
  15408. /**
  15409. * Update the sample count for a given multiple render target texture
  15410. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15411. * @param textures defines the textures to update
  15412. * @param samples defines the sample count to set
  15413. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15414. */
  15415. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15416. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15417. return 1;
  15418. }
  15419. if (textures[0].samples === samples) {
  15420. return samples;
  15421. }
  15422. var gl = this._gl;
  15423. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15424. // Dispose previous render buffers
  15425. if (textures[0]._depthStencilBuffer) {
  15426. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15427. textures[0]._depthStencilBuffer = null;
  15428. }
  15429. if (textures[0]._MSAAFramebuffer) {
  15430. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15431. textures[0]._MSAAFramebuffer = null;
  15432. }
  15433. for (var i = 0; i < textures.length; i++) {
  15434. if (textures[i]._MSAARenderBuffer) {
  15435. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15436. textures[i]._MSAARenderBuffer = null;
  15437. }
  15438. }
  15439. if (samples > 1) {
  15440. var framebuffer = gl.createFramebuffer();
  15441. if (!framebuffer) {
  15442. throw new Error("Unable to create multi sampled framebuffer");
  15443. }
  15444. this.bindUnboundFramebuffer(framebuffer);
  15445. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15446. var attachments = [];
  15447. for (var i = 0; i < textures.length; i++) {
  15448. var texture = textures[i];
  15449. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15450. var colorRenderbuffer = gl.createRenderbuffer();
  15451. if (!colorRenderbuffer) {
  15452. throw new Error("Unable to create multi sampled framebuffer");
  15453. }
  15454. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15455. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15456. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15457. texture._MSAAFramebuffer = framebuffer;
  15458. texture._MSAARenderBuffer = colorRenderbuffer;
  15459. texture.samples = samples;
  15460. texture._depthStencilBuffer = depthStencilBuffer;
  15461. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15462. attachments.push(attachment);
  15463. }
  15464. gl.drawBuffers(attachments);
  15465. }
  15466. else {
  15467. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15468. }
  15469. this.bindUnboundFramebuffer(null);
  15470. return samples;
  15471. };
  15472. /** @hidden */
  15473. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15474. if (faceIndex === void 0) { faceIndex = 0; }
  15475. if (lod === void 0) { lod = 0; }
  15476. var gl = this._gl;
  15477. var target = gl.TEXTURE_2D;
  15478. if (texture.isCube) {
  15479. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15480. }
  15481. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15482. };
  15483. /** @hidden */
  15484. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15485. if (faceIndex === void 0) { faceIndex = 0; }
  15486. if (lod === void 0) { lod = 0; }
  15487. var gl = this._gl;
  15488. var textureType = this._getWebGLTextureType(texture.type);
  15489. var format = this._getInternalFormat(texture.format);
  15490. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15491. this._unpackFlipY(texture.invertY);
  15492. var target = gl.TEXTURE_2D;
  15493. if (texture.isCube) {
  15494. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15495. }
  15496. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15497. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15498. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15499. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15500. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15501. };
  15502. /** @hidden */
  15503. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15504. if (faceIndex === void 0) { faceIndex = 0; }
  15505. if (lod === void 0) { lod = 0; }
  15506. var gl = this._gl;
  15507. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15508. this._bindTextureDirectly(bindTarget, texture, true);
  15509. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15510. this._bindTextureDirectly(bindTarget, null, true);
  15511. };
  15512. /** @hidden */
  15513. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15514. if (faceIndex === void 0) { faceIndex = 0; }
  15515. if (lod === void 0) { lod = 0; }
  15516. var gl = this._gl;
  15517. var textureType = this._getWebGLTextureType(texture.type);
  15518. var format = this._getInternalFormat(texture.format);
  15519. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15520. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15521. this._bindTextureDirectly(bindTarget, texture, true);
  15522. this._unpackFlipY(texture.invertY);
  15523. var target = gl.TEXTURE_2D;
  15524. if (texture.isCube) {
  15525. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15526. }
  15527. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15528. this._bindTextureDirectly(bindTarget, null, true);
  15529. };
  15530. /**
  15531. * Creates a new render target cube texture
  15532. * @param size defines the size of the texture
  15533. * @param options defines the options used to create the texture
  15534. * @returns a new render target cube texture stored in an InternalTexture
  15535. */
  15536. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15537. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15538. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15539. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15540. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15541. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15542. }
  15543. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15544. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15545. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15546. }
  15547. var gl = this._gl;
  15548. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15549. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15550. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15551. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15552. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15553. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15554. }
  15555. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15556. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15557. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15558. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15559. for (var face = 0; face < 6; face++) {
  15560. 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);
  15561. }
  15562. // Create the framebuffer
  15563. var framebuffer = gl.createFramebuffer();
  15564. this.bindUnboundFramebuffer(framebuffer);
  15565. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15566. // MipMaps
  15567. if (fullOptions.generateMipMaps) {
  15568. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15569. }
  15570. // Unbind
  15571. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15572. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15573. this.bindUnboundFramebuffer(null);
  15574. texture._framebuffer = framebuffer;
  15575. texture.width = size;
  15576. texture.height = size;
  15577. texture.isReady = true;
  15578. texture.isCube = true;
  15579. texture.samples = 1;
  15580. texture.generateMipMaps = fullOptions.generateMipMaps;
  15581. texture.samplingMode = fullOptions.samplingMode;
  15582. texture.type = fullOptions.type;
  15583. texture.format = fullOptions.format;
  15584. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15585. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15586. this._internalTexturesCache.push(texture);
  15587. return texture;
  15588. };
  15589. /**
  15590. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15591. * @param rootUrl defines the url where the file to load is located
  15592. * @param scene defines the current scene
  15593. * @param lodScale defines scale to apply to the mip map selection
  15594. * @param lodOffset defines offset to apply to the mip map selection
  15595. * @param onLoad defines an optional callback raised when the texture is loaded
  15596. * @param onError defines an optional callback raised if there is an issue to load the texture
  15597. * @param format defines the format of the data
  15598. * @param forcedExtension defines the extension to use to pick the right loader
  15599. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15600. * @returns the cube texture as an InternalTexture
  15601. */
  15602. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15603. var _this = this;
  15604. if (onLoad === void 0) { onLoad = null; }
  15605. if (onError === void 0) { onError = null; }
  15606. if (forcedExtension === void 0) { forcedExtension = null; }
  15607. if (createPolynomials === void 0) { createPolynomials = true; }
  15608. var callback = function (loadData) {
  15609. if (!loadData) {
  15610. if (onLoad) {
  15611. onLoad(null);
  15612. }
  15613. return;
  15614. }
  15615. var texture = loadData.texture;
  15616. if (!createPolynomials) {
  15617. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15618. }
  15619. else if (loadData.info.sphericalPolynomial) {
  15620. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15621. }
  15622. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15623. if (_this._caps.textureLOD) {
  15624. // Do not add extra process if texture lod is supported.
  15625. if (onLoad) {
  15626. onLoad(texture);
  15627. }
  15628. return;
  15629. }
  15630. var mipSlices = 3;
  15631. var gl = _this._gl;
  15632. var width = loadData.width;
  15633. if (!width) {
  15634. return;
  15635. }
  15636. var textures = [];
  15637. for (var i = 0; i < mipSlices; i++) {
  15638. //compute LOD from even spacing in smoothness (matching shader calculation)
  15639. var smoothness = i / (mipSlices - 1);
  15640. var roughness = 1 - smoothness;
  15641. var minLODIndex = lodOffset; // roughness = 0
  15642. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15643. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15644. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15645. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15646. glTextureFromLod.type = texture.type;
  15647. glTextureFromLod.format = texture.format;
  15648. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15649. glTextureFromLod.height = glTextureFromLod.width;
  15650. glTextureFromLod.isCube = true;
  15651. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15652. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15653. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15654. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15655. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15656. if (loadData.isDDS) {
  15657. var info = loadData.info;
  15658. var data = loadData.data;
  15659. _this._unpackFlipY(info.isCompressed);
  15660. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15661. }
  15662. else {
  15663. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15664. }
  15665. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15666. // Wrap in a base texture for easy binding.
  15667. var lodTexture = new BABYLON.BaseTexture(scene);
  15668. lodTexture.isCube = true;
  15669. lodTexture._texture = glTextureFromLod;
  15670. glTextureFromLod.isReady = true;
  15671. textures.push(lodTexture);
  15672. }
  15673. texture._lodTextureHigh = textures[2];
  15674. texture._lodTextureMid = textures[1];
  15675. texture._lodTextureLow = textures[0];
  15676. if (onLoad) {
  15677. onLoad(texture);
  15678. }
  15679. };
  15680. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15681. };
  15682. /**
  15683. * Creates a cube texture
  15684. * @param rootUrl defines the url where the files to load is located
  15685. * @param scene defines the current scene
  15686. * @param files defines the list of files to load (1 per face)
  15687. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15688. * @param onLoad defines an optional callback raised when the texture is loaded
  15689. * @param onError defines an optional callback raised if there is an issue to load the texture
  15690. * @param format defines the format of the data
  15691. * @param forcedExtension defines the extension to use to pick the right loader
  15692. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15693. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15694. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15695. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15696. * @returns the cube texture as an InternalTexture
  15697. */
  15698. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15699. var _this = this;
  15700. if (onLoad === void 0) { onLoad = null; }
  15701. if (onError === void 0) { onError = null; }
  15702. if (forcedExtension === void 0) { forcedExtension = null; }
  15703. if (createPolynomials === void 0) { createPolynomials = false; }
  15704. if (lodScale === void 0) { lodScale = 0; }
  15705. if (lodOffset === void 0) { lodOffset = 0; }
  15706. if (fallback === void 0) { fallback = null; }
  15707. var gl = this._gl;
  15708. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15709. texture.isCube = true;
  15710. texture.url = rootUrl;
  15711. texture.generateMipMaps = !noMipmap;
  15712. texture._lodGenerationScale = lodScale;
  15713. texture._lodGenerationOffset = lodOffset;
  15714. if (!this._doNotHandleContextLost) {
  15715. texture._extension = forcedExtension;
  15716. texture._files = files;
  15717. }
  15718. var lastDot = rootUrl.lastIndexOf('.');
  15719. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15720. var loader = null;
  15721. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15722. var availableLoader = _a[_i];
  15723. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15724. loader = availableLoader;
  15725. break;
  15726. }
  15727. }
  15728. var onInternalError = function (request, exception) {
  15729. if (loader) {
  15730. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15731. if (fallbackUrl) {
  15732. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15733. }
  15734. }
  15735. if (onError && request) {
  15736. onError(request.status + " " + request.statusText, exception);
  15737. }
  15738. };
  15739. if (loader) {
  15740. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15741. var onloaddata = function (data) {
  15742. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15743. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15744. };
  15745. if (files && files.length === 6) {
  15746. if (loader.supportCascades) {
  15747. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15748. }
  15749. else if (onError) {
  15750. onError("Textures type does not support cascades.");
  15751. }
  15752. }
  15753. else {
  15754. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15755. }
  15756. }
  15757. else {
  15758. if (!files) {
  15759. throw new Error("Cannot load cubemap because files were not defined");
  15760. }
  15761. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15762. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15763. var height = width;
  15764. _this._prepareWorkingCanvas();
  15765. if (!_this._workingCanvas || !_this._workingContext) {
  15766. return;
  15767. }
  15768. _this._workingCanvas.width = width;
  15769. _this._workingCanvas.height = height;
  15770. var faces = [
  15771. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15772. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15773. ];
  15774. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15775. _this._unpackFlipY(false);
  15776. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15777. for (var index = 0; index < faces.length; index++) {
  15778. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15779. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15780. }
  15781. if (!noMipmap) {
  15782. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15783. }
  15784. _this._setCubeMapTextureParams(!noMipmap);
  15785. texture.width = width;
  15786. texture.height = height;
  15787. texture.isReady = true;
  15788. if (format) {
  15789. texture.format = format;
  15790. }
  15791. texture.onLoadedObservable.notifyObservers(texture);
  15792. texture.onLoadedObservable.clear();
  15793. if (onLoad) {
  15794. onLoad();
  15795. }
  15796. }, files, onError);
  15797. }
  15798. this._internalTexturesCache.push(texture);
  15799. return texture;
  15800. };
  15801. /**
  15802. * @hidden
  15803. */
  15804. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15805. var gl = this._gl;
  15806. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15807. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15808. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15809. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15810. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15811. // this.resetTextureCache();
  15812. };
  15813. /**
  15814. * Update a raw cube texture
  15815. * @param texture defines the texture to udpdate
  15816. * @param data defines the data to store
  15817. * @param format defines the data format
  15818. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15819. * @param invertY defines if data must be stored with Y axis inverted
  15820. * @param compression defines the compression used (null by default)
  15821. * @param level defines which level of the texture to update
  15822. */
  15823. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15824. if (compression === void 0) { compression = null; }
  15825. if (level === void 0) { level = 0; }
  15826. texture._bufferViewArray = data;
  15827. texture.format = format;
  15828. texture.type = type;
  15829. texture.invertY = invertY;
  15830. texture._compression = compression;
  15831. var gl = this._gl;
  15832. var textureType = this._getWebGLTextureType(type);
  15833. var internalFormat = this._getInternalFormat(format);
  15834. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15835. var needConversion = false;
  15836. if (internalFormat === gl.RGB) {
  15837. internalFormat = gl.RGBA;
  15838. needConversion = true;
  15839. }
  15840. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15841. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15842. if (texture.width % 4 !== 0) {
  15843. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15844. }
  15845. // Data are known to be in +X +Y +Z -X -Y -Z
  15846. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15847. var faceData = data[faceIndex];
  15848. if (compression) {
  15849. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15850. }
  15851. else {
  15852. if (needConversion) {
  15853. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15854. }
  15855. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15856. }
  15857. }
  15858. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15859. if (isPot && texture.generateMipMaps && level === 0) {
  15860. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15861. }
  15862. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15863. // this.resetTextureCache();
  15864. texture.isReady = true;
  15865. };
  15866. /**
  15867. * Creates a new raw cube texture
  15868. * @param data defines the array of data to use to create each face
  15869. * @param size defines the size of the textures
  15870. * @param format defines the format of the data
  15871. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15872. * @param generateMipMaps defines if the engine should generate the mip levels
  15873. * @param invertY defines if data must be stored with Y axis inverted
  15874. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15875. * @param compression defines the compression used (null by default)
  15876. * @returns the cube texture as an InternalTexture
  15877. */
  15878. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15879. if (compression === void 0) { compression = null; }
  15880. var gl = this._gl;
  15881. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15882. texture.isCube = true;
  15883. texture.format = format;
  15884. texture.type = type;
  15885. if (!this._doNotHandleContextLost) {
  15886. texture._bufferViewArray = data;
  15887. }
  15888. var textureType = this._getWebGLTextureType(type);
  15889. var internalFormat = this._getInternalFormat(format);
  15890. if (internalFormat === gl.RGB) {
  15891. internalFormat = gl.RGBA;
  15892. }
  15893. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15894. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15895. generateMipMaps = false;
  15896. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15897. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15898. }
  15899. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15900. generateMipMaps = false;
  15901. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15902. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15903. }
  15904. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15905. generateMipMaps = false;
  15906. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15907. }
  15908. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15909. generateMipMaps = false;
  15910. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15911. }
  15912. var width = size;
  15913. var height = width;
  15914. texture.width = width;
  15915. texture.height = height;
  15916. // Double check on POT to generate Mips.
  15917. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15918. if (!isPot) {
  15919. generateMipMaps = false;
  15920. }
  15921. // Upload data if needed. The texture won't be ready until then.
  15922. if (data) {
  15923. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15924. }
  15925. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15926. // Filters
  15927. if (data && generateMipMaps) {
  15928. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15929. }
  15930. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15931. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15932. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15933. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15934. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15935. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15936. texture.generateMipMaps = generateMipMaps;
  15937. return texture;
  15938. };
  15939. /**
  15940. * Creates a new raw cube texture from a specified url
  15941. * @param url defines the url where the data is located
  15942. * @param scene defines the current scene
  15943. * @param size defines the size of the textures
  15944. * @param format defines the format of the data
  15945. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15946. * @param noMipmap defines if the engine should avoid generating the mip levels
  15947. * @param callback defines a callback used to extract texture data from loaded data
  15948. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15949. * @param onLoad defines a callback called when texture is loaded
  15950. * @param onError defines a callback called if there is an error
  15951. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15952. * @param invertY defines if data must be stored with Y axis inverted
  15953. * @returns the cube texture as an InternalTexture
  15954. */
  15955. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15956. var _this = this;
  15957. if (onLoad === void 0) { onLoad = null; }
  15958. if (onError === void 0) { onError = null; }
  15959. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15960. if (invertY === void 0) { invertY = false; }
  15961. var gl = this._gl;
  15962. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15963. scene._addPendingData(texture);
  15964. texture.url = url;
  15965. this._internalTexturesCache.push(texture);
  15966. var onerror = function (request, exception) {
  15967. scene._removePendingData(texture);
  15968. if (onError && request) {
  15969. onError(request.status + " " + request.statusText, exception);
  15970. }
  15971. };
  15972. var internalCallback = function (data) {
  15973. var width = texture.width;
  15974. var faceDataArrays = callback(data);
  15975. if (!faceDataArrays) {
  15976. return;
  15977. }
  15978. if (mipmapGenerator) {
  15979. var textureType = _this._getWebGLTextureType(type);
  15980. var internalFormat = _this._getInternalFormat(format);
  15981. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15982. var needConversion = false;
  15983. if (internalFormat === gl.RGB) {
  15984. internalFormat = gl.RGBA;
  15985. needConversion = true;
  15986. }
  15987. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15988. _this._unpackFlipY(false);
  15989. var mipData = mipmapGenerator(faceDataArrays);
  15990. for (var level = 0; level < mipData.length; level++) {
  15991. var mipSize = width >> level;
  15992. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15993. var mipFaceData = mipData[level][faceIndex];
  15994. if (needConversion) {
  15995. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15996. }
  15997. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15998. }
  15999. }
  16000. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16001. }
  16002. else {
  16003. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16004. }
  16005. texture.isReady = true;
  16006. // this.resetTextureCache();
  16007. scene._removePendingData(texture);
  16008. if (onLoad) {
  16009. onLoad();
  16010. }
  16011. };
  16012. this._loadFile(url, function (data) {
  16013. internalCallback(data);
  16014. }, undefined, scene.database, true, onerror);
  16015. return texture;
  16016. };
  16017. ;
  16018. /**
  16019. * Update a raw 3D texture
  16020. * @param texture defines the texture to update
  16021. * @param data defines the data to store
  16022. * @param format defines the data format
  16023. * @param invertY defines if data must be stored with Y axis inverted
  16024. * @param compression defines the used compression (can be null)
  16025. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16026. */
  16027. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16028. if (compression === void 0) { compression = null; }
  16029. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16030. var internalType = this._getWebGLTextureType(textureType);
  16031. var internalFormat = this._getInternalFormat(format);
  16032. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16033. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16034. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16035. if (!this._doNotHandleContextLost) {
  16036. texture._bufferView = data;
  16037. texture.format = format;
  16038. texture.invertY = invertY;
  16039. texture._compression = compression;
  16040. }
  16041. if (texture.width % 4 !== 0) {
  16042. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16043. }
  16044. if (compression && data) {
  16045. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16046. }
  16047. else {
  16048. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16049. }
  16050. if (texture.generateMipMaps) {
  16051. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16052. }
  16053. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16054. // this.resetTextureCache();
  16055. texture.isReady = true;
  16056. };
  16057. /**
  16058. * Creates a new raw 3D texture
  16059. * @param data defines the data used to create the texture
  16060. * @param width defines the width of the texture
  16061. * @param height defines the height of the texture
  16062. * @param depth defines the depth of the texture
  16063. * @param format defines the format of the texture
  16064. * @param generateMipMaps defines if the engine must generate mip levels
  16065. * @param invertY defines if data must be stored with Y axis inverted
  16066. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16067. * @param compression defines the compressed used (can be null)
  16068. * @param textureType defines the compressed used (can be null)
  16069. * @returns a new raw 3D texture (stored in an InternalTexture)
  16070. */
  16071. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16072. if (compression === void 0) { compression = null; }
  16073. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16074. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16075. texture.baseWidth = width;
  16076. texture.baseHeight = height;
  16077. texture.baseDepth = depth;
  16078. texture.width = width;
  16079. texture.height = height;
  16080. texture.depth = depth;
  16081. texture.format = format;
  16082. texture.type = textureType;
  16083. texture.generateMipMaps = generateMipMaps;
  16084. texture.samplingMode = samplingMode;
  16085. texture.is3D = true;
  16086. if (!this._doNotHandleContextLost) {
  16087. texture._bufferView = data;
  16088. }
  16089. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16090. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16091. // Filters
  16092. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16093. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16094. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16095. if (generateMipMaps) {
  16096. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16097. }
  16098. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16099. this._internalTexturesCache.push(texture);
  16100. return texture;
  16101. };
  16102. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16103. var gl = this._gl;
  16104. if (!gl) {
  16105. return;
  16106. }
  16107. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16108. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16109. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16110. if (!noMipmap && !isCompressed) {
  16111. gl.generateMipmap(gl.TEXTURE_2D);
  16112. }
  16113. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16114. // this.resetTextureCache();
  16115. if (scene) {
  16116. scene._removePendingData(texture);
  16117. }
  16118. texture.onLoadedObservable.notifyObservers(texture);
  16119. texture.onLoadedObservable.clear();
  16120. };
  16121. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16122. var _this = this;
  16123. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16124. var maxTextureSize = this.getCaps().maxTextureSize;
  16125. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16126. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16127. var gl = this._gl;
  16128. if (!gl) {
  16129. return;
  16130. }
  16131. if (!texture._webGLTexture) {
  16132. // this.resetTextureCache();
  16133. if (scene) {
  16134. scene._removePendingData(texture);
  16135. }
  16136. return;
  16137. }
  16138. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16139. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16140. texture.baseWidth = width;
  16141. texture.baseHeight = height;
  16142. texture.width = potWidth;
  16143. texture.height = potHeight;
  16144. texture.isReady = true;
  16145. if (processFunction(potWidth, potHeight, function () {
  16146. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16147. })) {
  16148. // Returning as texture needs extra async steps
  16149. return;
  16150. }
  16151. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16152. };
  16153. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16154. // Create new RGBA data container.
  16155. var rgbaData;
  16156. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16157. rgbaData = new Float32Array(width * height * 4);
  16158. }
  16159. else {
  16160. rgbaData = new Uint32Array(width * height * 4);
  16161. }
  16162. // Convert each pixel.
  16163. for (var x = 0; x < width; x++) {
  16164. for (var y = 0; y < height; y++) {
  16165. var index = (y * width + x) * 3;
  16166. var newIndex = (y * width + x) * 4;
  16167. // Map Old Value to new value.
  16168. rgbaData[newIndex + 0] = rgbData[index + 0];
  16169. rgbaData[newIndex + 1] = rgbData[index + 1];
  16170. rgbaData[newIndex + 2] = rgbData[index + 2];
  16171. // Add fully opaque alpha channel.
  16172. rgbaData[newIndex + 3] = 1;
  16173. }
  16174. }
  16175. return rgbaData;
  16176. };
  16177. /** @hidden */
  16178. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16179. var gl = this._gl;
  16180. if (texture._framebuffer) {
  16181. gl.deleteFramebuffer(texture._framebuffer);
  16182. texture._framebuffer = null;
  16183. }
  16184. if (texture._depthStencilBuffer) {
  16185. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16186. texture._depthStencilBuffer = null;
  16187. }
  16188. if (texture._MSAAFramebuffer) {
  16189. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16190. texture._MSAAFramebuffer = null;
  16191. }
  16192. if (texture._MSAARenderBuffer) {
  16193. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16194. texture._MSAARenderBuffer = null;
  16195. }
  16196. };
  16197. /** @hidden */
  16198. Engine.prototype._releaseTexture = function (texture) {
  16199. var gl = this._gl;
  16200. this._releaseFramebufferObjects(texture);
  16201. gl.deleteTexture(texture._webGLTexture);
  16202. // Unbind channels
  16203. this.unbindAllTextures();
  16204. var index = this._internalTexturesCache.indexOf(texture);
  16205. if (index !== -1) {
  16206. this._internalTexturesCache.splice(index, 1);
  16207. }
  16208. // Integrated fixed lod samplers.
  16209. if (texture._lodTextureHigh) {
  16210. texture._lodTextureHigh.dispose();
  16211. }
  16212. if (texture._lodTextureMid) {
  16213. texture._lodTextureMid.dispose();
  16214. }
  16215. if (texture._lodTextureLow) {
  16216. texture._lodTextureLow.dispose();
  16217. }
  16218. // Set output texture of post process to null if the texture has been released/disposed
  16219. this.scenes.forEach(function (scene) {
  16220. scene.postProcesses.forEach(function (postProcess) {
  16221. if (postProcess._outputTexture == texture) {
  16222. postProcess._outputTexture = null;
  16223. }
  16224. });
  16225. scene.cameras.forEach(function (camera) {
  16226. camera._postProcesses.forEach(function (postProcess) {
  16227. if (postProcess) {
  16228. if (postProcess._outputTexture == texture) {
  16229. postProcess._outputTexture = null;
  16230. }
  16231. }
  16232. });
  16233. });
  16234. });
  16235. };
  16236. Engine.prototype.setProgram = function (program) {
  16237. if (this._currentProgram !== program) {
  16238. this._gl.useProgram(program);
  16239. this._currentProgram = program;
  16240. }
  16241. };
  16242. /**
  16243. * Binds an effect to the webGL context
  16244. * @param effect defines the effect to bind
  16245. */
  16246. Engine.prototype.bindSamplers = function (effect) {
  16247. this.setProgram(effect.getProgram());
  16248. var samplers = effect.getSamplers();
  16249. for (var index = 0; index < samplers.length; index++) {
  16250. var uniform = effect.getUniform(samplers[index]);
  16251. if (uniform) {
  16252. this._boundUniforms[index] = uniform;
  16253. }
  16254. }
  16255. this._currentEffect = null;
  16256. };
  16257. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16258. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16259. return;
  16260. }
  16261. // Remove
  16262. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16263. // Bind last to it
  16264. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16265. // Bind to dummy
  16266. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16267. };
  16268. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16269. if (!internalTexture) {
  16270. return -1;
  16271. }
  16272. internalTexture._initialSlot = channel;
  16273. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16274. if (channel !== internalTexture._designatedSlot) {
  16275. this._textureCollisions.addCount(1, false);
  16276. }
  16277. }
  16278. else {
  16279. if (channel !== internalTexture._designatedSlot) {
  16280. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16281. return internalTexture._designatedSlot;
  16282. }
  16283. else {
  16284. // No slot for this texture, let's pick a new one (if we find a free slot)
  16285. if (this._nextFreeTextureSlots.length) {
  16286. return this._nextFreeTextureSlots[0];
  16287. }
  16288. // We need to recycle the oldest bound texture, sorry.
  16289. this._textureCollisions.addCount(1, false);
  16290. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16291. }
  16292. }
  16293. }
  16294. return channel;
  16295. };
  16296. Engine.prototype._linkTrackers = function (previous, next) {
  16297. previous.next = next;
  16298. next.previous = previous;
  16299. };
  16300. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16301. var currentSlot = internalTexture._designatedSlot;
  16302. if (currentSlot === -1) {
  16303. return -1;
  16304. }
  16305. internalTexture._designatedSlot = -1;
  16306. if (this.disableTextureBindingOptimization) {
  16307. return -1;
  16308. }
  16309. // Remove from bound list
  16310. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16311. // Free the slot
  16312. this._boundTexturesCache[currentSlot] = null;
  16313. this._nextFreeTextureSlots.push(currentSlot);
  16314. return currentSlot;
  16315. };
  16316. Engine.prototype._activateCurrentTexture = function () {
  16317. if (this._currentTextureChannel !== this._activeChannel) {
  16318. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16319. this._currentTextureChannel = this._activeChannel;
  16320. }
  16321. };
  16322. /** @hidden */
  16323. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16324. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16325. if (force === void 0) { force = false; }
  16326. var wasPreviouslyBound = false;
  16327. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16328. this._activeChannel = texture._designatedSlot;
  16329. }
  16330. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16331. var isTextureForRendering = texture && texture._initialSlot > -1;
  16332. if (currentTextureBound !== texture || force) {
  16333. if (currentTextureBound) {
  16334. this._removeDesignatedSlot(currentTextureBound);
  16335. }
  16336. this._activateCurrentTexture();
  16337. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16338. this._boundTexturesCache[this._activeChannel] = texture;
  16339. if (texture) {
  16340. if (!this.disableTextureBindingOptimization) {
  16341. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16342. if (slotIndex > -1) {
  16343. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16344. }
  16345. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16346. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16347. }
  16348. texture._designatedSlot = this._activeChannel;
  16349. }
  16350. }
  16351. else if (forTextureDataUpdate) {
  16352. wasPreviouslyBound = true;
  16353. this._activateCurrentTexture();
  16354. }
  16355. if (isTextureForRendering && !forTextureDataUpdate) {
  16356. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16357. }
  16358. return wasPreviouslyBound;
  16359. };
  16360. /** @hidden */
  16361. Engine.prototype._bindTexture = function (channel, texture) {
  16362. if (channel < 0) {
  16363. return;
  16364. }
  16365. if (texture) {
  16366. channel = this._getCorrectTextureChannel(channel, texture);
  16367. }
  16368. this._activeChannel = channel;
  16369. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16370. };
  16371. /**
  16372. * Sets a texture to the webGL context from a postprocess
  16373. * @param channel defines the channel to use
  16374. * @param postProcess defines the source postprocess
  16375. */
  16376. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16377. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16378. };
  16379. /**
  16380. * Binds the output of the passed in post process to the texture channel specified
  16381. * @param channel The channel the texture should be bound to
  16382. * @param postProcess The post process which's output should be bound
  16383. */
  16384. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16385. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16386. };
  16387. /**
  16388. * Unbind all textures from the webGL context
  16389. */
  16390. Engine.prototype.unbindAllTextures = function () {
  16391. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16392. this._activeChannel = channel;
  16393. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16394. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16395. if (this.webGLVersion > 1) {
  16396. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16397. }
  16398. }
  16399. };
  16400. /**
  16401. * Sets a texture to the according uniform.
  16402. * @param channel The texture channel
  16403. * @param uniform The uniform to set
  16404. * @param texture The texture to apply
  16405. */
  16406. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16407. if (channel < 0) {
  16408. return;
  16409. }
  16410. if (uniform) {
  16411. this._boundUniforms[channel] = uniform;
  16412. }
  16413. this._setTexture(channel, texture);
  16414. };
  16415. /**
  16416. * Sets a depth stencil texture from a render target to the according uniform.
  16417. * @param channel The texture channel
  16418. * @param uniform The uniform to set
  16419. * @param texture The render target texture containing the depth stencil texture to apply
  16420. */
  16421. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16422. if (channel < 0) {
  16423. return;
  16424. }
  16425. if (uniform) {
  16426. this._boundUniforms[channel] = uniform;
  16427. }
  16428. if (!texture || !texture.depthStencilTexture) {
  16429. this._setTexture(channel, null);
  16430. }
  16431. else {
  16432. this._setTexture(channel, texture, false, true);
  16433. }
  16434. };
  16435. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16436. var uniform = this._boundUniforms[sourceSlot];
  16437. if (uniform._currentState === destination) {
  16438. return;
  16439. }
  16440. this._gl.uniform1i(uniform, destination);
  16441. uniform._currentState = destination;
  16442. };
  16443. Engine.prototype._getTextureWrapMode = function (mode) {
  16444. switch (mode) {
  16445. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16446. return this._gl.REPEAT;
  16447. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16448. return this._gl.CLAMP_TO_EDGE;
  16449. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16450. return this._gl.MIRRORED_REPEAT;
  16451. }
  16452. return this._gl.REPEAT;
  16453. };
  16454. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16455. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16456. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16457. // Not ready?
  16458. if (!texture) {
  16459. if (this._boundTexturesCache[channel] != null) {
  16460. this._activeChannel = channel;
  16461. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16462. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16463. if (this.webGLVersion > 1) {
  16464. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16465. }
  16466. }
  16467. return false;
  16468. }
  16469. // Video
  16470. if (texture.video) {
  16471. this._activeChannel = channel;
  16472. texture.update();
  16473. }
  16474. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16475. texture.delayLoad();
  16476. return false;
  16477. }
  16478. var internalTexture;
  16479. if (depthStencilTexture) {
  16480. internalTexture = texture.depthStencilTexture;
  16481. }
  16482. else if (texture.isReady()) {
  16483. internalTexture = texture.getInternalTexture();
  16484. }
  16485. else if (texture.isCube) {
  16486. internalTexture = this.emptyCubeTexture;
  16487. }
  16488. else if (texture.is3D) {
  16489. internalTexture = this.emptyTexture3D;
  16490. }
  16491. else {
  16492. internalTexture = this.emptyTexture;
  16493. }
  16494. if (!isPartOfTextureArray) {
  16495. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16496. }
  16497. var needToBind = true;
  16498. if (this._boundTexturesCache[channel] === internalTexture) {
  16499. this._moveBoundTextureOnTop(internalTexture);
  16500. if (!isPartOfTextureArray) {
  16501. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16502. }
  16503. needToBind = false;
  16504. }
  16505. this._activeChannel = channel;
  16506. if (internalTexture && internalTexture.is3D) {
  16507. if (needToBind) {
  16508. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16509. }
  16510. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16511. internalTexture._cachedWrapU = texture.wrapU;
  16512. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16513. }
  16514. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16515. internalTexture._cachedWrapV = texture.wrapV;
  16516. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16517. }
  16518. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16519. internalTexture._cachedWrapR = texture.wrapR;
  16520. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16521. }
  16522. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16523. }
  16524. else if (internalTexture && internalTexture.isCube) {
  16525. if (needToBind) {
  16526. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16527. }
  16528. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16529. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16530. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16531. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16532. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16533. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16534. }
  16535. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16536. }
  16537. else {
  16538. if (needToBind) {
  16539. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16540. }
  16541. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16542. internalTexture._cachedWrapU = texture.wrapU;
  16543. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16544. }
  16545. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16546. internalTexture._cachedWrapV = texture.wrapV;
  16547. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16548. }
  16549. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16550. }
  16551. return true;
  16552. };
  16553. /**
  16554. * Sets an array of texture to the webGL context
  16555. * @param channel defines the channel where the texture array must be set
  16556. * @param uniform defines the associated uniform location
  16557. * @param textures defines the array of textures to bind
  16558. */
  16559. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16560. if (channel < 0 || !uniform) {
  16561. return;
  16562. }
  16563. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16564. this._textureUnits = new Int32Array(textures.length);
  16565. }
  16566. for (var i = 0; i < textures.length; i++) {
  16567. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16568. }
  16569. this._gl.uniform1iv(uniform, this._textureUnits);
  16570. for (var index = 0; index < textures.length; index++) {
  16571. this._setTexture(this._textureUnits[index], textures[index], true);
  16572. }
  16573. };
  16574. /** @hidden */
  16575. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16576. var internalTexture = texture.getInternalTexture();
  16577. if (!internalTexture) {
  16578. return;
  16579. }
  16580. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16581. var value = texture.anisotropicFilteringLevel;
  16582. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16583. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16584. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16585. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16586. }
  16587. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16588. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16589. internalTexture._cachedAnisotropicFilteringLevel = value;
  16590. }
  16591. };
  16592. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16593. this._bindTextureDirectly(target, texture, true, true);
  16594. this._gl.texParameterf(target, parameter, value);
  16595. };
  16596. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16597. if (texture) {
  16598. this._bindTextureDirectly(target, texture, true, true);
  16599. }
  16600. this._gl.texParameteri(target, parameter, value);
  16601. };
  16602. /**
  16603. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16604. * @param x defines the x coordinate of the rectangle where pixels must be read
  16605. * @param y defines the y coordinate of the rectangle where pixels must be read
  16606. * @param width defines the width of the rectangle where pixels must be read
  16607. * @param height defines the height of the rectangle where pixels must be read
  16608. * @returns a Uint8Array containing RGBA colors
  16609. */
  16610. Engine.prototype.readPixels = function (x, y, width, height) {
  16611. var data = new Uint8Array(height * width * 4);
  16612. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16613. return data;
  16614. };
  16615. /**
  16616. * Add an externaly attached data from its key.
  16617. * This method call will fail and return false, if such key already exists.
  16618. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16619. * @param key the unique key that identifies the data
  16620. * @param data the data object to associate to the key for this Engine instance
  16621. * @return true if no such key were already present and the data was added successfully, false otherwise
  16622. */
  16623. Engine.prototype.addExternalData = function (key, data) {
  16624. if (!this._externalData) {
  16625. this._externalData = new BABYLON.StringDictionary();
  16626. }
  16627. return this._externalData.add(key, data);
  16628. };
  16629. /**
  16630. * Get an externaly attached data from its key
  16631. * @param key the unique key that identifies the data
  16632. * @return the associated data, if present (can be null), or undefined if not present
  16633. */
  16634. Engine.prototype.getExternalData = function (key) {
  16635. if (!this._externalData) {
  16636. this._externalData = new BABYLON.StringDictionary();
  16637. }
  16638. return this._externalData.get(key);
  16639. };
  16640. /**
  16641. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16642. * @param key the unique key that identifies the data
  16643. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16644. * @return the associated data, can be null if the factory returned null.
  16645. */
  16646. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16647. if (!this._externalData) {
  16648. this._externalData = new BABYLON.StringDictionary();
  16649. }
  16650. return this._externalData.getOrAddWithFactory(key, factory);
  16651. };
  16652. /**
  16653. * Remove an externaly attached data from the Engine instance
  16654. * @param key the unique key that identifies the data
  16655. * @return true if the data was successfully removed, false if it doesn't exist
  16656. */
  16657. Engine.prototype.removeExternalData = function (key) {
  16658. if (!this._externalData) {
  16659. this._externalData = new BABYLON.StringDictionary();
  16660. }
  16661. return this._externalData.remove(key);
  16662. };
  16663. /**
  16664. * Unbind all vertex attributes from the webGL context
  16665. */
  16666. Engine.prototype.unbindAllAttributes = function () {
  16667. if (this._mustWipeVertexAttributes) {
  16668. this._mustWipeVertexAttributes = false;
  16669. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16670. this._gl.disableVertexAttribArray(i);
  16671. this._vertexAttribArraysEnabled[i] = false;
  16672. this._currentBufferPointers[i].active = false;
  16673. }
  16674. return;
  16675. }
  16676. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16677. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16678. continue;
  16679. }
  16680. this._gl.disableVertexAttribArray(i);
  16681. this._vertexAttribArraysEnabled[i] = false;
  16682. this._currentBufferPointers[i].active = false;
  16683. }
  16684. };
  16685. /**
  16686. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16687. */
  16688. Engine.prototype.releaseEffects = function () {
  16689. for (var name in this._compiledEffects) {
  16690. this._deleteProgram(this._compiledEffects[name]._program);
  16691. }
  16692. this._compiledEffects = {};
  16693. };
  16694. /**
  16695. * Dispose and release all associated resources
  16696. */
  16697. Engine.prototype.dispose = function () {
  16698. this.hideLoadingUI();
  16699. this.stopRenderLoop();
  16700. // Release postProcesses
  16701. while (this.postProcesses.length) {
  16702. this.postProcesses[0].dispose();
  16703. }
  16704. // Empty texture
  16705. if (this._emptyTexture) {
  16706. this._releaseTexture(this._emptyTexture);
  16707. this._emptyTexture = null;
  16708. }
  16709. if (this._emptyCubeTexture) {
  16710. this._releaseTexture(this._emptyCubeTexture);
  16711. this._emptyCubeTexture = null;
  16712. }
  16713. // Rescale PP
  16714. if (this._rescalePostProcess) {
  16715. this._rescalePostProcess.dispose();
  16716. }
  16717. // Release scenes
  16718. while (this.scenes.length) {
  16719. this.scenes[0].dispose();
  16720. }
  16721. // Release audio engine
  16722. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  16723. Engine.audioEngine.dispose();
  16724. }
  16725. // Release effects
  16726. this.releaseEffects();
  16727. // Unbind
  16728. this.unbindAllAttributes();
  16729. this._boundUniforms = [];
  16730. if (this._dummyFramebuffer) {
  16731. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16732. }
  16733. //WebVR
  16734. this.disableVR();
  16735. // Events
  16736. if (BABYLON.Tools.IsWindowObjectExist()) {
  16737. window.removeEventListener("blur", this._onBlur);
  16738. window.removeEventListener("focus", this._onFocus);
  16739. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16740. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16741. if (this._renderingCanvas) {
  16742. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16743. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16744. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16745. if (!this._doNotHandleContextLost) {
  16746. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16747. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16748. }
  16749. }
  16750. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16751. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16752. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16753. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16754. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16755. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16756. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16757. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16758. if (this._onVrDisplayConnect) {
  16759. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16760. if (this._onVrDisplayDisconnect) {
  16761. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16762. }
  16763. if (this._onVrDisplayPresentChange) {
  16764. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16765. }
  16766. this._onVrDisplayConnect = null;
  16767. this._onVrDisplayDisconnect = null;
  16768. }
  16769. }
  16770. // Remove from Instances
  16771. var index = Engine.Instances.indexOf(this);
  16772. if (index >= 0) {
  16773. Engine.Instances.splice(index, 1);
  16774. }
  16775. this._workingCanvas = null;
  16776. this._workingContext = null;
  16777. this._currentBufferPointers = [];
  16778. this._renderingCanvas = null;
  16779. this._currentProgram = null;
  16780. this._bindedRenderFunction = null;
  16781. this.onResizeObservable.clear();
  16782. this.onCanvasBlurObservable.clear();
  16783. this.onCanvasFocusObservable.clear();
  16784. this.onCanvasPointerOutObservable.clear();
  16785. this.onBeginFrameObservable.clear();
  16786. this.onEndFrameObservable.clear();
  16787. BABYLON.Effect.ResetCache();
  16788. // Abort active requests
  16789. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16790. var request = _a[_i];
  16791. request.abort();
  16792. }
  16793. };
  16794. // Loading screen
  16795. /**
  16796. * Display the loading screen
  16797. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16798. */
  16799. Engine.prototype.displayLoadingUI = function () {
  16800. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16801. return;
  16802. }
  16803. var loadingScreen = this.loadingScreen;
  16804. if (loadingScreen) {
  16805. loadingScreen.displayLoadingUI();
  16806. }
  16807. };
  16808. /**
  16809. * Hide the loading screen
  16810. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16811. */
  16812. Engine.prototype.hideLoadingUI = function () {
  16813. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16814. return;
  16815. }
  16816. var loadingScreen = this.loadingScreen;
  16817. if (loadingScreen) {
  16818. loadingScreen.hideLoadingUI();
  16819. }
  16820. };
  16821. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16822. /**
  16823. * Gets the current loading screen object
  16824. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16825. */
  16826. get: function () {
  16827. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16828. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16829. return this._loadingScreen;
  16830. },
  16831. /**
  16832. * Sets the current loading screen object
  16833. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16834. */
  16835. set: function (loadingScreen) {
  16836. this._loadingScreen = loadingScreen;
  16837. },
  16838. enumerable: true,
  16839. configurable: true
  16840. });
  16841. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16842. /**
  16843. * Sets the current loading screen text
  16844. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16845. */
  16846. set: function (text) {
  16847. this.loadingScreen.loadingUIText = text;
  16848. },
  16849. enumerable: true,
  16850. configurable: true
  16851. });
  16852. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16853. /**
  16854. * Sets the current loading screen background color
  16855. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16856. */
  16857. set: function (color) {
  16858. this.loadingScreen.loadingUIBackgroundColor = color;
  16859. },
  16860. enumerable: true,
  16861. configurable: true
  16862. });
  16863. /**
  16864. * Attach a new callback raised when context lost event is fired
  16865. * @param callback defines the callback to call
  16866. */
  16867. Engine.prototype.attachContextLostEvent = function (callback) {
  16868. if (this._renderingCanvas) {
  16869. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16870. }
  16871. };
  16872. /**
  16873. * Attach a new callback raised when context restored event is fired
  16874. * @param callback defines the callback to call
  16875. */
  16876. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16877. if (this._renderingCanvas) {
  16878. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16879. }
  16880. };
  16881. /**
  16882. * Gets the source code of the vertex shader associated with a specific webGL program
  16883. * @param program defines the program to use
  16884. * @returns a string containing the source code of the vertex shader associated with the program
  16885. */
  16886. Engine.prototype.getVertexShaderSource = function (program) {
  16887. var shaders = this._gl.getAttachedShaders(program);
  16888. if (!shaders) {
  16889. return null;
  16890. }
  16891. return this._gl.getShaderSource(shaders[0]);
  16892. };
  16893. /**
  16894. * Gets the source code of the fragment shader associated with a specific webGL program
  16895. * @param program defines the program to use
  16896. * @returns a string containing the source code of the fragment shader associated with the program
  16897. */
  16898. Engine.prototype.getFragmentShaderSource = function (program) {
  16899. var shaders = this._gl.getAttachedShaders(program);
  16900. if (!shaders) {
  16901. return null;
  16902. }
  16903. return this._gl.getShaderSource(shaders[1]);
  16904. };
  16905. /**
  16906. * Get the current error code of the webGL context
  16907. * @returns the error code
  16908. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16909. */
  16910. Engine.prototype.getError = function () {
  16911. return this._gl.getError();
  16912. };
  16913. // FPS
  16914. /**
  16915. * Gets the current framerate
  16916. * @returns a number representing the framerate
  16917. */
  16918. Engine.prototype.getFps = function () {
  16919. return this._fps;
  16920. };
  16921. /**
  16922. * Gets the time spent between current and previous frame
  16923. * @returns a number representing the delta time in ms
  16924. */
  16925. Engine.prototype.getDeltaTime = function () {
  16926. return this._deltaTime;
  16927. };
  16928. Engine.prototype._measureFps = function () {
  16929. this._performanceMonitor.sampleFrame();
  16930. this._fps = this._performanceMonitor.averageFPS;
  16931. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16932. };
  16933. /** @hidden */
  16934. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  16935. if (faceIndex === void 0) { faceIndex = -1; }
  16936. if (level === void 0) { level = 0; }
  16937. if (buffer === void 0) { buffer = null; }
  16938. var gl = this._gl;
  16939. if (!this._dummyFramebuffer) {
  16940. var dummy = gl.createFramebuffer();
  16941. if (!dummy) {
  16942. throw new Error("Unable to create dummy framebuffer");
  16943. }
  16944. this._dummyFramebuffer = dummy;
  16945. }
  16946. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16947. if (faceIndex > -1) {
  16948. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16949. }
  16950. else {
  16951. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16952. }
  16953. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16954. switch (readType) {
  16955. case gl.UNSIGNED_BYTE:
  16956. if (!buffer) {
  16957. buffer = new Uint8Array(4 * width * height);
  16958. }
  16959. readType = gl.UNSIGNED_BYTE;
  16960. break;
  16961. default:
  16962. if (!buffer) {
  16963. buffer = new Float32Array(4 * width * height);
  16964. }
  16965. readType = gl.FLOAT;
  16966. break;
  16967. }
  16968. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16969. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16970. return buffer;
  16971. };
  16972. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16973. if (this._webGLVersion > 1) {
  16974. return this._caps.colorBufferFloat;
  16975. }
  16976. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16977. };
  16978. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16979. if (this._webGLVersion > 1) {
  16980. return this._caps.colorBufferFloat;
  16981. }
  16982. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16983. };
  16984. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16985. Engine.prototype._canRenderToFramebuffer = function (type) {
  16986. var gl = this._gl;
  16987. //clear existing errors
  16988. while (gl.getError() !== gl.NO_ERROR) { }
  16989. var successful = true;
  16990. var texture = gl.createTexture();
  16991. gl.bindTexture(gl.TEXTURE_2D, texture);
  16992. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16993. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16994. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16995. var fb = gl.createFramebuffer();
  16996. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16997. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16998. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16999. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17000. successful = successful && (gl.getError() === gl.NO_ERROR);
  17001. //try render by clearing frame buffer's color buffer
  17002. if (successful) {
  17003. gl.clear(gl.COLOR_BUFFER_BIT);
  17004. successful = successful && (gl.getError() === gl.NO_ERROR);
  17005. }
  17006. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17007. if (successful) {
  17008. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17009. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17010. var readFormat = gl.RGBA;
  17011. var readType = gl.UNSIGNED_BYTE;
  17012. var buffer = new Uint8Array(4);
  17013. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17014. successful = successful && (gl.getError() === gl.NO_ERROR);
  17015. }
  17016. //clean up
  17017. gl.deleteTexture(texture);
  17018. gl.deleteFramebuffer(fb);
  17019. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17020. //clear accumulated errors
  17021. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17022. return successful;
  17023. };
  17024. /** @hidden */
  17025. Engine.prototype._getWebGLTextureType = function (type) {
  17026. if (this._webGLVersion === 1) {
  17027. switch (type) {
  17028. case Engine.TEXTURETYPE_FLOAT:
  17029. return this._gl.FLOAT;
  17030. case Engine.TEXTURETYPE_HALF_FLOAT:
  17031. return this._gl.HALF_FLOAT_OES;
  17032. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17033. return this._gl.UNSIGNED_BYTE;
  17034. }
  17035. return this._gl.UNSIGNED_BYTE;
  17036. }
  17037. switch (type) {
  17038. case Engine.TEXTURETYPE_BYTE:
  17039. return this._gl.BYTE;
  17040. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17041. return this._gl.UNSIGNED_BYTE;
  17042. case Engine.TEXTURETYPE_SHORT:
  17043. return this._gl.SHORT;
  17044. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17045. return this._gl.UNSIGNED_SHORT;
  17046. case Engine.TEXTURETYPE_INT:
  17047. return this._gl.INT;
  17048. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17049. return this._gl.UNSIGNED_INT;
  17050. case Engine.TEXTURETYPE_FLOAT:
  17051. return this._gl.FLOAT;
  17052. case Engine.TEXTURETYPE_HALF_FLOAT:
  17053. return this._gl.HALF_FLOAT;
  17054. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17055. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17056. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17057. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17058. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17059. return this._gl.UNSIGNED_SHORT_5_6_5;
  17060. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17061. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17062. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17063. return this._gl.UNSIGNED_INT_24_8;
  17064. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17065. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17066. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17067. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17068. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17069. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17070. }
  17071. return this._gl.UNSIGNED_BYTE;
  17072. };
  17073. ;
  17074. Engine.prototype._getInternalFormat = function (format) {
  17075. var internalFormat = this._gl.RGBA;
  17076. switch (format) {
  17077. case Engine.TEXTUREFORMAT_ALPHA:
  17078. internalFormat = this._gl.ALPHA;
  17079. break;
  17080. case Engine.TEXTUREFORMAT_LUMINANCE:
  17081. internalFormat = this._gl.LUMINANCE;
  17082. break;
  17083. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17084. internalFormat = this._gl.LUMINANCE_ALPHA;
  17085. break;
  17086. case Engine.TEXTUREFORMAT_RED:
  17087. internalFormat = this._gl.RED;
  17088. break;
  17089. case Engine.TEXTUREFORMAT_RG:
  17090. internalFormat = this._gl.RG;
  17091. break;
  17092. case Engine.TEXTUREFORMAT_RGB:
  17093. internalFormat = this._gl.RGB;
  17094. break;
  17095. case Engine.TEXTUREFORMAT_RGBA:
  17096. internalFormat = this._gl.RGBA;
  17097. break;
  17098. }
  17099. if (this._webGLVersion > 1) {
  17100. switch (format) {
  17101. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17102. internalFormat = this._gl.RED_INTEGER;
  17103. break;
  17104. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17105. internalFormat = this._gl.RG_INTEGER;
  17106. break;
  17107. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17108. internalFormat = this._gl.RGB_INTEGER;
  17109. break;
  17110. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17111. internalFormat = this._gl.RGBA_INTEGER;
  17112. break;
  17113. }
  17114. }
  17115. return internalFormat;
  17116. };
  17117. /** @hidden */
  17118. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17119. if (this._webGLVersion === 1) {
  17120. if (format !== undefined) {
  17121. switch (format) {
  17122. case Engine.TEXTUREFORMAT_ALPHA:
  17123. return this._gl.ALPHA;
  17124. case Engine.TEXTUREFORMAT_LUMINANCE:
  17125. return this._gl.LUMINANCE;
  17126. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17127. return this._gl.LUMINANCE_ALPHA;
  17128. }
  17129. }
  17130. return this._gl.RGBA;
  17131. }
  17132. switch (type) {
  17133. case Engine.TEXTURETYPE_BYTE:
  17134. switch (format) {
  17135. case Engine.TEXTUREFORMAT_RED:
  17136. return this._gl.R8_SNORM;
  17137. case Engine.TEXTUREFORMAT_RG:
  17138. return this._gl.RG8_SNORM;
  17139. case Engine.TEXTUREFORMAT_RGB:
  17140. return this._gl.RGB8_SNORM;
  17141. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17142. return this._gl.R8I;
  17143. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17144. return this._gl.RG8I;
  17145. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17146. return this._gl.RGB8I;
  17147. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17148. return this._gl.RGBA8I;
  17149. default:
  17150. return this._gl.RGBA8_SNORM;
  17151. }
  17152. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17153. switch (format) {
  17154. case Engine.TEXTUREFORMAT_RED:
  17155. return this._gl.R8;
  17156. case Engine.TEXTUREFORMAT_RG:
  17157. return this._gl.RG8;
  17158. case Engine.TEXTUREFORMAT_RGB:
  17159. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17160. case Engine.TEXTUREFORMAT_RGBA:
  17161. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17162. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17163. return this._gl.R8UI;
  17164. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17165. return this._gl.RG8UI;
  17166. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17167. return this._gl.RGB8UI;
  17168. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17169. return this._gl.RGBA8UI;
  17170. default:
  17171. return this._gl.RGBA8;
  17172. }
  17173. case Engine.TEXTURETYPE_SHORT:
  17174. switch (format) {
  17175. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17176. return this._gl.R16I;
  17177. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17178. return this._gl.RG16I;
  17179. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17180. return this._gl.RGB16I;
  17181. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17182. return this._gl.RGBA16I;
  17183. default:
  17184. return this._gl.RGBA16I;
  17185. }
  17186. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17187. switch (format) {
  17188. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17189. return this._gl.R16UI;
  17190. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17191. return this._gl.RG16UI;
  17192. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17193. return this._gl.RGB16UI;
  17194. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17195. return this._gl.RGBA16UI;
  17196. default:
  17197. return this._gl.RGBA16UI;
  17198. }
  17199. case Engine.TEXTURETYPE_INT:
  17200. switch (format) {
  17201. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17202. return this._gl.R32I;
  17203. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17204. return this._gl.RG32I;
  17205. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17206. return this._gl.RGB32I;
  17207. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17208. return this._gl.RGBA32I;
  17209. default:
  17210. return this._gl.RGBA32I;
  17211. }
  17212. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17213. switch (format) {
  17214. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17215. return this._gl.R32UI;
  17216. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17217. return this._gl.RG32UI;
  17218. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17219. return this._gl.RGB32UI;
  17220. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17221. return this._gl.RGBA32UI;
  17222. default:
  17223. return this._gl.RGBA32UI;
  17224. }
  17225. case Engine.TEXTURETYPE_FLOAT:
  17226. switch (format) {
  17227. case Engine.TEXTUREFORMAT_RED:
  17228. return this._gl.R32F; // By default. Other possibility is R16F.
  17229. case Engine.TEXTUREFORMAT_RG:
  17230. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17231. case Engine.TEXTUREFORMAT_RGB:
  17232. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17233. case Engine.TEXTUREFORMAT_RGBA:
  17234. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17235. default:
  17236. return this._gl.RGBA32F;
  17237. }
  17238. case Engine.TEXTURETYPE_HALF_FLOAT:
  17239. switch (format) {
  17240. case Engine.TEXTUREFORMAT_RED:
  17241. return this._gl.R16F;
  17242. case Engine.TEXTUREFORMAT_RG:
  17243. return this._gl.RG16F;
  17244. case Engine.TEXTUREFORMAT_RGB:
  17245. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17246. case Engine.TEXTUREFORMAT_RGBA:
  17247. return this._gl.RGBA16F;
  17248. default:
  17249. return this._gl.RGBA16F;
  17250. }
  17251. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17252. return this._gl.RGB565;
  17253. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17254. return this._gl.R11F_G11F_B10F;
  17255. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17256. return this._gl.RGB9_E5;
  17257. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17258. return this._gl.RGBA4;
  17259. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17260. return this._gl.RGB5_A1;
  17261. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17262. switch (format) {
  17263. case Engine.TEXTUREFORMAT_RGBA:
  17264. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17265. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17266. return this._gl.RGB10_A2UI;
  17267. default:
  17268. return this._gl.RGB10_A2;
  17269. }
  17270. }
  17271. return this._gl.RGBA8;
  17272. };
  17273. ;
  17274. /** @hidden */
  17275. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17276. if (type === Engine.TEXTURETYPE_FLOAT) {
  17277. return this._gl.RGBA32F;
  17278. }
  17279. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17280. return this._gl.RGBA16F;
  17281. }
  17282. return this._gl.RGBA8;
  17283. };
  17284. ;
  17285. /** @hidden */
  17286. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17287. var _this = this;
  17288. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17289. this._activeRequests.push(request);
  17290. request.onCompleteObservable.add(function (request) {
  17291. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17292. });
  17293. return request;
  17294. };
  17295. /** @hidden */
  17296. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17297. var _this = this;
  17298. return new Promise(function (resolve, reject) {
  17299. _this._loadFile(url, function (data) {
  17300. resolve(data);
  17301. }, undefined, database, useArrayBuffer, function (request, exception) {
  17302. reject(exception);
  17303. });
  17304. });
  17305. };
  17306. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17307. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17308. var onload = function (data) {
  17309. loadedFiles[index] = data;
  17310. loadedFiles._internalCount++;
  17311. if (loadedFiles._internalCount === 6) {
  17312. onfinish(loadedFiles);
  17313. }
  17314. };
  17315. var onerror = function (request, exception) {
  17316. if (onErrorCallBack && request) {
  17317. onErrorCallBack(request.status + " " + request.statusText, exception);
  17318. }
  17319. };
  17320. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17321. };
  17322. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17323. if (onError === void 0) { onError = null; }
  17324. var loadedFiles = [];
  17325. loadedFiles._internalCount = 0;
  17326. for (var index = 0; index < 6; index++) {
  17327. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17328. }
  17329. };
  17330. // Statics
  17331. /**
  17332. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17333. * @returns true if the engine can be created
  17334. * @ignorenaming
  17335. */
  17336. Engine.isSupported = function () {
  17337. try {
  17338. var tempcanvas = document.createElement("canvas");
  17339. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17340. return gl != null && !!window.WebGLRenderingContext;
  17341. }
  17342. catch (e) {
  17343. return false;
  17344. }
  17345. };
  17346. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17347. Engine.ExceptionList = [
  17348. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17349. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17350. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17351. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17352. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17353. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17354. ];
  17355. /** Gets the list of created engines */
  17356. Engine.Instances = new Array();
  17357. /**
  17358. * Hidden
  17359. */
  17360. Engine._TextureLoaders = [];
  17361. // Const statics
  17362. /** Defines that alpha blending is disabled */
  17363. Engine.ALPHA_DISABLE = 0;
  17364. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17365. Engine.ALPHA_ADD = 1;
  17366. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17367. Engine.ALPHA_COMBINE = 2;
  17368. /** Defines that alpha blending to DEST - SRC * DEST */
  17369. Engine.ALPHA_SUBTRACT = 3;
  17370. /** Defines that alpha blending to SRC * DEST */
  17371. Engine.ALPHA_MULTIPLY = 4;
  17372. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17373. Engine.ALPHA_MAXIMIZED = 5;
  17374. /** Defines that alpha blending to SRC + DEST */
  17375. Engine.ALPHA_ONEONE = 6;
  17376. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17377. Engine.ALPHA_PREMULTIPLIED = 7;
  17378. /**
  17379. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17380. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17381. */
  17382. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17383. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17384. Engine.ALPHA_INTERPOLATE = 9;
  17385. /**
  17386. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17387. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17388. */
  17389. Engine.ALPHA_SCREENMODE = 10;
  17390. /** Defines that the ressource is not delayed*/
  17391. Engine.DELAYLOADSTATE_NONE = 0;
  17392. /** Defines that the ressource was successfully delay loaded */
  17393. Engine.DELAYLOADSTATE_LOADED = 1;
  17394. /** Defines that the ressource is currently delay loading */
  17395. Engine.DELAYLOADSTATE_LOADING = 2;
  17396. /** Defines that the ressource is delayed and has not started loading */
  17397. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17398. // Depht or Stencil test Constants.
  17399. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17400. Engine.NEVER = 0x0200;
  17401. /** 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 */
  17402. Engine.ALWAYS = 0x0207;
  17403. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17404. Engine.LESS = 0x0201;
  17405. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17406. Engine.EQUAL = 0x0202;
  17407. /** 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 */
  17408. Engine.LEQUAL = 0x0203;
  17409. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17410. Engine.GREATER = 0x0204;
  17411. /** 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 */
  17412. Engine.GEQUAL = 0x0206;
  17413. /** 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 */
  17414. Engine.NOTEQUAL = 0x0205;
  17415. // Stencil Actions Constants.
  17416. /** Passed to stencilOperation to specify that stencil value must be kept */
  17417. Engine.KEEP = 0x1E00;
  17418. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17419. Engine.REPLACE = 0x1E01;
  17420. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17421. Engine.INCR = 0x1E02;
  17422. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17423. Engine.DECR = 0x1E03;
  17424. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17425. Engine.INVERT = 0x150A;
  17426. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17427. Engine.INCR_WRAP = 0x8507;
  17428. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17429. Engine.DECR_WRAP = 0x8508;
  17430. /** Texture is not repeating outside of 0..1 UVs */
  17431. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17432. /** Texture is repeating outside of 0..1 UVs */
  17433. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17434. /** Texture is repeating and mirrored */
  17435. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17436. /** ALPHA */
  17437. Engine.TEXTUREFORMAT_ALPHA = 0;
  17438. /** LUMINANCE */
  17439. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17440. /** LUMINANCE_ALPHA */
  17441. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17442. /** RGB */
  17443. Engine.TEXTUREFORMAT_RGB = 4;
  17444. /** RGBA */
  17445. Engine.TEXTUREFORMAT_RGBA = 5;
  17446. /** RED */
  17447. Engine.TEXTUREFORMAT_RED = 6;
  17448. /** RED (2nd reference) */
  17449. Engine.TEXTUREFORMAT_R = 6;
  17450. /** RG */
  17451. Engine.TEXTUREFORMAT_RG = 7;
  17452. /** RED_INTEGER */
  17453. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17454. /** RED_INTEGER (2nd reference) */
  17455. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17456. /** RG_INTEGER */
  17457. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17458. /** RGB_INTEGER */
  17459. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17460. /** RGBA_INTEGER */
  17461. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17462. /** UNSIGNED_BYTE */
  17463. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17464. /** UNSIGNED_BYTE (2nd reference) */
  17465. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17466. /** FLOAT */
  17467. Engine.TEXTURETYPE_FLOAT = 1;
  17468. /** HALF_FLOAT */
  17469. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17470. /** BYTE */
  17471. Engine.TEXTURETYPE_BYTE = 3;
  17472. /** SHORT */
  17473. Engine.TEXTURETYPE_SHORT = 4;
  17474. /** UNSIGNED_SHORT */
  17475. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17476. /** INT */
  17477. Engine.TEXTURETYPE_INT = 6;
  17478. /** UNSIGNED_INT */
  17479. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17480. /** UNSIGNED_SHORT_4_4_4_4 */
  17481. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17482. /** UNSIGNED_SHORT_5_5_5_1 */
  17483. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17484. /** UNSIGNED_SHORT_5_6_5 */
  17485. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17486. /** UNSIGNED_INT_2_10_10_10_REV */
  17487. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17488. /** UNSIGNED_INT_24_8 */
  17489. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17490. /** UNSIGNED_INT_10F_11F_11F_REV */
  17491. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17492. /** UNSIGNED_INT_5_9_9_9_REV */
  17493. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17494. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17495. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17496. /** nearest is mag = nearest and min = nearest and mip = linear */
  17497. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17498. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17499. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17500. /** Trilinear is mag = linear and min = linear and mip = linear */
  17501. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17502. /** nearest is mag = nearest and min = nearest and mip = linear */
  17503. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17504. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17505. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17506. /** Trilinear is mag = linear and min = linear and mip = linear */
  17507. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17508. /** mag = nearest and min = nearest and mip = nearest */
  17509. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17510. /** mag = nearest and min = linear and mip = nearest */
  17511. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17512. /** mag = nearest and min = linear and mip = linear */
  17513. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17514. /** mag = nearest and min = linear and mip = none */
  17515. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17516. /** mag = nearest and min = nearest and mip = none */
  17517. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17518. /** mag = linear and min = nearest and mip = nearest */
  17519. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17520. /** mag = linear and min = nearest and mip = linear */
  17521. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17522. /** mag = linear and min = linear and mip = none */
  17523. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17524. /** mag = linear and min = nearest and mip = none */
  17525. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17526. /** Explicit coordinates mode */
  17527. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17528. /** Spherical coordinates mode */
  17529. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17530. /** Planar coordinates mode */
  17531. Engine.TEXTURE_PLANAR_MODE = 2;
  17532. /** Cubic coordinates mode */
  17533. Engine.TEXTURE_CUBIC_MODE = 3;
  17534. /** Projection coordinates mode */
  17535. Engine.TEXTURE_PROJECTION_MODE = 4;
  17536. /** Skybox coordinates mode */
  17537. Engine.TEXTURE_SKYBOX_MODE = 5;
  17538. /** Inverse Cubic coordinates mode */
  17539. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17540. /** Equirectangular coordinates mode */
  17541. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17542. /** Equirectangular Fixed coordinates mode */
  17543. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17544. /** Equirectangular Fixed Mirrored coordinates mode */
  17545. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17546. // Texture rescaling mode
  17547. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17548. Engine.SCALEMODE_FLOOR = 1;
  17549. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17550. Engine.SCALEMODE_NEAREST = 2;
  17551. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17552. Engine.SCALEMODE_CEILING = 3;
  17553. // Updatable statics so stick with vars here
  17554. /**
  17555. * Gets or sets the epsilon value used by collision engine
  17556. */
  17557. Engine.CollisionsEpsilon = 0.001;
  17558. /**
  17559. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17560. */
  17561. Engine.CodeRepository = "src/";
  17562. /**
  17563. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17564. */
  17565. Engine.ShadersRepository = "src/Shaders/";
  17566. return Engine;
  17567. }());
  17568. BABYLON.Engine = Engine;
  17569. })(BABYLON || (BABYLON = {}));
  17570. //# sourceMappingURL=babylon.engine.js.map
  17571. var BABYLON;
  17572. (function (BABYLON) {
  17573. /**
  17574. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17575. */
  17576. var Node = /** @class */ (function () {
  17577. /**
  17578. * Creates a new Node
  17579. * @param {string} name - the name and id to be given to this node
  17580. * @param {BABYLON.Scene} the scene this node will be added to
  17581. */
  17582. function Node(name, scene) {
  17583. if (scene === void 0) { scene = null; }
  17584. /**
  17585. * Gets or sets a string used to store user defined state for the node
  17586. */
  17587. this.state = "";
  17588. /**
  17589. * Gets or sets an object used to store user defined information for the node
  17590. */
  17591. this.metadata = null;
  17592. /**
  17593. * Gets or sets a boolean used to define if the node must be serialized
  17594. */
  17595. this.doNotSerialize = false;
  17596. /** @hidden */
  17597. this._isDisposed = false;
  17598. /**
  17599. * Gets a list of Animations associated with the node
  17600. */
  17601. this.animations = new Array();
  17602. this._ranges = {};
  17603. this._isEnabled = true;
  17604. this._isReady = true;
  17605. /** @hidden */
  17606. this._currentRenderId = -1;
  17607. this._parentRenderId = -1;
  17608. this._childRenderId = -1;
  17609. /** @hidden */
  17610. this._worldMatrix = BABYLON.Matrix.Zero();
  17611. /** @hidden */
  17612. this._worldMatrixDeterminant = 0;
  17613. this._animationPropertiesOverride = null;
  17614. /**
  17615. * An event triggered when the mesh is disposed
  17616. */
  17617. this.onDisposeObservable = new BABYLON.Observable();
  17618. // Behaviors
  17619. this._behaviors = new Array();
  17620. this.name = name;
  17621. this.id = name;
  17622. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17623. this.uniqueId = this._scene.getUniqueId();
  17624. this._initCache();
  17625. this._scene.rootNodes.push(this);
  17626. }
  17627. /**
  17628. * Add a new node constructor
  17629. * @param type defines the type name of the node to construct
  17630. * @param constructorFunc defines the constructor function
  17631. */
  17632. Node.AddNodeConstructor = function (type, constructorFunc) {
  17633. this._NodeConstructors[type] = constructorFunc;
  17634. };
  17635. /**
  17636. * Returns a node constructor based on type name
  17637. * @param type defines the type name
  17638. * @param name defines the new node name
  17639. * @param scene defines the hosting scene
  17640. * @param options defines optional options to transmit to constructors
  17641. * @returns the new constructor or null
  17642. */
  17643. Node.Construct = function (type, name, scene, options) {
  17644. var constructorFunc = this._NodeConstructors[type];
  17645. if (!constructorFunc) {
  17646. return null;
  17647. }
  17648. return constructorFunc(name, scene, options);
  17649. };
  17650. /**
  17651. * Gets a boolean indicating if the node has been disposed
  17652. * @returns true if the node was disposed
  17653. */
  17654. Node.prototype.isDisposed = function () {
  17655. return this._isDisposed;
  17656. };
  17657. Object.defineProperty(Node.prototype, "parent", {
  17658. get: function () {
  17659. return this._parentNode;
  17660. },
  17661. /**
  17662. * Gets or sets the parent of the node
  17663. */
  17664. set: function (parent) {
  17665. if (this._parentNode === parent) {
  17666. return;
  17667. }
  17668. var previousParentNode = this._parentNode;
  17669. // Remove self from list of children of parent
  17670. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17671. var index = this._parentNode._children.indexOf(this);
  17672. if (index !== -1) {
  17673. this._parentNode._children.splice(index, 1);
  17674. }
  17675. if (!parent) {
  17676. // Need to add this node to the rootNodes
  17677. this._scene.rootNodes.push(this);
  17678. }
  17679. }
  17680. // Store new parent
  17681. this._parentNode = parent;
  17682. // Add as child to new parent
  17683. if (this._parentNode) {
  17684. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17685. this._parentNode._children = new Array();
  17686. }
  17687. this._parentNode._children.push(this);
  17688. if (!previousParentNode) {
  17689. // Need to remove from rootNodes
  17690. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17691. if (rootNodeIndex > -1) {
  17692. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17693. }
  17694. }
  17695. }
  17696. },
  17697. enumerable: true,
  17698. configurable: true
  17699. });
  17700. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17701. /**
  17702. * Gets or sets the animation properties override
  17703. */
  17704. get: function () {
  17705. if (!this._animationPropertiesOverride) {
  17706. return this._scene.animationPropertiesOverride;
  17707. }
  17708. return this._animationPropertiesOverride;
  17709. },
  17710. set: function (value) {
  17711. this._animationPropertiesOverride = value;
  17712. },
  17713. enumerable: true,
  17714. configurable: true
  17715. });
  17716. /**
  17717. * Gets a string idenfifying the name of the class
  17718. * @returns "Node" string
  17719. */
  17720. Node.prototype.getClassName = function () {
  17721. return "Node";
  17722. };
  17723. Object.defineProperty(Node.prototype, "onDispose", {
  17724. /**
  17725. * Sets a callback that will be raised when the node will be disposed
  17726. */
  17727. set: function (callback) {
  17728. if (this._onDisposeObserver) {
  17729. this.onDisposeObservable.remove(this._onDisposeObserver);
  17730. }
  17731. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17732. },
  17733. enumerable: true,
  17734. configurable: true
  17735. });
  17736. /**
  17737. * Gets the scene of the node
  17738. * @returns a {BABYLON.Scene}
  17739. */
  17740. Node.prototype.getScene = function () {
  17741. return this._scene;
  17742. };
  17743. /**
  17744. * Gets the engine of the node
  17745. * @returns a {BABYLON.Engine}
  17746. */
  17747. Node.prototype.getEngine = function () {
  17748. return this._scene.getEngine();
  17749. };
  17750. /**
  17751. * Attach a behavior to the node
  17752. * @see http://doc.babylonjs.com/features/behaviour
  17753. * @param behavior defines the behavior to attach
  17754. * @returns the current Node
  17755. */
  17756. Node.prototype.addBehavior = function (behavior) {
  17757. var _this = this;
  17758. var index = this._behaviors.indexOf(behavior);
  17759. if (index !== -1) {
  17760. return this;
  17761. }
  17762. behavior.init();
  17763. if (this._scene.isLoading) {
  17764. // We defer the attach when the scene will be loaded
  17765. this._scene.onDataLoadedObservable.addOnce(function () {
  17766. behavior.attach(_this);
  17767. });
  17768. }
  17769. else {
  17770. behavior.attach(this);
  17771. }
  17772. this._behaviors.push(behavior);
  17773. return this;
  17774. };
  17775. /**
  17776. * Remove an attached behavior
  17777. * @see http://doc.babylonjs.com/features/behaviour
  17778. * @param behavior defines the behavior to attach
  17779. * @returns the current Node
  17780. */
  17781. Node.prototype.removeBehavior = function (behavior) {
  17782. var index = this._behaviors.indexOf(behavior);
  17783. if (index === -1) {
  17784. return this;
  17785. }
  17786. this._behaviors[index].detach();
  17787. this._behaviors.splice(index, 1);
  17788. return this;
  17789. };
  17790. Object.defineProperty(Node.prototype, "behaviors", {
  17791. /**
  17792. * Gets the list of attached behaviors
  17793. * @see http://doc.babylonjs.com/features/behaviour
  17794. */
  17795. get: function () {
  17796. return this._behaviors;
  17797. },
  17798. enumerable: true,
  17799. configurable: true
  17800. });
  17801. /**
  17802. * Gets an attached behavior by name
  17803. * @param name defines the name of the behavior to look for
  17804. * @see http://doc.babylonjs.com/features/behaviour
  17805. * @returns null if behavior was not found else the requested behavior
  17806. */
  17807. Node.prototype.getBehaviorByName = function (name) {
  17808. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17809. var behavior = _a[_i];
  17810. if (behavior.name === name) {
  17811. return behavior;
  17812. }
  17813. }
  17814. return null;
  17815. };
  17816. /**
  17817. * Returns the latest update of the World matrix
  17818. * @returns a Matrix
  17819. */
  17820. Node.prototype.getWorldMatrix = function () {
  17821. if (this._currentRenderId !== this._scene.getRenderId()) {
  17822. this.computeWorldMatrix();
  17823. }
  17824. return this._worldMatrix;
  17825. };
  17826. /** @hidden */
  17827. Node.prototype._getWorldMatrixDeterminant = function () {
  17828. return this._worldMatrixDeterminant;
  17829. };
  17830. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  17831. /**
  17832. * Returns directly the latest state of the mesh World matrix.
  17833. * A Matrix is returned.
  17834. */
  17835. get: function () {
  17836. return this._worldMatrix;
  17837. },
  17838. enumerable: true,
  17839. configurable: true
  17840. });
  17841. // override it in derived class if you add new variables to the cache
  17842. // and call the parent class method
  17843. /** @hidden */
  17844. Node.prototype._initCache = function () {
  17845. this._cache = {};
  17846. this._cache.parent = undefined;
  17847. };
  17848. /** @hidden */
  17849. Node.prototype.updateCache = function (force) {
  17850. if (!force && this.isSynchronized())
  17851. return;
  17852. this._cache.parent = this.parent;
  17853. this._updateCache();
  17854. };
  17855. // override it in derived class if you add new variables to the cache
  17856. // and call the parent class method if !ignoreParentClass
  17857. /** @hidden */
  17858. Node.prototype._updateCache = function (ignoreParentClass) {
  17859. };
  17860. // override it in derived class if you add new variables to the cache
  17861. /** @hidden */
  17862. Node.prototype._isSynchronized = function () {
  17863. return true;
  17864. };
  17865. /** @hidden */
  17866. Node.prototype._markSyncedWithParent = function () {
  17867. if (this._parentNode) {
  17868. this._parentRenderId = this._parentNode._childRenderId;
  17869. }
  17870. };
  17871. /** @hidden */
  17872. Node.prototype.isSynchronizedWithParent = function () {
  17873. if (!this._parentNode) {
  17874. return true;
  17875. }
  17876. if (this._parentRenderId !== this._parentNode._childRenderId) {
  17877. return false;
  17878. }
  17879. return this._parentNode.isSynchronized();
  17880. };
  17881. /** @hidden */
  17882. Node.prototype.isSynchronized = function () {
  17883. if (this._cache.parent != this._parentNode) {
  17884. this._cache.parent = this._parentNode;
  17885. return false;
  17886. }
  17887. if (this._parentNode && !this.isSynchronizedWithParent()) {
  17888. return false;
  17889. }
  17890. return this._isSynchronized();
  17891. };
  17892. /**
  17893. * Is this node ready to be used/rendered
  17894. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17895. * @return true if the node is ready
  17896. */
  17897. Node.prototype.isReady = function (completeCheck) {
  17898. if (completeCheck === void 0) { completeCheck = false; }
  17899. return this._isReady;
  17900. };
  17901. /**
  17902. * Is this node enabled?
  17903. * 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
  17904. * @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
  17905. * @return whether this node (and its parent) is enabled
  17906. */
  17907. Node.prototype.isEnabled = function (checkAncestors) {
  17908. if (checkAncestors === void 0) { checkAncestors = true; }
  17909. if (checkAncestors === false) {
  17910. return this._isEnabled;
  17911. }
  17912. if (this._isEnabled === false) {
  17913. return false;
  17914. }
  17915. if (this._parentNode !== undefined && this._parentNode !== null) {
  17916. return this._parentNode.isEnabled(checkAncestors);
  17917. }
  17918. return true;
  17919. };
  17920. /**
  17921. * Set the enabled state of this node
  17922. * @param value defines the new enabled state
  17923. */
  17924. Node.prototype.setEnabled = function (value) {
  17925. this._isEnabled = value;
  17926. };
  17927. /**
  17928. * Is this node a descendant of the given node?
  17929. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17930. * @param ancestor defines the parent node to inspect
  17931. * @returns a boolean indicating if this node is a descendant of the given node
  17932. */
  17933. Node.prototype.isDescendantOf = function (ancestor) {
  17934. if (this.parent) {
  17935. if (this.parent === ancestor) {
  17936. return true;
  17937. }
  17938. return this.parent.isDescendantOf(ancestor);
  17939. }
  17940. return false;
  17941. };
  17942. /** @hidden */
  17943. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17944. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17945. if (!this._children) {
  17946. return;
  17947. }
  17948. for (var index = 0; index < this._children.length; index++) {
  17949. var item = this._children[index];
  17950. if (!predicate || predicate(item)) {
  17951. results.push(item);
  17952. }
  17953. if (!directDescendantsOnly) {
  17954. item._getDescendants(results, false, predicate);
  17955. }
  17956. }
  17957. };
  17958. /**
  17959. * Will return all nodes that have this node as ascendant
  17960. * @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
  17961. * @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
  17962. * @return all children nodes of all types
  17963. */
  17964. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17965. var results = new Array();
  17966. this._getDescendants(results, directDescendantsOnly, predicate);
  17967. return results;
  17968. };
  17969. /**
  17970. * Get all child-meshes of this node
  17971. * @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
  17972. * @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
  17973. * @returns an array of {BABYLON.AbstractMesh}
  17974. */
  17975. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17976. var results = [];
  17977. this._getDescendants(results, directDescendantsOnly, function (node) {
  17978. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17979. });
  17980. return results;
  17981. };
  17982. /**
  17983. * Get all child-transformNodes of this node
  17984. * @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
  17985. * @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
  17986. * @returns an array of {BABYLON.TransformNode}
  17987. */
  17988. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17989. var results = [];
  17990. this._getDescendants(results, directDescendantsOnly, function (node) {
  17991. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17992. });
  17993. return results;
  17994. };
  17995. /**
  17996. * Get all direct children of this node
  17997. * @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
  17998. * @returns an array of {BABYLON.Node}
  17999. */
  18000. Node.prototype.getChildren = function (predicate) {
  18001. if (!predicate) {
  18002. return this._children;
  18003. }
  18004. return this.getDescendants(true, predicate);
  18005. };
  18006. /** @hidden */
  18007. Node.prototype._setReady = function (state) {
  18008. if (state === this._isReady) {
  18009. return;
  18010. }
  18011. if (!state) {
  18012. this._isReady = false;
  18013. return;
  18014. }
  18015. if (this.onReady) {
  18016. this.onReady(this);
  18017. }
  18018. this._isReady = true;
  18019. };
  18020. /**
  18021. * Get an animation by name
  18022. * @param name defines the name of the animation to look for
  18023. * @returns null if not found else the requested animation
  18024. */
  18025. Node.prototype.getAnimationByName = function (name) {
  18026. for (var i = 0; i < this.animations.length; i++) {
  18027. var animation = this.animations[i];
  18028. if (animation.name === name) {
  18029. return animation;
  18030. }
  18031. }
  18032. return null;
  18033. };
  18034. /**
  18035. * Creates an animation range for this node
  18036. * @param name defines the name of the range
  18037. * @param from defines the starting key
  18038. * @param to defines the end key
  18039. */
  18040. Node.prototype.createAnimationRange = function (name, from, to) {
  18041. // check name not already in use
  18042. if (!this._ranges[name]) {
  18043. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18044. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18045. if (this.animations[i]) {
  18046. this.animations[i].createRange(name, from, to);
  18047. }
  18048. }
  18049. }
  18050. };
  18051. /**
  18052. * Delete a specific animation range
  18053. * @param name defines the name of the range to delete
  18054. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18055. */
  18056. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18057. if (deleteFrames === void 0) { deleteFrames = true; }
  18058. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18059. if (this.animations[i]) {
  18060. this.animations[i].deleteRange(name, deleteFrames);
  18061. }
  18062. }
  18063. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18064. };
  18065. /**
  18066. * Get an animation range by name
  18067. * @param name defines the name of the animation range to look for
  18068. * @returns null if not found else the requested animation range
  18069. */
  18070. Node.prototype.getAnimationRange = function (name) {
  18071. return this._ranges[name];
  18072. };
  18073. /**
  18074. * Will start the animation sequence
  18075. * @param name defines the range frames for animation sequence
  18076. * @param loop defines if the animation should loop (false by default)
  18077. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18078. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18079. * @returns the object created for this animation. If range does not exist, it will return null
  18080. */
  18081. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18082. var range = this.getAnimationRange(name);
  18083. if (!range) {
  18084. return null;
  18085. }
  18086. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18087. };
  18088. /**
  18089. * Serialize animation ranges into a JSON compatible object
  18090. * @returns serialization object
  18091. */
  18092. Node.prototype.serializeAnimationRanges = function () {
  18093. var serializationRanges = [];
  18094. for (var name in this._ranges) {
  18095. var localRange = this._ranges[name];
  18096. if (!localRange) {
  18097. continue;
  18098. }
  18099. var range = {};
  18100. range.name = name;
  18101. range.from = localRange.from;
  18102. range.to = localRange.to;
  18103. serializationRanges.push(range);
  18104. }
  18105. return serializationRanges;
  18106. };
  18107. /**
  18108. * Computes the world matrix of the node
  18109. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18110. * @returns the world matrix
  18111. */
  18112. Node.prototype.computeWorldMatrix = function (force) {
  18113. if (!this._worldMatrix) {
  18114. this._worldMatrix = BABYLON.Matrix.Identity();
  18115. }
  18116. return this._worldMatrix;
  18117. };
  18118. /**
  18119. * Releases resources associated with this node.
  18120. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18121. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18122. */
  18123. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18124. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18125. if (!doNotRecurse) {
  18126. var nodes = this.getDescendants(true);
  18127. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18128. var node = nodes_1[_i];
  18129. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18130. }
  18131. }
  18132. else {
  18133. var transformNodes = this.getChildTransformNodes(true);
  18134. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18135. var transformNode = transformNodes_1[_a];
  18136. transformNode.parent = null;
  18137. transformNode.computeWorldMatrix(true);
  18138. }
  18139. }
  18140. if (!this.parent) {
  18141. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18142. if (rootNodeIndex > -1) {
  18143. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18144. }
  18145. }
  18146. else {
  18147. this.parent = null;
  18148. }
  18149. // Callback
  18150. this.onDisposeObservable.notifyObservers(this);
  18151. this.onDisposeObservable.clear();
  18152. // Behaviors
  18153. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18154. var behavior = _c[_b];
  18155. behavior.detach();
  18156. }
  18157. this._behaviors = [];
  18158. this._isDisposed = true;
  18159. };
  18160. /**
  18161. * Parse animation range data from a serialization object and store them into a given node
  18162. * @param node defines where to store the animation ranges
  18163. * @param parsedNode defines the serialization object to read data from
  18164. * @param scene defines the hosting scene
  18165. */
  18166. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18167. if (parsedNode.ranges) {
  18168. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18169. var data = parsedNode.ranges[index];
  18170. node.createAnimationRange(data.name, data.from, data.to);
  18171. }
  18172. }
  18173. };
  18174. Node._NodeConstructors = {};
  18175. __decorate([
  18176. BABYLON.serialize()
  18177. ], Node.prototype, "name", void 0);
  18178. __decorate([
  18179. BABYLON.serialize()
  18180. ], Node.prototype, "id", void 0);
  18181. __decorate([
  18182. BABYLON.serialize()
  18183. ], Node.prototype, "uniqueId", void 0);
  18184. __decorate([
  18185. BABYLON.serialize()
  18186. ], Node.prototype, "state", void 0);
  18187. __decorate([
  18188. BABYLON.serialize()
  18189. ], Node.prototype, "metadata", void 0);
  18190. return Node;
  18191. }());
  18192. BABYLON.Node = Node;
  18193. })(BABYLON || (BABYLON = {}));
  18194. //# sourceMappingURL=babylon.node.js.map
  18195. var BABYLON;
  18196. (function (BABYLON) {
  18197. // This matrix is used as a value to reset the bounding box.
  18198. var _identityMatrix = BABYLON.Matrix.Identity();
  18199. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18200. var BoundingSphere = /** @class */ (function () {
  18201. /**
  18202. * Creates a new bounding sphere
  18203. * @param min defines the minimum vector (in local space)
  18204. * @param max defines the maximum vector (in local space)
  18205. */
  18206. function BoundingSphere(min, max) {
  18207. this.center = BABYLON.Vector3.Zero();
  18208. this.centerWorld = BABYLON.Vector3.Zero();
  18209. this.reConstruct(min, max);
  18210. }
  18211. /**
  18212. * Recreates the entire bounding sphere from scratch
  18213. * @param min defines the new minimum vector (in local space)
  18214. * @param max defines the new maximum vector (in local space)
  18215. */
  18216. BoundingSphere.prototype.reConstruct = function (min, max) {
  18217. this.minimum = min.clone();
  18218. this.maximum = max.clone();
  18219. var distance = BABYLON.Vector3.Distance(min, max);
  18220. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18221. this.radius = distance * 0.5;
  18222. this.centerWorld.set(0, 0, 0);
  18223. this._update(_identityMatrix);
  18224. };
  18225. /**
  18226. * Scale the current bounding sphere by applying a scale factor
  18227. * @param factor defines the scale factor to apply
  18228. * @returns the current bounding box
  18229. */
  18230. BoundingSphere.prototype.scale = function (factor) {
  18231. var newRadius = this.radius * factor;
  18232. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18233. var min = this.center.subtract(_tempRadiusVector);
  18234. var max = this.center.add(_tempRadiusVector);
  18235. this.reConstruct(min, max);
  18236. return this;
  18237. };
  18238. // Methods
  18239. /** @hidden */
  18240. BoundingSphere.prototype._update = function (world) {
  18241. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18242. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18243. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18244. };
  18245. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18246. for (var i = 0; i < 6; i++) {
  18247. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18248. return false;
  18249. }
  18250. return true;
  18251. };
  18252. BoundingSphere.prototype.intersectsPoint = function (point) {
  18253. var x = this.centerWorld.x - point.x;
  18254. var y = this.centerWorld.y - point.y;
  18255. var z = this.centerWorld.z - point.z;
  18256. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18257. if (this.radiusWorld < distance)
  18258. return false;
  18259. return true;
  18260. };
  18261. // Statics
  18262. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18263. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18264. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18265. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18266. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18267. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18268. return false;
  18269. return true;
  18270. };
  18271. return BoundingSphere;
  18272. }());
  18273. BABYLON.BoundingSphere = BoundingSphere;
  18274. })(BABYLON || (BABYLON = {}));
  18275. //# sourceMappingURL=babylon.boundingSphere.js.map
  18276. var BABYLON;
  18277. (function (BABYLON) {
  18278. var BoundingBox = /** @class */ (function () {
  18279. /**
  18280. * Creates a new bounding box
  18281. * @param min defines the minimum vector (in local space)
  18282. * @param max defines the maximum vector (in local space)
  18283. */
  18284. function BoundingBox(min, max) {
  18285. this.vectorsWorld = new Array();
  18286. this.reConstruct(min, max);
  18287. }
  18288. // Methods
  18289. /**
  18290. * Recreates the entire bounding box from scratch
  18291. * @param min defines the new minimum vector (in local space)
  18292. * @param max defines the new maximum vector (in local space)
  18293. */
  18294. BoundingBox.prototype.reConstruct = function (min, max) {
  18295. this.minimum = min.clone();
  18296. this.maximum = max.clone();
  18297. // Bounding vectors
  18298. this.vectors = [
  18299. this.minimum.clone(),
  18300. this.maximum.clone(),
  18301. this.minimum.clone(),
  18302. this.minimum.clone(),
  18303. this.minimum.clone(),
  18304. this.maximum.clone(),
  18305. this.maximum.clone(),
  18306. this.maximum.clone()
  18307. ];
  18308. this.vectors[2].x = this.maximum.x;
  18309. this.vectors[3].y = this.maximum.y;
  18310. this.vectors[4].z = this.maximum.z;
  18311. this.vectors[5].z = this.minimum.z;
  18312. this.vectors[6].x = this.minimum.x;
  18313. this.vectors[7].y = this.minimum.y;
  18314. // OBB
  18315. this.center = this.maximum.add(this.minimum).scale(0.5);
  18316. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18317. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18318. // World
  18319. for (var index = 0; index < this.vectors.length; index++) {
  18320. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18321. }
  18322. this.minimumWorld = BABYLON.Vector3.Zero();
  18323. this.maximumWorld = BABYLON.Vector3.Zero();
  18324. this.centerWorld = BABYLON.Vector3.Zero();
  18325. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18326. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18327. };
  18328. /**
  18329. * Scale the current bounding box by applying a scale factor
  18330. * @param factor defines the scale factor to apply
  18331. * @returns the current bounding box
  18332. */
  18333. BoundingBox.prototype.scale = function (factor) {
  18334. var diff = this.maximum.subtract(this.minimum);
  18335. var distance = diff.length() * factor;
  18336. diff.normalize();
  18337. var newRadius = diff.scale(distance / 2);
  18338. var min = this.center.subtract(newRadius);
  18339. var max = this.center.add(newRadius);
  18340. this.reConstruct(min, max);
  18341. return this;
  18342. };
  18343. BoundingBox.prototype.getWorldMatrix = function () {
  18344. return this._worldMatrix;
  18345. };
  18346. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18347. this._worldMatrix.copyFrom(matrix);
  18348. return this;
  18349. };
  18350. /** @hidden */
  18351. BoundingBox.prototype._update = function (world) {
  18352. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18353. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18354. for (var index = 0; index < this.vectors.length; index++) {
  18355. var v = this.vectorsWorld[index];
  18356. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18357. if (v.x < this.minimumWorld.x)
  18358. this.minimumWorld.x = v.x;
  18359. if (v.y < this.minimumWorld.y)
  18360. this.minimumWorld.y = v.y;
  18361. if (v.z < this.minimumWorld.z)
  18362. this.minimumWorld.z = v.z;
  18363. if (v.x > this.maximumWorld.x)
  18364. this.maximumWorld.x = v.x;
  18365. if (v.y > this.maximumWorld.y)
  18366. this.maximumWorld.y = v.y;
  18367. if (v.z > this.maximumWorld.z)
  18368. this.maximumWorld.z = v.z;
  18369. }
  18370. // Extend
  18371. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18372. this.extendSizeWorld.scaleInPlace(0.5);
  18373. // OBB
  18374. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18375. this.centerWorld.scaleInPlace(0.5);
  18376. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18377. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18378. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18379. this._worldMatrix = world;
  18380. };
  18381. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18382. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18383. };
  18384. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18385. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18386. };
  18387. BoundingBox.prototype.intersectsPoint = function (point) {
  18388. var delta = -BABYLON.Epsilon;
  18389. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18390. return false;
  18391. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18392. return false;
  18393. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18394. return false;
  18395. return true;
  18396. };
  18397. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18398. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18399. };
  18400. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18401. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18402. return false;
  18403. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18404. return false;
  18405. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18406. return false;
  18407. return true;
  18408. };
  18409. // Statics
  18410. BoundingBox.Intersects = function (box0, box1) {
  18411. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18412. return false;
  18413. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18414. return false;
  18415. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18416. return false;
  18417. return true;
  18418. };
  18419. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18420. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18421. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18422. return (num <= (sphereRadius * sphereRadius));
  18423. };
  18424. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18425. for (var p = 0; p < 6; p++) {
  18426. for (var i = 0; i < 8; i++) {
  18427. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18428. return false;
  18429. }
  18430. }
  18431. }
  18432. return true;
  18433. };
  18434. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18435. for (var p = 0; p < 6; p++) {
  18436. var inCount = 8;
  18437. for (var i = 0; i < 8; i++) {
  18438. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18439. --inCount;
  18440. }
  18441. else {
  18442. break;
  18443. }
  18444. }
  18445. if (inCount === 0)
  18446. return false;
  18447. }
  18448. return true;
  18449. };
  18450. return BoundingBox;
  18451. }());
  18452. BABYLON.BoundingBox = BoundingBox;
  18453. })(BABYLON || (BABYLON = {}));
  18454. //# sourceMappingURL=babylon.boundingBox.js.map
  18455. var BABYLON;
  18456. (function (BABYLON) {
  18457. var computeBoxExtents = function (axis, box) {
  18458. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18459. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18460. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18461. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18462. var r = r0 + r1 + r2;
  18463. return {
  18464. min: p - r,
  18465. max: p + r
  18466. };
  18467. };
  18468. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18469. var axisOverlap = function (axis, box0, box1) {
  18470. var result0 = computeBoxExtents(axis, box0);
  18471. var result1 = computeBoxExtents(axis, box1);
  18472. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18473. };
  18474. var BoundingInfo = /** @class */ (function () {
  18475. function BoundingInfo(minimum, maximum) {
  18476. this.minimum = minimum;
  18477. this.maximum = maximum;
  18478. this._isLocked = false;
  18479. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18480. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18481. }
  18482. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18483. get: function () {
  18484. return this._isLocked;
  18485. },
  18486. set: function (value) {
  18487. this._isLocked = value;
  18488. },
  18489. enumerable: true,
  18490. configurable: true
  18491. });
  18492. // Methods
  18493. BoundingInfo.prototype.update = function (world) {
  18494. if (this._isLocked) {
  18495. return;
  18496. }
  18497. this.boundingBox._update(world);
  18498. this.boundingSphere._update(world);
  18499. };
  18500. /**
  18501. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18502. * @param center New center of the bounding info
  18503. * @param extend New extend of the bounding info
  18504. */
  18505. BoundingInfo.prototype.centerOn = function (center, extend) {
  18506. this.minimum = center.subtract(extend);
  18507. this.maximum = center.add(extend);
  18508. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18509. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18510. return this;
  18511. };
  18512. /**
  18513. * Scale the current bounding info by applying a scale factor
  18514. * @param factor defines the scale factor to apply
  18515. * @returns the current bounding info
  18516. */
  18517. BoundingInfo.prototype.scale = function (factor) {
  18518. this.boundingBox.scale(factor);
  18519. this.boundingSphere.scale(factor);
  18520. return this;
  18521. };
  18522. /**
  18523. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18524. * @param frustumPlanes defines the frustum to test
  18525. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18526. * @returns true if the bounding info is in the frustum planes
  18527. */
  18528. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18529. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18530. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18531. return false;
  18532. }
  18533. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18534. return true;
  18535. }
  18536. return this.boundingBox.isInFrustum(frustumPlanes);
  18537. };
  18538. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18539. /**
  18540. * Gets the world distance between the min and max points of the bounding box
  18541. */
  18542. get: function () {
  18543. var boundingBox = this.boundingBox;
  18544. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18545. return size.length();
  18546. },
  18547. enumerable: true,
  18548. configurable: true
  18549. });
  18550. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18551. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18552. };
  18553. /** @hidden */
  18554. BoundingInfo.prototype._checkCollision = function (collider) {
  18555. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18556. };
  18557. BoundingInfo.prototype.intersectsPoint = function (point) {
  18558. if (!this.boundingSphere.centerWorld) {
  18559. return false;
  18560. }
  18561. if (!this.boundingSphere.intersectsPoint(point)) {
  18562. return false;
  18563. }
  18564. if (!this.boundingBox.intersectsPoint(point)) {
  18565. return false;
  18566. }
  18567. return true;
  18568. };
  18569. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18570. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18571. return false;
  18572. }
  18573. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18574. return false;
  18575. }
  18576. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18577. return false;
  18578. }
  18579. if (!precise) {
  18580. return true;
  18581. }
  18582. var box0 = this.boundingBox;
  18583. var box1 = boundingInfo.boundingBox;
  18584. if (!axisOverlap(box0.directions[0], box0, box1))
  18585. return false;
  18586. if (!axisOverlap(box0.directions[1], box0, box1))
  18587. return false;
  18588. if (!axisOverlap(box0.directions[2], box0, box1))
  18589. return false;
  18590. if (!axisOverlap(box1.directions[0], box0, box1))
  18591. return false;
  18592. if (!axisOverlap(box1.directions[1], box0, box1))
  18593. return false;
  18594. if (!axisOverlap(box1.directions[2], box0, box1))
  18595. return false;
  18596. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18597. return false;
  18598. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18599. return false;
  18600. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18601. return false;
  18602. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18603. return false;
  18604. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18605. return false;
  18606. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18607. return false;
  18608. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18609. return false;
  18610. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18611. return false;
  18612. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18613. return false;
  18614. return true;
  18615. };
  18616. return BoundingInfo;
  18617. }());
  18618. BABYLON.BoundingInfo = BoundingInfo;
  18619. })(BABYLON || (BABYLON = {}));
  18620. //# sourceMappingURL=babylon.boundingInfo.js.map
  18621. var BABYLON;
  18622. (function (BABYLON) {
  18623. var TransformNode = /** @class */ (function (_super) {
  18624. __extends(TransformNode, _super);
  18625. function TransformNode(name, scene, isPure) {
  18626. if (scene === void 0) { scene = null; }
  18627. if (isPure === void 0) { isPure = true; }
  18628. var _this = _super.call(this, name, scene) || this;
  18629. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18630. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18631. _this._up = new BABYLON.Vector3(0, 1, 0);
  18632. _this._right = new BABYLON.Vector3(1, 0, 0);
  18633. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18634. // Properties
  18635. _this._position = BABYLON.Vector3.Zero();
  18636. _this._rotation = BABYLON.Vector3.Zero();
  18637. _this._scaling = BABYLON.Vector3.One();
  18638. _this._isDirty = false;
  18639. /**
  18640. * Set the billboard mode. Default is 0.
  18641. *
  18642. * | Value | Type | Description |
  18643. * | --- | --- | --- |
  18644. * | 0 | BILLBOARDMODE_NONE | |
  18645. * | 1 | BILLBOARDMODE_X | |
  18646. * | 2 | BILLBOARDMODE_Y | |
  18647. * | 4 | BILLBOARDMODE_Z | |
  18648. * | 7 | BILLBOARDMODE_ALL | |
  18649. *
  18650. */
  18651. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18652. _this.scalingDeterminant = 1;
  18653. _this.infiniteDistance = false;
  18654. /**
  18655. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18656. * By default the system will update normals to compensate
  18657. */
  18658. _this.ignoreNonUniformScaling = false;
  18659. _this._localWorld = BABYLON.Matrix.Zero();
  18660. _this._absolutePosition = BABYLON.Vector3.Zero();
  18661. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18662. _this._postMultiplyPivotMatrix = false;
  18663. _this._isWorldMatrixFrozen = false;
  18664. /**
  18665. * An event triggered after the world matrix is updated
  18666. */
  18667. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18668. _this._nonUniformScaling = false;
  18669. if (isPure) {
  18670. _this.getScene().addTransformNode(_this);
  18671. }
  18672. return _this;
  18673. }
  18674. /**
  18675. * Gets a string identifying the name of the class
  18676. * @returns "TransformNode" string
  18677. */
  18678. TransformNode.prototype.getClassName = function () {
  18679. return "TransformNode";
  18680. };
  18681. Object.defineProperty(TransformNode.prototype, "position", {
  18682. /**
  18683. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  18684. */
  18685. get: function () {
  18686. return this._position;
  18687. },
  18688. set: function (newPosition) {
  18689. this._position = newPosition;
  18690. this._isDirty = true;
  18691. },
  18692. enumerable: true,
  18693. configurable: true
  18694. });
  18695. Object.defineProperty(TransformNode.prototype, "rotation", {
  18696. /**
  18697. * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  18698. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  18699. */
  18700. get: function () {
  18701. return this._rotation;
  18702. },
  18703. set: function (newRotation) {
  18704. this._rotation = newRotation;
  18705. this._isDirty = true;
  18706. },
  18707. enumerable: true,
  18708. configurable: true
  18709. });
  18710. Object.defineProperty(TransformNode.prototype, "scaling", {
  18711. /**
  18712. * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  18713. */
  18714. get: function () {
  18715. return this._scaling;
  18716. },
  18717. set: function (newScaling) {
  18718. this._scaling = newScaling;
  18719. this._isDirty = true;
  18720. },
  18721. enumerable: true,
  18722. configurable: true
  18723. });
  18724. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18725. /**
  18726. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  18727. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  18728. */
  18729. get: function () {
  18730. return this._rotationQuaternion;
  18731. },
  18732. set: function (quaternion) {
  18733. this._rotationQuaternion = quaternion;
  18734. //reset the rotation vector.
  18735. if (quaternion && this.rotation.length()) {
  18736. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18737. }
  18738. },
  18739. enumerable: true,
  18740. configurable: true
  18741. });
  18742. Object.defineProperty(TransformNode.prototype, "forward", {
  18743. /**
  18744. * The forward direction of that transform in world space.
  18745. */
  18746. get: function () {
  18747. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18748. },
  18749. enumerable: true,
  18750. configurable: true
  18751. });
  18752. Object.defineProperty(TransformNode.prototype, "up", {
  18753. /**
  18754. * The up direction of that transform in world space.
  18755. */
  18756. get: function () {
  18757. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18758. },
  18759. enumerable: true,
  18760. configurable: true
  18761. });
  18762. Object.defineProperty(TransformNode.prototype, "right", {
  18763. /**
  18764. * The right direction of that transform in world space.
  18765. */
  18766. get: function () {
  18767. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18768. },
  18769. enumerable: true,
  18770. configurable: true
  18771. });
  18772. /**
  18773. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18774. * Returns the TransformNode.
  18775. */
  18776. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18777. this._poseMatrix.copyFrom(matrix);
  18778. return this;
  18779. };
  18780. /**
  18781. * Returns the mesh Pose matrix.
  18782. * Returned object : Matrix
  18783. */
  18784. TransformNode.prototype.getPoseMatrix = function () {
  18785. return this._poseMatrix;
  18786. };
  18787. /** @hidden */
  18788. TransformNode.prototype._isSynchronized = function () {
  18789. if (this._isDirty) {
  18790. return false;
  18791. }
  18792. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18793. return false;
  18794. if (this._cache.pivotMatrixUpdated) {
  18795. return false;
  18796. }
  18797. if (this.infiniteDistance) {
  18798. return false;
  18799. }
  18800. if (!this._cache.position.equals(this._position))
  18801. return false;
  18802. if (this._rotationQuaternion) {
  18803. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18804. return false;
  18805. }
  18806. else if (!this._cache.rotation.equals(this._rotation))
  18807. return false;
  18808. if (!this._cache.scaling.equals(this._scaling))
  18809. return false;
  18810. return true;
  18811. };
  18812. /** @hidden */
  18813. TransformNode.prototype._initCache = function () {
  18814. _super.prototype._initCache.call(this);
  18815. this._cache.localMatrixUpdated = false;
  18816. this._cache.position = BABYLON.Vector3.Zero();
  18817. this._cache.scaling = BABYLON.Vector3.Zero();
  18818. this._cache.rotation = BABYLON.Vector3.Zero();
  18819. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18820. this._cache.billboardMode = -1;
  18821. };
  18822. TransformNode.prototype.markAsDirty = function (property) {
  18823. if (property === "rotation") {
  18824. this.rotationQuaternion = null;
  18825. }
  18826. this._currentRenderId = Number.MAX_VALUE;
  18827. this._isDirty = true;
  18828. return this;
  18829. };
  18830. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18831. /**
  18832. * Returns the current mesh absolute position.
  18833. * Returns a Vector3.
  18834. */
  18835. get: function () {
  18836. return this._absolutePosition;
  18837. },
  18838. enumerable: true,
  18839. configurable: true
  18840. });
  18841. /**
  18842. * Sets a new matrix to apply before all other transformation
  18843. * @param matrix defines the transform matrix
  18844. * @returns the current TransformNode
  18845. */
  18846. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18847. return this.setPivotMatrix(matrix, false);
  18848. };
  18849. /**
  18850. * Sets a new pivot matrix to the current node
  18851. * @param matrix defines the new pivot matrix to use
  18852. * @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
  18853. * @returns the current TransformNode
  18854. */
  18855. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18856. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18857. this._pivotMatrix = matrix.clone();
  18858. this._cache.pivotMatrixUpdated = true;
  18859. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18860. if (this._postMultiplyPivotMatrix) {
  18861. if (!this._pivotMatrixInverse) {
  18862. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18863. }
  18864. else {
  18865. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18866. }
  18867. }
  18868. return this;
  18869. };
  18870. /**
  18871. * Returns the mesh pivot matrix.
  18872. * Default : Identity.
  18873. * A Matrix is returned.
  18874. */
  18875. TransformNode.prototype.getPivotMatrix = function () {
  18876. return this._pivotMatrix;
  18877. };
  18878. /**
  18879. * Prevents the World matrix to be computed any longer.
  18880. * Returns the TransformNode.
  18881. */
  18882. TransformNode.prototype.freezeWorldMatrix = function () {
  18883. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18884. this.computeWorldMatrix(true);
  18885. this._isWorldMatrixFrozen = true;
  18886. return this;
  18887. };
  18888. /**
  18889. * Allows back the World matrix computation.
  18890. * Returns the TransformNode.
  18891. */
  18892. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18893. this._isWorldMatrixFrozen = false;
  18894. this.computeWorldMatrix(true);
  18895. return this;
  18896. };
  18897. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18898. /**
  18899. * True if the World matrix has been frozen.
  18900. * Returns a boolean.
  18901. */
  18902. get: function () {
  18903. return this._isWorldMatrixFrozen;
  18904. },
  18905. enumerable: true,
  18906. configurable: true
  18907. });
  18908. /**
  18909. * Retuns the mesh absolute position in the World.
  18910. * Returns a Vector3.
  18911. */
  18912. TransformNode.prototype.getAbsolutePosition = function () {
  18913. this.computeWorldMatrix();
  18914. return this._absolutePosition;
  18915. };
  18916. /**
  18917. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18918. * Returns the TransformNode.
  18919. */
  18920. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18921. if (!absolutePosition) {
  18922. return this;
  18923. }
  18924. var absolutePositionX;
  18925. var absolutePositionY;
  18926. var absolutePositionZ;
  18927. if (absolutePosition.x === undefined) {
  18928. if (arguments.length < 3) {
  18929. return this;
  18930. }
  18931. absolutePositionX = arguments[0];
  18932. absolutePositionY = arguments[1];
  18933. absolutePositionZ = arguments[2];
  18934. }
  18935. else {
  18936. absolutePositionX = absolutePosition.x;
  18937. absolutePositionY = absolutePosition.y;
  18938. absolutePositionZ = absolutePosition.z;
  18939. }
  18940. if (this.parent) {
  18941. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18942. invertParentWorldMatrix.invert();
  18943. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18944. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18945. }
  18946. else {
  18947. this.position.x = absolutePositionX;
  18948. this.position.y = absolutePositionY;
  18949. this.position.z = absolutePositionZ;
  18950. }
  18951. return this;
  18952. };
  18953. /**
  18954. * Sets the mesh position in its local space.
  18955. * Returns the TransformNode.
  18956. */
  18957. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18958. this.computeWorldMatrix();
  18959. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18960. return this;
  18961. };
  18962. /**
  18963. * Returns the mesh position in the local space from the current World matrix values.
  18964. * Returns a new Vector3.
  18965. */
  18966. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18967. this.computeWorldMatrix();
  18968. var invLocalWorldMatrix = this._localWorld.clone();
  18969. invLocalWorldMatrix.invert();
  18970. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18971. };
  18972. /**
  18973. * Translates the mesh along the passed Vector3 in its local space.
  18974. * Returns the TransformNode.
  18975. */
  18976. TransformNode.prototype.locallyTranslate = function (vector3) {
  18977. this.computeWorldMatrix(true);
  18978. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18979. return this;
  18980. };
  18981. /**
  18982. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18983. * @param targetPoint the position (must be in same space as current mesh) to look at
  18984. * @param yawCor optional yaw (y-axis) correction in radians
  18985. * @param pitchCor optional pitch (x-axis) correction in radians
  18986. * @param rollCor optional roll (z-axis) correction in radians
  18987. * @param space the choosen space of the target
  18988. * @returns the TransformNode.
  18989. */
  18990. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18991. if (yawCor === void 0) { yawCor = 0; }
  18992. if (pitchCor === void 0) { pitchCor = 0; }
  18993. if (rollCor === void 0) { rollCor = 0; }
  18994. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18995. var dv = TransformNode._lookAtVectorCache;
  18996. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18997. targetPoint.subtractToRef(pos, dv);
  18998. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18999. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19000. var pitch = Math.atan2(dv.y, len);
  19001. if (this.rotationQuaternion) {
  19002. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19003. }
  19004. else {
  19005. this.rotation.x = pitch + pitchCor;
  19006. this.rotation.y = yaw + yawCor;
  19007. this.rotation.z = rollCor;
  19008. }
  19009. return this;
  19010. };
  19011. /**
  19012. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19013. * This Vector3 is expressed in the World space.
  19014. */
  19015. TransformNode.prototype.getDirection = function (localAxis) {
  19016. var result = BABYLON.Vector3.Zero();
  19017. this.getDirectionToRef(localAxis, result);
  19018. return result;
  19019. };
  19020. /**
  19021. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19022. * localAxis is expressed in the mesh local space.
  19023. * result is computed in the Wordl space from the mesh World matrix.
  19024. * Returns the TransformNode.
  19025. */
  19026. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19027. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19028. return this;
  19029. };
  19030. /**
  19031. * Sets a new pivot point to the current node
  19032. * @param point defines the new pivot point to use
  19033. * @param space defines if the point is in world or local space (local by default)
  19034. * @returns the current TransformNode
  19035. */
  19036. TransformNode.prototype.setPivotPoint = function (point, space) {
  19037. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19038. if (this.getScene().getRenderId() == 0) {
  19039. this.computeWorldMatrix(true);
  19040. }
  19041. var wm = this.getWorldMatrix();
  19042. if (space == BABYLON.Space.WORLD) {
  19043. var tmat = BABYLON.Tmp.Matrix[0];
  19044. wm.invertToRef(tmat);
  19045. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19046. }
  19047. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19048. };
  19049. /**
  19050. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19051. */
  19052. TransformNode.prototype.getPivotPoint = function () {
  19053. var point = BABYLON.Vector3.Zero();
  19054. this.getPivotPointToRef(point);
  19055. return point;
  19056. };
  19057. /**
  19058. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19059. * Returns the TransformNode.
  19060. */
  19061. TransformNode.prototype.getPivotPointToRef = function (result) {
  19062. result.x = -this._pivotMatrix.m[12];
  19063. result.y = -this._pivotMatrix.m[13];
  19064. result.z = -this._pivotMatrix.m[14];
  19065. return this;
  19066. };
  19067. /**
  19068. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19069. */
  19070. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19071. var point = BABYLON.Vector3.Zero();
  19072. this.getAbsolutePivotPointToRef(point);
  19073. return point;
  19074. };
  19075. /**
  19076. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19077. * Returns the TransformNode.
  19078. */
  19079. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19080. result.x = this._pivotMatrix.m[12];
  19081. result.y = this._pivotMatrix.m[13];
  19082. result.z = this._pivotMatrix.m[14];
  19083. this.getPivotPointToRef(result);
  19084. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19085. return this;
  19086. };
  19087. /**
  19088. * Defines the passed node as the parent of the current node.
  19089. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19090. * Returns the TransformNode.
  19091. */
  19092. TransformNode.prototype.setParent = function (node) {
  19093. if (!node && !this.parent) {
  19094. return this;
  19095. }
  19096. if (!node) {
  19097. var rotation = BABYLON.Tmp.Quaternion[0];
  19098. var position = BABYLON.Tmp.Vector3[0];
  19099. var scale = BABYLON.Tmp.Vector3[1];
  19100. if (this.parent && this.parent.computeWorldMatrix) {
  19101. this.parent.computeWorldMatrix(true);
  19102. }
  19103. this.computeWorldMatrix(true);
  19104. this.getWorldMatrix().decompose(scale, rotation, position);
  19105. if (this.rotationQuaternion) {
  19106. this.rotationQuaternion.copyFrom(rotation);
  19107. }
  19108. else {
  19109. rotation.toEulerAnglesToRef(this.rotation);
  19110. }
  19111. this.scaling.x = scale.x;
  19112. this.scaling.y = scale.y;
  19113. this.scaling.z = scale.z;
  19114. this.position.x = position.x;
  19115. this.position.y = position.y;
  19116. this.position.z = position.z;
  19117. }
  19118. else {
  19119. var rotation = BABYLON.Tmp.Quaternion[0];
  19120. var position = BABYLON.Tmp.Vector3[0];
  19121. var scale = BABYLON.Tmp.Vector3[1];
  19122. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19123. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19124. this.computeWorldMatrix(true);
  19125. node.computeWorldMatrix(true);
  19126. node.getWorldMatrix().invertToRef(invParentMatrix);
  19127. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19128. diffMatrix.decompose(scale, rotation, position);
  19129. if (this.rotationQuaternion) {
  19130. this.rotationQuaternion.copyFrom(rotation);
  19131. }
  19132. else {
  19133. rotation.toEulerAnglesToRef(this.rotation);
  19134. }
  19135. this.position.x = position.x;
  19136. this.position.y = position.y;
  19137. this.position.z = position.z;
  19138. this.scaling.x = scale.x;
  19139. this.scaling.y = scale.y;
  19140. this.scaling.z = scale.z;
  19141. }
  19142. this.parent = node;
  19143. return this;
  19144. };
  19145. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19146. get: function () {
  19147. return this._nonUniformScaling;
  19148. },
  19149. enumerable: true,
  19150. configurable: true
  19151. });
  19152. /** @hidden */
  19153. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19154. if (this._nonUniformScaling === value) {
  19155. return false;
  19156. }
  19157. this._nonUniformScaling = value;
  19158. return true;
  19159. };
  19160. /**
  19161. * Attach the current TransformNode to another TransformNode associated with a bone
  19162. * @param bone Bone affecting the TransformNode
  19163. * @param affectedTransformNode TransformNode associated with the bone
  19164. */
  19165. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19166. this._transformToBoneReferal = affectedTransformNode;
  19167. this.parent = bone;
  19168. if (bone.getWorldMatrix().determinant() < 0) {
  19169. this.scalingDeterminant *= -1;
  19170. }
  19171. return this;
  19172. };
  19173. TransformNode.prototype.detachFromBone = function () {
  19174. if (!this.parent) {
  19175. return this;
  19176. }
  19177. if (this.parent.getWorldMatrix().determinant() < 0) {
  19178. this.scalingDeterminant *= -1;
  19179. }
  19180. this._transformToBoneReferal = null;
  19181. this.parent = null;
  19182. return this;
  19183. };
  19184. /**
  19185. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19186. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19187. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19188. * The passed axis is also normalized.
  19189. * Returns the TransformNode.
  19190. */
  19191. TransformNode.prototype.rotate = function (axis, amount, space) {
  19192. axis.normalize();
  19193. if (!this.rotationQuaternion) {
  19194. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19195. this.rotation = BABYLON.Vector3.Zero();
  19196. }
  19197. var rotationQuaternion;
  19198. if (!space || space === BABYLON.Space.LOCAL) {
  19199. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19200. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19201. }
  19202. else {
  19203. if (this.parent) {
  19204. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19205. invertParentWorldMatrix.invert();
  19206. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19207. }
  19208. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19209. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19210. }
  19211. return this;
  19212. };
  19213. /**
  19214. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19215. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19216. * The passed axis is also normalized.
  19217. * Returns the TransformNode.
  19218. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19219. */
  19220. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19221. axis.normalize();
  19222. if (!this.rotationQuaternion) {
  19223. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19224. this.rotation.copyFromFloats(0, 0, 0);
  19225. }
  19226. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19227. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19228. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19229. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19230. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19231. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19232. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19233. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19234. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19235. return this;
  19236. };
  19237. /**
  19238. * Translates the mesh along the axis vector for the passed distance in the given space.
  19239. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19240. * Returns the TransformNode.
  19241. */
  19242. TransformNode.prototype.translate = function (axis, distance, space) {
  19243. var displacementVector = axis.scale(distance);
  19244. if (!space || space === BABYLON.Space.LOCAL) {
  19245. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19246. this.setPositionWithLocalVector(tempV3);
  19247. }
  19248. else {
  19249. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19250. }
  19251. return this;
  19252. };
  19253. /**
  19254. * Adds a rotation step to the mesh current rotation.
  19255. * x, y, z are Euler angles expressed in radians.
  19256. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19257. * This means this rotation is made in the mesh local space only.
  19258. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19259. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19260. * ```javascript
  19261. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19262. * ```
  19263. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19264. * 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.
  19265. * Returns the TransformNode.
  19266. */
  19267. TransformNode.prototype.addRotation = function (x, y, z) {
  19268. var rotationQuaternion;
  19269. if (this.rotationQuaternion) {
  19270. rotationQuaternion = this.rotationQuaternion;
  19271. }
  19272. else {
  19273. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19274. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19275. }
  19276. var accumulation = BABYLON.Tmp.Quaternion[0];
  19277. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19278. rotationQuaternion.multiplyInPlace(accumulation);
  19279. if (!this.rotationQuaternion) {
  19280. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19281. }
  19282. return this;
  19283. };
  19284. /**
  19285. * Computes the world matrix of the node
  19286. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19287. * @returns the world matrix
  19288. */
  19289. TransformNode.prototype.computeWorldMatrix = function (force) {
  19290. if (this._isWorldMatrixFrozen) {
  19291. return this._worldMatrix;
  19292. }
  19293. if (!force && this.isSynchronized()) {
  19294. this._currentRenderId = this.getScene().getRenderId();
  19295. return this._worldMatrix;
  19296. }
  19297. this._updateCache();
  19298. this._cache.position.copyFrom(this.position);
  19299. this._cache.scaling.copyFrom(this.scaling);
  19300. this._cache.pivotMatrixUpdated = false;
  19301. this._cache.billboardMode = this.billboardMode;
  19302. this._currentRenderId = this.getScene().getRenderId();
  19303. this._childRenderId = this.getScene().getRenderId();
  19304. this._isDirty = false;
  19305. // Scaling
  19306. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19307. // Rotation
  19308. //rotate, if quaternion is set and rotation was used
  19309. if (this.rotationQuaternion) {
  19310. var len = this.rotation.length();
  19311. if (len) {
  19312. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19313. this.rotation.copyFromFloats(0, 0, 0);
  19314. }
  19315. }
  19316. if (this.rotationQuaternion) {
  19317. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19318. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19319. }
  19320. else {
  19321. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19322. this._cache.rotation.copyFrom(this.rotation);
  19323. }
  19324. // Translation
  19325. var camera = this.getScene().activeCamera;
  19326. if (this.infiniteDistance && !this.parent && camera) {
  19327. var cameraWorldMatrix = camera.getWorldMatrix();
  19328. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19329. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19330. }
  19331. else {
  19332. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19333. }
  19334. // Composing transformations
  19335. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19336. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19337. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19338. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19339. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19340. // Need to decompose each rotation here
  19341. var currentPosition = BABYLON.Tmp.Vector3[3];
  19342. if (this.parent && this.parent.getWorldMatrix) {
  19343. if (this._transformToBoneReferal) {
  19344. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19345. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19346. }
  19347. else {
  19348. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19349. }
  19350. }
  19351. else {
  19352. currentPosition.copyFrom(this.position);
  19353. }
  19354. currentPosition.subtractInPlace(camera.globalPosition);
  19355. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19356. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19357. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19358. }
  19359. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19360. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19361. }
  19362. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19363. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19364. }
  19365. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19366. }
  19367. else {
  19368. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19369. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19370. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19371. }
  19372. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19373. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19374. }
  19375. // Post multiply inverse of pivotMatrix
  19376. if (this._postMultiplyPivotMatrix) {
  19377. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19378. }
  19379. // Local world
  19380. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19381. // Parent
  19382. if (this.parent && this.parent.getWorldMatrix) {
  19383. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19384. if (this._transformToBoneReferal) {
  19385. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19386. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19387. }
  19388. else {
  19389. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19390. }
  19391. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19392. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19393. this._worldMatrix.copyFrom(this._localWorld);
  19394. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19395. }
  19396. else {
  19397. if (this._transformToBoneReferal) {
  19398. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19399. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19400. }
  19401. else {
  19402. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19403. }
  19404. }
  19405. this._markSyncedWithParent();
  19406. }
  19407. else {
  19408. this._worldMatrix.copyFrom(this._localWorld);
  19409. }
  19410. // Normal matrix
  19411. if (!this.ignoreNonUniformScaling) {
  19412. if (this.scaling.isNonUniform) {
  19413. this._updateNonUniformScalingState(true);
  19414. }
  19415. else if (this.parent && this.parent._nonUniformScaling) {
  19416. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19417. }
  19418. else {
  19419. this._updateNonUniformScalingState(false);
  19420. }
  19421. }
  19422. else {
  19423. this._updateNonUniformScalingState(false);
  19424. }
  19425. this._afterComputeWorldMatrix();
  19426. // Absolute position
  19427. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19428. // Callbacks
  19429. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19430. if (!this._poseMatrix) {
  19431. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19432. }
  19433. // Cache the determinant
  19434. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19435. return this._worldMatrix;
  19436. };
  19437. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19438. };
  19439. /**
  19440. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19441. * @param func: callback function to add
  19442. *
  19443. * Returns the TransformNode.
  19444. */
  19445. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19446. this.onAfterWorldMatrixUpdateObservable.add(func);
  19447. return this;
  19448. };
  19449. /**
  19450. * Removes a registered callback function.
  19451. * Returns the TransformNode.
  19452. */
  19453. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19454. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19455. return this;
  19456. };
  19457. /**
  19458. * Clone the current transform node
  19459. * Returns the new transform node
  19460. * @param name Name of the new clone
  19461. * @param newParent New parent for the clone
  19462. * @param doNotCloneChildren Do not clone children hierarchy
  19463. */
  19464. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19465. var _this = this;
  19466. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19467. result.name = name;
  19468. result.id = name;
  19469. if (newParent) {
  19470. result.parent = newParent;
  19471. }
  19472. if (!doNotCloneChildren) {
  19473. // Children
  19474. var directDescendants = this.getDescendants(true);
  19475. for (var index = 0; index < directDescendants.length; index++) {
  19476. var child = directDescendants[index];
  19477. if (child.clone) {
  19478. child.clone(name + "." + child.name, result);
  19479. }
  19480. }
  19481. }
  19482. return result;
  19483. };
  19484. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19485. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19486. serializationObject.type = this.getClassName();
  19487. // Parent
  19488. if (this.parent) {
  19489. serializationObject.parentId = this.parent.id;
  19490. }
  19491. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19492. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19493. }
  19494. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19495. serializationObject.isEnabled = this.isEnabled();
  19496. // Parent
  19497. if (this.parent) {
  19498. serializationObject.parentId = this.parent.id;
  19499. }
  19500. return serializationObject;
  19501. };
  19502. // Statics
  19503. /**
  19504. * Returns a new TransformNode object parsed from the source provided.
  19505. * The parameter `parsedMesh` is the source.
  19506. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19507. */
  19508. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19509. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19510. if (BABYLON.Tags) {
  19511. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19512. }
  19513. if (parsedTransformNode.localMatrix) {
  19514. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19515. }
  19516. else if (parsedTransformNode.pivotMatrix) {
  19517. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19518. }
  19519. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19520. // Parent
  19521. if (parsedTransformNode.parentId) {
  19522. transformNode._waitingParentId = parsedTransformNode.parentId;
  19523. }
  19524. return transformNode;
  19525. };
  19526. /**
  19527. * Releases resources associated with this transform node.
  19528. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19529. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19530. */
  19531. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19532. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19533. // Animations
  19534. this.getScene().stopAnimation(this);
  19535. // Remove from scene
  19536. this.getScene().removeTransformNode(this);
  19537. this.onAfterWorldMatrixUpdateObservable.clear();
  19538. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19539. };
  19540. // Statics
  19541. TransformNode.BILLBOARDMODE_NONE = 0;
  19542. TransformNode.BILLBOARDMODE_X = 1;
  19543. TransformNode.BILLBOARDMODE_Y = 2;
  19544. TransformNode.BILLBOARDMODE_Z = 4;
  19545. TransformNode.BILLBOARDMODE_ALL = 7;
  19546. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19547. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19548. __decorate([
  19549. BABYLON.serializeAsVector3("position")
  19550. ], TransformNode.prototype, "_position", void 0);
  19551. __decorate([
  19552. BABYLON.serializeAsVector3("rotation")
  19553. ], TransformNode.prototype, "_rotation", void 0);
  19554. __decorate([
  19555. BABYLON.serializeAsQuaternion("rotationQuaternion")
  19556. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19557. __decorate([
  19558. BABYLON.serializeAsVector3("scaling")
  19559. ], TransformNode.prototype, "_scaling", void 0);
  19560. __decorate([
  19561. BABYLON.serialize()
  19562. ], TransformNode.prototype, "billboardMode", void 0);
  19563. __decorate([
  19564. BABYLON.serialize()
  19565. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19566. __decorate([
  19567. BABYLON.serialize()
  19568. ], TransformNode.prototype, "infiniteDistance", void 0);
  19569. __decorate([
  19570. BABYLON.serialize()
  19571. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19572. return TransformNode;
  19573. }(BABYLON.Node));
  19574. BABYLON.TransformNode = TransformNode;
  19575. })(BABYLON || (BABYLON = {}));
  19576. //# sourceMappingURL=babylon.transformNode.js.map
  19577. var BABYLON;
  19578. (function (BABYLON) {
  19579. /**
  19580. * Class used to store all common mesh properties
  19581. */
  19582. var AbstractMesh = /** @class */ (function (_super) {
  19583. __extends(AbstractMesh, _super);
  19584. // Constructor
  19585. /**
  19586. * Creates a new AbstractMesh
  19587. * @param name defines the name of the mesh
  19588. * @param scene defines the hosting scene
  19589. */
  19590. function AbstractMesh(name, scene) {
  19591. if (scene === void 0) { scene = null; }
  19592. var _this = _super.call(this, name, scene, false) || this;
  19593. _this._facetNb = 0; // facet number
  19594. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19595. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19596. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19597. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19598. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19599. _this._subDiv = {
  19600. max: 1,
  19601. X: 1,
  19602. Y: 1,
  19603. Z: 1
  19604. };
  19605. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19606. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19607. /** Gets ot sets the culling strategy to use to find visible meshes */
  19608. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19609. // Events
  19610. /**
  19611. * An event triggered when this mesh collides with another one
  19612. */
  19613. _this.onCollideObservable = new BABYLON.Observable();
  19614. /**
  19615. * An event triggered when the collision's position changes
  19616. */
  19617. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19618. /**
  19619. * An event triggered when material is changed
  19620. */
  19621. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19622. // Properties
  19623. /**
  19624. * Gets or sets the orientation for POV movement & rotation
  19625. */
  19626. _this.definedFacingForward = true;
  19627. /**
  19628. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19629. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19630. * * 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.
  19631. * @see http://doc.babylonjs.com/features/occlusionquery
  19632. */
  19633. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19634. /**
  19635. * 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:
  19636. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19637. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19638. * * 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.
  19639. * @see http://doc.babylonjs.com/features/occlusionquery
  19640. */
  19641. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19642. /**
  19643. * 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.
  19644. * The default value is -1 which means don't break the query and wait till the result
  19645. * @see http://doc.babylonjs.com/features/occlusionquery
  19646. */
  19647. _this.occlusionRetryCount = -1;
  19648. /** @hidden */
  19649. _this._occlusionInternalRetryCounter = 0;
  19650. /** @hidden */
  19651. _this._isOccluded = false;
  19652. /** @hidden */
  19653. _this._isOcclusionQueryInProgress = false;
  19654. _this._visibility = 1.0;
  19655. /** Gets or sets the alpha index used to sort transparent meshes
  19656. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19657. */
  19658. _this.alphaIndex = Number.MAX_VALUE;
  19659. /**
  19660. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19661. */
  19662. _this.isVisible = true;
  19663. /**
  19664. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19665. */
  19666. _this.isPickable = true;
  19667. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19668. _this.showSubMeshesBoundingBox = false;
  19669. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19670. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19671. */
  19672. _this.isBlocker = false;
  19673. /**
  19674. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19675. */
  19676. _this.enablePointerMoveEvents = false;
  19677. /**
  19678. * Specifies the rendering group id for this mesh (0 by default)
  19679. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19680. */
  19681. _this.renderingGroupId = 0;
  19682. _this._receiveShadows = false;
  19683. /** Defines color to use when rendering outline */
  19684. _this.outlineColor = BABYLON.Color3.Red();
  19685. /** Define width to use when rendering outline */
  19686. _this.outlineWidth = 0.02;
  19687. /** Defines color to use when rendering overlay */
  19688. _this.overlayColor = BABYLON.Color3.Red();
  19689. /** Defines alpha to use when rendering overlay */
  19690. _this.overlayAlpha = 0.5;
  19691. _this._hasVertexAlpha = false;
  19692. _this._useVertexColors = true;
  19693. _this._computeBonesUsingShaders = true;
  19694. _this._numBoneInfluencers = 4;
  19695. _this._applyFog = true;
  19696. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19697. _this.useOctreeForRenderingSelection = true;
  19698. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19699. _this.useOctreeForPicking = true;
  19700. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19701. _this.useOctreeForCollisions = true;
  19702. _this._layerMask = 0x0FFFFFFF;
  19703. /**
  19704. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19705. */
  19706. _this.alwaysSelectAsActiveMesh = false;
  19707. /**
  19708. * Gets or sets the current action manager
  19709. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19710. */
  19711. _this.actionManager = null;
  19712. // Collisions
  19713. _this._checkCollisions = false;
  19714. _this._collisionMask = -1;
  19715. _this._collisionGroup = -1;
  19716. /**
  19717. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19718. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19719. */
  19720. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19721. /**
  19722. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19723. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19724. */
  19725. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19726. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19727. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19728. // Edges
  19729. /**
  19730. * Defines edge width used when edgesRenderer is enabled
  19731. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19732. */
  19733. _this.edgesWidth = 1;
  19734. /**
  19735. * Defines edge color used when edgesRenderer is enabled
  19736. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19737. */
  19738. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19739. // Cache
  19740. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19741. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19742. /** @hidden */
  19743. _this._renderId = 0;
  19744. /** @hidden */
  19745. _this._intersectionsInProgress = new Array();
  19746. /** @hidden */
  19747. _this._unIndexed = false;
  19748. /** @hidden */
  19749. _this._lightSources = new Array();
  19750. /**
  19751. * An event triggered when the mesh is rebuilt.
  19752. */
  19753. _this.onRebuildObservable = new BABYLON.Observable();
  19754. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19755. if (collidedMesh === void 0) { collidedMesh = null; }
  19756. //TODO move this to the collision coordinator!
  19757. if (_this.getScene().workerCollisions)
  19758. newPosition.multiplyInPlace(_this._collider._radius);
  19759. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19760. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19761. _this.position.addInPlace(_this._diffPositionForCollisions);
  19762. }
  19763. if (collidedMesh) {
  19764. _this.onCollideObservable.notifyObservers(collidedMesh);
  19765. }
  19766. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19767. };
  19768. _this.getScene().addMesh(_this);
  19769. _this._resyncLightSources();
  19770. return _this;
  19771. }
  19772. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19773. /**
  19774. * No billboard
  19775. */
  19776. get: function () {
  19777. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19778. },
  19779. enumerable: true,
  19780. configurable: true
  19781. });
  19782. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19783. /** Billboard on X axis */
  19784. get: function () {
  19785. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19786. },
  19787. enumerable: true,
  19788. configurable: true
  19789. });
  19790. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19791. /** Billboard on Y axis */
  19792. get: function () {
  19793. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19794. },
  19795. enumerable: true,
  19796. configurable: true
  19797. });
  19798. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19799. /** Billboard on Z axis */
  19800. get: function () {
  19801. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19802. },
  19803. enumerable: true,
  19804. configurable: true
  19805. });
  19806. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19807. /** Billboard on all axes */
  19808. get: function () {
  19809. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19815. /**
  19816. * Gets the number of facets in the mesh
  19817. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19818. */
  19819. get: function () {
  19820. return this._facetNb;
  19821. },
  19822. enumerable: true,
  19823. configurable: true
  19824. });
  19825. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19826. /**
  19827. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19828. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19829. */
  19830. get: function () {
  19831. return this._partitioningSubdivisions;
  19832. },
  19833. set: function (nb) {
  19834. this._partitioningSubdivisions = nb;
  19835. },
  19836. enumerable: true,
  19837. configurable: true
  19838. });
  19839. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19840. /**
  19841. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19842. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19843. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19844. */
  19845. get: function () {
  19846. return this._partitioningBBoxRatio;
  19847. },
  19848. set: function (ratio) {
  19849. this._partitioningBBoxRatio = ratio;
  19850. },
  19851. enumerable: true,
  19852. configurable: true
  19853. });
  19854. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19855. /**
  19856. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19857. * Works only for updatable meshes.
  19858. * Doesn't work with multi-materials
  19859. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19860. */
  19861. get: function () {
  19862. return this._facetDepthSort;
  19863. },
  19864. set: function (sort) {
  19865. this._facetDepthSort = sort;
  19866. },
  19867. enumerable: true,
  19868. configurable: true
  19869. });
  19870. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19871. /**
  19872. * The location (Vector3) where the facet depth sort must be computed from.
  19873. * By default, the active camera position.
  19874. * Used only when facet depth sort is enabled
  19875. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19876. */
  19877. get: function () {
  19878. return this._facetDepthSortFrom;
  19879. },
  19880. set: function (location) {
  19881. this._facetDepthSortFrom = location;
  19882. },
  19883. enumerable: true,
  19884. configurable: true
  19885. });
  19886. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19887. /**
  19888. * gets a boolean indicating if facetData is enabled
  19889. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19890. */
  19891. get: function () {
  19892. return this._facetDataEnabled;
  19893. },
  19894. enumerable: true,
  19895. configurable: true
  19896. });
  19897. /** @hidden */
  19898. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19899. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19900. return false;
  19901. }
  19902. this._markSubMeshesAsMiscDirty();
  19903. return true;
  19904. };
  19905. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19906. /** Set a function to call when this mesh collides with another one */
  19907. set: function (callback) {
  19908. if (this._onCollideObserver) {
  19909. this.onCollideObservable.remove(this._onCollideObserver);
  19910. }
  19911. this._onCollideObserver = this.onCollideObservable.add(callback);
  19912. },
  19913. enumerable: true,
  19914. configurable: true
  19915. });
  19916. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19917. /** Set a function to call when the collision's position changes */
  19918. set: function (callback) {
  19919. if (this._onCollisionPositionChangeObserver) {
  19920. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19921. }
  19922. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19923. },
  19924. enumerable: true,
  19925. configurable: true
  19926. });
  19927. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19928. /**
  19929. * 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
  19930. * @see http://doc.babylonjs.com/features/occlusionquery
  19931. */
  19932. get: function () {
  19933. return this._isOccluded;
  19934. },
  19935. set: function (value) {
  19936. this._isOccluded = value;
  19937. },
  19938. enumerable: true,
  19939. configurable: true
  19940. });
  19941. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19942. /**
  19943. * Flag to check the progress status of the query
  19944. * @see http://doc.babylonjs.com/features/occlusionquery
  19945. */
  19946. get: function () {
  19947. return this._isOcclusionQueryInProgress;
  19948. },
  19949. enumerable: true,
  19950. configurable: true
  19951. });
  19952. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19953. /**
  19954. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19955. */
  19956. get: function () {
  19957. return this._visibility;
  19958. },
  19959. /**
  19960. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19961. */
  19962. set: function (value) {
  19963. if (this._visibility === value) {
  19964. return;
  19965. }
  19966. this._visibility = value;
  19967. this._markSubMeshesAsMiscDirty();
  19968. },
  19969. enumerable: true,
  19970. configurable: true
  19971. });
  19972. Object.defineProperty(AbstractMesh.prototype, "material", {
  19973. /** Gets or sets current material */
  19974. get: function () {
  19975. return this._material;
  19976. },
  19977. set: function (value) {
  19978. if (this._material === value) {
  19979. return;
  19980. }
  19981. this._material = value;
  19982. if (this.onMaterialChangedObservable.hasObservers) {
  19983. this.onMaterialChangedObservable.notifyObservers(this);
  19984. }
  19985. if (!this.subMeshes) {
  19986. return;
  19987. }
  19988. this._unBindEffect();
  19989. },
  19990. enumerable: true,
  19991. configurable: true
  19992. });
  19993. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19994. /**
  19995. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19996. * @see http://doc.babylonjs.com/babylon101/shadows
  19997. */
  19998. get: function () {
  19999. return this._receiveShadows;
  20000. },
  20001. set: function (value) {
  20002. if (this._receiveShadows === value) {
  20003. return;
  20004. }
  20005. this._receiveShadows = value;
  20006. this._markSubMeshesAsLightDirty();
  20007. },
  20008. enumerable: true,
  20009. configurable: true
  20010. });
  20011. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20012. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20013. get: function () {
  20014. return this._hasVertexAlpha;
  20015. },
  20016. set: function (value) {
  20017. if (this._hasVertexAlpha === value) {
  20018. return;
  20019. }
  20020. this._hasVertexAlpha = value;
  20021. this._markSubMeshesAsAttributesDirty();
  20022. this._markSubMeshesAsMiscDirty();
  20023. },
  20024. enumerable: true,
  20025. configurable: true
  20026. });
  20027. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20028. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  20029. get: function () {
  20030. return this._useVertexColors;
  20031. },
  20032. set: function (value) {
  20033. if (this._useVertexColors === value) {
  20034. return;
  20035. }
  20036. this._useVertexColors = value;
  20037. this._markSubMeshesAsAttributesDirty();
  20038. },
  20039. enumerable: true,
  20040. configurable: true
  20041. });
  20042. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20043. /**
  20044. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20045. */
  20046. get: function () {
  20047. return this._computeBonesUsingShaders;
  20048. },
  20049. set: function (value) {
  20050. if (this._computeBonesUsingShaders === value) {
  20051. return;
  20052. }
  20053. this._computeBonesUsingShaders = value;
  20054. this._markSubMeshesAsAttributesDirty();
  20055. },
  20056. enumerable: true,
  20057. configurable: true
  20058. });
  20059. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20060. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20061. get: function () {
  20062. return this._numBoneInfluencers;
  20063. },
  20064. set: function (value) {
  20065. if (this._numBoneInfluencers === value) {
  20066. return;
  20067. }
  20068. this._numBoneInfluencers = value;
  20069. this._markSubMeshesAsAttributesDirty();
  20070. },
  20071. enumerable: true,
  20072. configurable: true
  20073. });
  20074. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20075. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20076. get: function () {
  20077. return this._applyFog;
  20078. },
  20079. set: function (value) {
  20080. if (this._applyFog === value) {
  20081. return;
  20082. }
  20083. this._applyFog = value;
  20084. this._markSubMeshesAsMiscDirty();
  20085. },
  20086. enumerable: true,
  20087. configurable: true
  20088. });
  20089. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20090. /**
  20091. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20092. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20093. */
  20094. get: function () {
  20095. return this._layerMask;
  20096. },
  20097. set: function (value) {
  20098. if (value === this._layerMask) {
  20099. return;
  20100. }
  20101. this._layerMask = value;
  20102. this._resyncLightSources();
  20103. },
  20104. enumerable: true,
  20105. configurable: true
  20106. });
  20107. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20108. /**
  20109. * Gets or sets a collision mask used to mask collisions (default is -1).
  20110. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20111. */
  20112. get: function () {
  20113. return this._collisionMask;
  20114. },
  20115. set: function (mask) {
  20116. this._collisionMask = !isNaN(mask) ? mask : -1;
  20117. },
  20118. enumerable: true,
  20119. configurable: true
  20120. });
  20121. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20122. /**
  20123. * Gets or sets the current collision group mask (-1 by default).
  20124. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20125. */
  20126. get: function () {
  20127. return this._collisionGroup;
  20128. },
  20129. set: function (mask) {
  20130. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20131. },
  20132. enumerable: true,
  20133. configurable: true
  20134. });
  20135. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20136. /** @hidden */
  20137. get: function () {
  20138. return null;
  20139. },
  20140. enumerable: true,
  20141. configurable: true
  20142. });
  20143. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20144. get: function () {
  20145. return this._skeleton;
  20146. },
  20147. /**
  20148. * Gets or sets a skeleton to apply skining transformations
  20149. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20150. */
  20151. set: function (value) {
  20152. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20153. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20154. }
  20155. if (value && value.needInitialSkinMatrix) {
  20156. value._registerMeshWithPoseMatrix(this);
  20157. }
  20158. this._skeleton = value;
  20159. if (!this._skeleton) {
  20160. this._bonesTransformMatrices = null;
  20161. }
  20162. this._markSubMeshesAsAttributesDirty();
  20163. },
  20164. enumerable: true,
  20165. configurable: true
  20166. });
  20167. /**
  20168. * Returns the string "AbstractMesh"
  20169. * @returns "AbstractMesh"
  20170. */
  20171. AbstractMesh.prototype.getClassName = function () {
  20172. return "AbstractMesh";
  20173. };
  20174. /**
  20175. * Gets a string representation of the current mesh
  20176. * @param fullDetails defines a boolean indicating if full details must be included
  20177. * @returns a string representation of the current mesh
  20178. */
  20179. AbstractMesh.prototype.toString = function (fullDetails) {
  20180. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20181. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20182. if (this._skeleton) {
  20183. ret += ", skeleton: " + this._skeleton.name;
  20184. }
  20185. if (fullDetails) {
  20186. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20187. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20188. }
  20189. return ret;
  20190. };
  20191. /** @hidden */
  20192. AbstractMesh.prototype._rebuild = function () {
  20193. this.onRebuildObservable.notifyObservers(this);
  20194. if (this._occlusionQuery) {
  20195. this._occlusionQuery = null;
  20196. }
  20197. if (!this.subMeshes) {
  20198. return;
  20199. }
  20200. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20201. var subMesh = _a[_i];
  20202. subMesh._rebuild();
  20203. }
  20204. };
  20205. /** @hidden */
  20206. AbstractMesh.prototype._resyncLightSources = function () {
  20207. this._lightSources.length = 0;
  20208. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20209. var light = _a[_i];
  20210. if (!light.isEnabled()) {
  20211. continue;
  20212. }
  20213. if (light.canAffectMesh(this)) {
  20214. this._lightSources.push(light);
  20215. }
  20216. }
  20217. this._markSubMeshesAsLightDirty();
  20218. };
  20219. /** @hidden */
  20220. AbstractMesh.prototype._resyncLighSource = function (light) {
  20221. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20222. var index = this._lightSources.indexOf(light);
  20223. if (index === -1) {
  20224. if (!isIn) {
  20225. return;
  20226. }
  20227. this._lightSources.push(light);
  20228. }
  20229. else {
  20230. if (isIn) {
  20231. return;
  20232. }
  20233. this._lightSources.splice(index, 1);
  20234. }
  20235. this._markSubMeshesAsLightDirty();
  20236. };
  20237. /** @hidden */
  20238. AbstractMesh.prototype._unBindEffect = function () {
  20239. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20240. var subMesh = _a[_i];
  20241. subMesh.setEffect(null);
  20242. }
  20243. };
  20244. /** @hidden */
  20245. AbstractMesh.prototype._removeLightSource = function (light) {
  20246. var index = this._lightSources.indexOf(light);
  20247. if (index === -1) {
  20248. return;
  20249. }
  20250. this._lightSources.splice(index, 1);
  20251. this._markSubMeshesAsLightDirty();
  20252. };
  20253. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20254. if (!this.subMeshes) {
  20255. return;
  20256. }
  20257. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20258. var subMesh = _a[_i];
  20259. if (subMesh._materialDefines) {
  20260. func(subMesh._materialDefines);
  20261. }
  20262. }
  20263. };
  20264. /** @hidden */
  20265. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20266. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20267. };
  20268. /** @hidden */
  20269. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20270. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20271. };
  20272. /** @hidden */
  20273. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20274. if (!this.subMeshes) {
  20275. return;
  20276. }
  20277. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20278. var subMesh = _a[_i];
  20279. var material = subMesh.getMaterial();
  20280. if (material) {
  20281. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20282. }
  20283. }
  20284. };
  20285. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20286. /**
  20287. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20288. */
  20289. get: function () {
  20290. return this._scaling;
  20291. },
  20292. set: function (newScaling) {
  20293. this._scaling = newScaling;
  20294. if (this.physicsImpostor) {
  20295. this.physicsImpostor.forceUpdate();
  20296. }
  20297. },
  20298. enumerable: true,
  20299. configurable: true
  20300. });
  20301. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20302. // Methods
  20303. /**
  20304. * Returns true if the mesh is blocked. Implemented by child classes
  20305. */
  20306. get: function () {
  20307. return false;
  20308. },
  20309. enumerable: true,
  20310. configurable: true
  20311. });
  20312. /**
  20313. * Returns the mesh itself by default. Implemented by child classes
  20314. * @param camera defines the camera to use to pick the right LOD level
  20315. * @returns the currentAbstractMesh
  20316. */
  20317. AbstractMesh.prototype.getLOD = function (camera) {
  20318. return this;
  20319. };
  20320. /**
  20321. * Returns 0 by default. Implemented by child classes
  20322. * @returns an integer
  20323. */
  20324. AbstractMesh.prototype.getTotalVertices = function () {
  20325. return 0;
  20326. };
  20327. /**
  20328. * Returns null by default. Implemented by child classes
  20329. * @returns null
  20330. */
  20331. AbstractMesh.prototype.getIndices = function () {
  20332. return null;
  20333. };
  20334. /**
  20335. * Returns the array of the requested vertex data kind. Implemented by child classes
  20336. * @param kind defines the vertex data kind to use
  20337. * @returns null
  20338. */
  20339. AbstractMesh.prototype.getVerticesData = function (kind) {
  20340. return null;
  20341. };
  20342. /**
  20343. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20344. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20345. * Note that a new underlying VertexBuffer object is created each call.
  20346. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20347. * @param kind defines vertex data kind:
  20348. * * BABYLON.VertexBuffer.PositionKind
  20349. * * BABYLON.VertexBuffer.UVKind
  20350. * * BABYLON.VertexBuffer.UV2Kind
  20351. * * BABYLON.VertexBuffer.UV3Kind
  20352. * * BABYLON.VertexBuffer.UV4Kind
  20353. * * BABYLON.VertexBuffer.UV5Kind
  20354. * * BABYLON.VertexBuffer.UV6Kind
  20355. * * BABYLON.VertexBuffer.ColorKind
  20356. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20357. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20358. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20359. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20360. * @param data defines the data source
  20361. * @param updatable defines if the data must be flagged as updatable (or static)
  20362. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20363. * @returns the current mesh
  20364. */
  20365. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20366. return this;
  20367. };
  20368. /**
  20369. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20370. * If the mesh has no geometry, it is simply returned as it is.
  20371. * @param kind defines vertex data kind:
  20372. * * BABYLON.VertexBuffer.PositionKind
  20373. * * BABYLON.VertexBuffer.UVKind
  20374. * * BABYLON.VertexBuffer.UV2Kind
  20375. * * BABYLON.VertexBuffer.UV3Kind
  20376. * * BABYLON.VertexBuffer.UV4Kind
  20377. * * BABYLON.VertexBuffer.UV5Kind
  20378. * * BABYLON.VertexBuffer.UV6Kind
  20379. * * BABYLON.VertexBuffer.ColorKind
  20380. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20381. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20382. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20383. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20384. * @param data defines the data source
  20385. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20386. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20387. * @returns the current mesh
  20388. */
  20389. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20390. return this;
  20391. };
  20392. /**
  20393. * Sets the mesh indices,
  20394. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20395. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20396. * @param totalVertices Defines the total number of vertices
  20397. * @returns the current mesh
  20398. */
  20399. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20400. return this;
  20401. };
  20402. /**
  20403. * Gets a boolean indicating if specific vertex data is present
  20404. * @param kind defines the vertex data kind to use
  20405. * @returns true is data kind is present
  20406. */
  20407. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20408. return false;
  20409. };
  20410. /**
  20411. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20412. * @returns a BoundingInfo
  20413. */
  20414. AbstractMesh.prototype.getBoundingInfo = function () {
  20415. if (this._masterMesh) {
  20416. return this._masterMesh.getBoundingInfo();
  20417. }
  20418. if (!this._boundingInfo) {
  20419. // this._boundingInfo is being created here
  20420. this._updateBoundingInfo();
  20421. }
  20422. // cannot be null.
  20423. return this._boundingInfo;
  20424. };
  20425. /**
  20426. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20427. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20428. * @returns the current mesh
  20429. */
  20430. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20431. if (includeDescendants === void 0) { includeDescendants = true; }
  20432. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20433. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20434. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20435. if (maxDimension === 0) {
  20436. return this;
  20437. }
  20438. var scale = 1 / maxDimension;
  20439. this.scaling.scaleInPlace(scale);
  20440. return this;
  20441. };
  20442. /**
  20443. * Overwrite the current bounding info
  20444. * @param boundingInfo defines the new bounding info
  20445. * @returns the current mesh
  20446. */
  20447. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20448. this._boundingInfo = boundingInfo;
  20449. return this;
  20450. };
  20451. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20452. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20453. get: function () {
  20454. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20455. },
  20456. enumerable: true,
  20457. configurable: true
  20458. });
  20459. /** @hidden */
  20460. AbstractMesh.prototype._preActivate = function () {
  20461. };
  20462. /** @hidden */
  20463. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20464. };
  20465. /** @hidden */
  20466. AbstractMesh.prototype._activate = function (renderId) {
  20467. this._renderId = renderId;
  20468. };
  20469. /**
  20470. * Gets the current world matrix
  20471. * @returns a Matrix
  20472. */
  20473. AbstractMesh.prototype.getWorldMatrix = function () {
  20474. if (this._masterMesh) {
  20475. return this._masterMesh.getWorldMatrix();
  20476. }
  20477. return _super.prototype.getWorldMatrix.call(this);
  20478. };
  20479. /** @hidden */
  20480. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20481. if (this._masterMesh) {
  20482. return this._masterMesh._getWorldMatrixDeterminant();
  20483. }
  20484. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20485. };
  20486. // ================================== Point of View Movement =================================
  20487. /**
  20488. * Perform relative position change from the point of view of behind the front of the mesh.
  20489. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20490. * Supports definition of mesh facing forward or backward
  20491. * @param amountRight defines the distance on the right axis
  20492. * @param amountUp defines the distance on the up axis
  20493. * @param amountForward defines the distance on the forward axis
  20494. * @returns the current mesh
  20495. */
  20496. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20497. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20498. return this;
  20499. };
  20500. /**
  20501. * Calculate relative position change from the point of view of behind the front of the mesh.
  20502. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20503. * Supports definition of mesh facing forward or backward
  20504. * @param amountRight defines the distance on the right axis
  20505. * @param amountUp defines the distance on the up axis
  20506. * @param amountForward defines the distance on the forward axis
  20507. * @returns the new displacement vector
  20508. */
  20509. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20510. var rotMatrix = new BABYLON.Matrix();
  20511. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20512. rotQuaternion.toRotationMatrix(rotMatrix);
  20513. var translationDelta = BABYLON.Vector3.Zero();
  20514. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20515. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20516. return translationDelta;
  20517. };
  20518. // ================================== Point of View Rotation =================================
  20519. /**
  20520. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20521. * Supports definition of mesh facing forward or backward
  20522. * @param flipBack defines the flip
  20523. * @param twirlClockwise defines the twirl
  20524. * @param tiltRight defines the tilt
  20525. * @returns the current mesh
  20526. */
  20527. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20528. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20529. return this;
  20530. };
  20531. /**
  20532. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20533. * Supports definition of mesh facing forward or backward.
  20534. * @param flipBack defines the flip
  20535. * @param twirlClockwise defines the twirl
  20536. * @param tiltRight defines the tilt
  20537. * @returns the new rotation vector
  20538. */
  20539. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20540. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20541. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20542. };
  20543. /**
  20544. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20545. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20546. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20547. * @returns the new bounding vectors
  20548. */
  20549. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20550. if (includeDescendants === void 0) { includeDescendants = true; }
  20551. if (predicate === void 0) { predicate = null; }
  20552. // Ensures that all world matrix will be recomputed.
  20553. this.getScene().incrementRenderId();
  20554. this.computeWorldMatrix(true);
  20555. var min;
  20556. var max;
  20557. var boundingInfo = this.getBoundingInfo();
  20558. if (!this.subMeshes) {
  20559. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20560. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20561. }
  20562. else {
  20563. min = boundingInfo.boundingBox.minimumWorld;
  20564. max = boundingInfo.boundingBox.maximumWorld;
  20565. }
  20566. if (includeDescendants) {
  20567. var descendants = this.getDescendants(false);
  20568. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20569. var descendant = descendants_1[_i];
  20570. var childMesh = descendant;
  20571. childMesh.computeWorldMatrix(true);
  20572. // Filters meshes based on custom predicate function.
  20573. if (predicate && !predicate(childMesh)) {
  20574. continue;
  20575. }
  20576. //make sure we have the needed params to get mix and max
  20577. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20578. continue;
  20579. }
  20580. var childBoundingInfo = childMesh.getBoundingInfo();
  20581. var boundingBox = childBoundingInfo.boundingBox;
  20582. var minBox = boundingBox.minimumWorld;
  20583. var maxBox = boundingBox.maximumWorld;
  20584. BABYLON.Tools.CheckExtends(minBox, min, max);
  20585. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20586. }
  20587. }
  20588. return {
  20589. min: min,
  20590. max: max
  20591. };
  20592. };
  20593. /** @hidden */
  20594. AbstractMesh.prototype._updateBoundingInfo = function () {
  20595. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20596. this._boundingInfo.update(this.worldMatrixFromCache);
  20597. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20598. return this;
  20599. };
  20600. /** @hidden */
  20601. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20602. if (!this.subMeshes) {
  20603. return this;
  20604. }
  20605. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20606. var subMesh = this.subMeshes[subIndex];
  20607. if (!subMesh.IsGlobal) {
  20608. subMesh.updateBoundingInfo(matrix);
  20609. }
  20610. }
  20611. return this;
  20612. };
  20613. /** @hidden */
  20614. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20615. // Bounding info
  20616. this._updateBoundingInfo();
  20617. };
  20618. /**
  20619. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20620. * A mesh is in the frustum if its bounding box intersects the frustum
  20621. * @param frustumPlanes defines the frustum to test
  20622. * @returns true if the mesh is in the frustum planes
  20623. */
  20624. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20625. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20626. };
  20627. /**
  20628. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20629. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20630. * @param frustumPlanes defines the frustum to test
  20631. * @returns true if the mesh is completely in the frustum planes
  20632. */
  20633. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20634. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20635. };
  20636. /**
  20637. * True if the mesh intersects another mesh or a SolidParticle object
  20638. * @param mesh defines a target mesh or SolidParticle to test
  20639. * @param precise 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)
  20640. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20641. * @returns true if there is an intersection
  20642. */
  20643. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20644. if (precise === void 0) { precise = false; }
  20645. if (!this._boundingInfo || !mesh._boundingInfo) {
  20646. return false;
  20647. }
  20648. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20649. return true;
  20650. }
  20651. if (includeDescendants) {
  20652. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20653. var child = _a[_i];
  20654. if (child.intersectsMesh(mesh, precise, true)) {
  20655. return true;
  20656. }
  20657. }
  20658. }
  20659. return false;
  20660. };
  20661. /**
  20662. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20663. * @param point defines the point to test
  20664. * @returns true if there is an intersection
  20665. */
  20666. AbstractMesh.prototype.intersectsPoint = function (point) {
  20667. if (!this._boundingInfo) {
  20668. return false;
  20669. }
  20670. return this._boundingInfo.intersectsPoint(point);
  20671. };
  20672. /**
  20673. * Gets the position of the current mesh in camera space
  20674. * @param camera defines the camera to use
  20675. * @returns a position
  20676. */
  20677. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20678. if (camera === void 0) { camera = null; }
  20679. if (!camera) {
  20680. camera = this.getScene().activeCamera;
  20681. }
  20682. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20683. };
  20684. /**
  20685. * Returns the distance from the mesh to the active camera
  20686. * @param camera defines the camera to use
  20687. * @returns the distance
  20688. */
  20689. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20690. if (camera === void 0) { camera = null; }
  20691. if (!camera) {
  20692. camera = this.getScene().activeCamera;
  20693. }
  20694. return this.absolutePosition.subtract(camera.position).length();
  20695. };
  20696. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20697. // Collisions
  20698. /**
  20699. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20700. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20701. */
  20702. get: function () {
  20703. return this._checkCollisions;
  20704. },
  20705. set: function (collisionEnabled) {
  20706. this._checkCollisions = collisionEnabled;
  20707. if (this.getScene().workerCollisions) {
  20708. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20709. }
  20710. },
  20711. enumerable: true,
  20712. configurable: true
  20713. });
  20714. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20715. /**
  20716. * Gets Collider object used to compute collisions (not physics)
  20717. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20718. */
  20719. get: function () {
  20720. return this._collider;
  20721. },
  20722. enumerable: true,
  20723. configurable: true
  20724. });
  20725. /**
  20726. * Move the mesh using collision engine
  20727. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20728. * @param displacement defines the requested displacement vector
  20729. * @returns the current mesh
  20730. */
  20731. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20732. var globalPosition = this.getAbsolutePosition();
  20733. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20734. if (!this._collider) {
  20735. this._collider = new BABYLON.Collider();
  20736. }
  20737. this._collider._radius = this.ellipsoid;
  20738. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20739. return this;
  20740. };
  20741. // Collisions
  20742. /** @hidden */
  20743. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20744. this._generatePointsArray();
  20745. if (!this._positions) {
  20746. return this;
  20747. }
  20748. // Transformation
  20749. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20750. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20751. subMesh._lastColliderWorldVertices = [];
  20752. subMesh._trianglePlanes = [];
  20753. var start = subMesh.verticesStart;
  20754. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20755. for (var i = start; i < end; i++) {
  20756. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20757. }
  20758. }
  20759. // Collide
  20760. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20761. if (collider.collisionFound) {
  20762. collider.collidedMesh = this;
  20763. }
  20764. return this;
  20765. };
  20766. /** @hidden */
  20767. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20768. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  20769. var len = subMeshes.length;
  20770. for (var index = 0; index < len; index++) {
  20771. var subMesh = subMeshes.data[index];
  20772. // Bounding test
  20773. if (len > 1 && !subMesh._checkCollision(collider))
  20774. continue;
  20775. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20776. }
  20777. return this;
  20778. };
  20779. /** @hidden */
  20780. AbstractMesh.prototype._checkCollision = function (collider) {
  20781. // Bounding box test
  20782. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20783. return this;
  20784. // Transformation matrix
  20785. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20786. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20787. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20788. return this;
  20789. };
  20790. // Picking
  20791. /** @hidden */
  20792. AbstractMesh.prototype._generatePointsArray = function () {
  20793. return false;
  20794. };
  20795. /**
  20796. * Checks if the passed Ray intersects with the mesh
  20797. * @param ray defines the ray to use
  20798. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20799. * @returns the picking info
  20800. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20801. */
  20802. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20803. var pickingInfo = new BABYLON.PickingInfo();
  20804. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20805. return pickingInfo;
  20806. }
  20807. if (!this._generatePointsArray()) {
  20808. return pickingInfo;
  20809. }
  20810. var intersectInfo = null;
  20811. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  20812. var len = subMeshes.length;
  20813. for (var index = 0; index < len; index++) {
  20814. var subMesh = subMeshes.data[index];
  20815. // Bounding test
  20816. if (len > 1 && !subMesh.canIntersects(ray))
  20817. continue;
  20818. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20819. if (currentIntersectInfo) {
  20820. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20821. intersectInfo = currentIntersectInfo;
  20822. intersectInfo.subMeshId = index;
  20823. if (fastCheck) {
  20824. break;
  20825. }
  20826. }
  20827. }
  20828. }
  20829. if (intersectInfo) {
  20830. // Get picked point
  20831. var world = this.getWorldMatrix();
  20832. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20833. var direction = ray.direction.clone();
  20834. direction = direction.scale(intersectInfo.distance);
  20835. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20836. var pickedPoint = worldOrigin.add(worldDirection);
  20837. // Return result
  20838. pickingInfo.hit = true;
  20839. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20840. pickingInfo.pickedPoint = pickedPoint;
  20841. pickingInfo.pickedMesh = this;
  20842. pickingInfo.bu = intersectInfo.bu || 0;
  20843. pickingInfo.bv = intersectInfo.bv || 0;
  20844. pickingInfo.faceId = intersectInfo.faceId;
  20845. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20846. return pickingInfo;
  20847. }
  20848. return pickingInfo;
  20849. };
  20850. /**
  20851. * Clones the current mesh
  20852. * @param name defines the mesh name
  20853. * @param newParent defines the new mesh parent
  20854. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20855. * @returns the new mesh
  20856. */
  20857. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20858. return null;
  20859. };
  20860. /**
  20861. * Disposes all the submeshes of the current meshnp
  20862. * @returns the current mesh
  20863. */
  20864. AbstractMesh.prototype.releaseSubMeshes = function () {
  20865. if (this.subMeshes) {
  20866. while (this.subMeshes.length) {
  20867. this.subMeshes[0].dispose();
  20868. }
  20869. }
  20870. else {
  20871. this.subMeshes = new Array();
  20872. }
  20873. return this;
  20874. };
  20875. /**
  20876. * Releases resources associated with this abstract mesh.
  20877. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20878. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20879. */
  20880. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20881. var _this = this;
  20882. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20883. var index;
  20884. // Smart Array Retainers.
  20885. this.getScene().freeActiveMeshes();
  20886. this.getScene().freeRenderingGroups();
  20887. // Action manager
  20888. if (this.actionManager !== undefined && this.actionManager !== null) {
  20889. this.actionManager.dispose();
  20890. this.actionManager = null;
  20891. }
  20892. // Skeleton
  20893. this._skeleton = null;
  20894. // Intersections in progress
  20895. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20896. var other = this._intersectionsInProgress[index];
  20897. var pos = other._intersectionsInProgress.indexOf(this);
  20898. other._intersectionsInProgress.splice(pos, 1);
  20899. }
  20900. this._intersectionsInProgress = [];
  20901. // Lights
  20902. var lights = this.getScene().lights;
  20903. lights.forEach(function (light) {
  20904. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20905. if (meshIndex !== -1) {
  20906. light.includedOnlyMeshes.splice(meshIndex, 1);
  20907. }
  20908. meshIndex = light.excludedMeshes.indexOf(_this);
  20909. if (meshIndex !== -1) {
  20910. light.excludedMeshes.splice(meshIndex, 1);
  20911. }
  20912. // Shadow generators
  20913. var generator = light.getShadowGenerator();
  20914. if (generator) {
  20915. var shadowMap = generator.getShadowMap();
  20916. if (shadowMap && shadowMap.renderList) {
  20917. meshIndex = shadowMap.renderList.indexOf(_this);
  20918. if (meshIndex !== -1) {
  20919. shadowMap.renderList.splice(meshIndex, 1);
  20920. }
  20921. }
  20922. }
  20923. });
  20924. // SubMeshes
  20925. if (this.getClassName() !== "InstancedMesh") {
  20926. this.releaseSubMeshes();
  20927. }
  20928. // Query
  20929. var engine = this.getScene().getEngine();
  20930. if (this._occlusionQuery) {
  20931. this._isOcclusionQueryInProgress = false;
  20932. engine.deleteQuery(this._occlusionQuery);
  20933. this._occlusionQuery = null;
  20934. }
  20935. // Engine
  20936. engine.wipeCaches();
  20937. // Remove from scene
  20938. this.getScene().removeMesh(this);
  20939. if (disposeMaterialAndTextures) {
  20940. if (this.material) {
  20941. this.material.dispose(false, true);
  20942. }
  20943. }
  20944. if (!doNotRecurse) {
  20945. // Particles
  20946. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20947. if (this.getScene().particleSystems[index].emitter === this) {
  20948. this.getScene().particleSystems[index].dispose();
  20949. index--;
  20950. }
  20951. }
  20952. }
  20953. // facet data
  20954. if (this._facetDataEnabled) {
  20955. this.disableFacetData();
  20956. }
  20957. this.onAfterWorldMatrixUpdateObservable.clear();
  20958. this.onCollideObservable.clear();
  20959. this.onCollisionPositionChangeObservable.clear();
  20960. this.onRebuildObservable.clear();
  20961. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20962. };
  20963. /**
  20964. * Adds the passed mesh as a child to the current mesh
  20965. * @param mesh defines the child mesh
  20966. * @returns the current mesh
  20967. */
  20968. AbstractMesh.prototype.addChild = function (mesh) {
  20969. mesh.setParent(this);
  20970. return this;
  20971. };
  20972. /**
  20973. * Removes the passed mesh from the current mesh children list
  20974. * @param mesh defines the child mesh
  20975. * @returns the current mesh
  20976. */
  20977. AbstractMesh.prototype.removeChild = function (mesh) {
  20978. mesh.setParent(null);
  20979. return this;
  20980. };
  20981. // Facet data
  20982. /** @hidden */
  20983. AbstractMesh.prototype._initFacetData = function () {
  20984. if (!this._facetNormals) {
  20985. this._facetNormals = new Array();
  20986. }
  20987. if (!this._facetPositions) {
  20988. this._facetPositions = new Array();
  20989. }
  20990. if (!this._facetPartitioning) {
  20991. this._facetPartitioning = new Array();
  20992. }
  20993. this._facetNb = (this.getIndices().length / 3) | 0;
  20994. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20995. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20996. for (var f = 0; f < this._facetNb; f++) {
  20997. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20998. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20999. }
  21000. this._facetDataEnabled = true;
  21001. return this;
  21002. };
  21003. /**
  21004. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21005. * This method can be called within the render loop.
  21006. * 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
  21007. * @returns the current mesh
  21008. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21009. */
  21010. AbstractMesh.prototype.updateFacetData = function () {
  21011. if (!this._facetDataEnabled) {
  21012. this._initFacetData();
  21013. }
  21014. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21015. var indices = this.getIndices();
  21016. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21017. var bInfo = this.getBoundingInfo();
  21018. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21019. // init arrays, matrix and sort function on first call
  21020. this._facetDepthSortEnabled = true;
  21021. if (indices instanceof Uint16Array) {
  21022. this._depthSortedIndices = new Uint16Array(indices);
  21023. }
  21024. else if (indices instanceof Uint32Array) {
  21025. this._depthSortedIndices = new Uint32Array(indices);
  21026. }
  21027. else {
  21028. var needs32bits = false;
  21029. for (var i = 0; i < indices.length; i++) {
  21030. if (indices[i] > 65535) {
  21031. needs32bits = true;
  21032. break;
  21033. }
  21034. }
  21035. if (needs32bits) {
  21036. this._depthSortedIndices = new Uint32Array(indices);
  21037. }
  21038. else {
  21039. this._depthSortedIndices = new Uint16Array(indices);
  21040. }
  21041. }
  21042. this._facetDepthSortFunction = function (f1, f2) {
  21043. return (f2.sqDistance - f1.sqDistance);
  21044. };
  21045. if (!this._facetDepthSortFrom) {
  21046. var camera = this.getScene().activeCamera;
  21047. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21048. }
  21049. this._depthSortedFacets = [];
  21050. for (var f = 0; f < this._facetNb; f++) {
  21051. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21052. this._depthSortedFacets.push(depthSortedFacet);
  21053. }
  21054. this._invertedMatrix = BABYLON.Matrix.Identity();
  21055. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21056. }
  21057. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21058. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21059. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21060. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21061. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21062. this._subDiv.max = this._partitioningSubdivisions;
  21063. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21064. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21065. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21066. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21067. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21068. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21069. // set the parameters for ComputeNormals()
  21070. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21071. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21072. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21073. this._facetParameters.bInfo = bInfo;
  21074. this._facetParameters.bbSize = this._bbSize;
  21075. this._facetParameters.subDiv = this._subDiv;
  21076. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21077. this._facetParameters.depthSort = this._facetDepthSort;
  21078. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21079. this.computeWorldMatrix(true);
  21080. this._worldMatrix.invertToRef(this._invertedMatrix);
  21081. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21082. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21083. }
  21084. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21085. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21086. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21087. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21088. var l = (this._depthSortedIndices.length / 3) | 0;
  21089. for (var f = 0; f < l; f++) {
  21090. var sind = this._depthSortedFacets[f].ind;
  21091. this._depthSortedIndices[f * 3] = indices[sind];
  21092. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21093. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21094. }
  21095. this.updateIndices(this._depthSortedIndices);
  21096. }
  21097. return this;
  21098. };
  21099. /**
  21100. * Returns the facetLocalNormals array.
  21101. * The normals are expressed in the mesh local spac
  21102. * @returns an array of Vector3
  21103. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21104. */
  21105. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21106. if (!this._facetNormals) {
  21107. this.updateFacetData();
  21108. }
  21109. return this._facetNormals;
  21110. };
  21111. /**
  21112. * Returns the facetLocalPositions array.
  21113. * The facet positions are expressed in the mesh local space
  21114. * @returns an array of Vector3
  21115. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21116. */
  21117. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21118. if (!this._facetPositions) {
  21119. this.updateFacetData();
  21120. }
  21121. return this._facetPositions;
  21122. };
  21123. /**
  21124. * Returns the facetLocalPartioning array
  21125. * @returns an array of array of numbers
  21126. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21127. */
  21128. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21129. if (!this._facetPartitioning) {
  21130. this.updateFacetData();
  21131. }
  21132. return this._facetPartitioning;
  21133. };
  21134. /**
  21135. * Returns the i-th facet position in the world system.
  21136. * This method allocates a new Vector3 per call
  21137. * @param i defines the facet index
  21138. * @returns a new Vector3
  21139. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21140. */
  21141. AbstractMesh.prototype.getFacetPosition = function (i) {
  21142. var pos = BABYLON.Vector3.Zero();
  21143. this.getFacetPositionToRef(i, pos);
  21144. return pos;
  21145. };
  21146. /**
  21147. * Sets the reference Vector3 with the i-th facet position in the world system
  21148. * @param i defines the facet index
  21149. * @param ref defines the target vector
  21150. * @returns the current mesh
  21151. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21152. */
  21153. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21154. var localPos = (this.getFacetLocalPositions())[i];
  21155. var world = this.getWorldMatrix();
  21156. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21157. return this;
  21158. };
  21159. /**
  21160. * Returns the i-th facet normal in the world system.
  21161. * This method allocates a new Vector3 per call
  21162. * @param i defines the facet index
  21163. * @returns a new Vector3
  21164. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21165. */
  21166. AbstractMesh.prototype.getFacetNormal = function (i) {
  21167. var norm = BABYLON.Vector3.Zero();
  21168. this.getFacetNormalToRef(i, norm);
  21169. return norm;
  21170. };
  21171. /**
  21172. * Sets the reference Vector3 with the i-th facet normal in the world system
  21173. * @param i defines the facet index
  21174. * @param ref defines the target vector
  21175. * @returns the current mesh
  21176. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21177. */
  21178. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21179. var localNorm = (this.getFacetLocalNormals())[i];
  21180. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21181. return this;
  21182. };
  21183. /**
  21184. * 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)
  21185. * @param x defines x coordinate
  21186. * @param y defines y coordinate
  21187. * @param z defines z coordinate
  21188. * @returns the array of facet indexes
  21189. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21190. */
  21191. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21192. var bInfo = this.getBoundingInfo();
  21193. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21194. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21195. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21196. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21197. return null;
  21198. }
  21199. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21200. };
  21201. /**
  21202. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21203. * @param projected sets as the (x,y,z) world projection on the facet
  21204. * @param checkFace if 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
  21205. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. 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
  21206. * @param x defines x coordinate
  21207. * @param y defines y coordinate
  21208. * @param z defines z coordinate
  21209. * @returns the face index if found (or null instead)
  21210. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21211. */
  21212. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21213. if (checkFace === void 0) { checkFace = false; }
  21214. if (facing === void 0) { facing = true; }
  21215. var world = this.getWorldMatrix();
  21216. var invMat = BABYLON.Tmp.Matrix[5];
  21217. world.invertToRef(invMat);
  21218. var invVect = BABYLON.Tmp.Vector3[8];
  21219. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21220. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21221. if (projected) {
  21222. // tranform the local computed projected vector to world coordinates
  21223. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21224. }
  21225. return closest;
  21226. };
  21227. /**
  21228. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21229. * @param projected sets as the (x,y,z) local projection on the facet
  21230. * @param checkFace if 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
  21231. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. 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
  21232. * @param x defines x coordinate
  21233. * @param y defines y coordinate
  21234. * @param z defines z coordinate
  21235. * @returns the face index if found (or null instead)
  21236. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21237. */
  21238. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21239. if (checkFace === void 0) { checkFace = false; }
  21240. if (facing === void 0) { facing = true; }
  21241. var closest = null;
  21242. var tmpx = 0.0;
  21243. var tmpy = 0.0;
  21244. var tmpz = 0.0;
  21245. var d = 0.0; // tmp dot facet normal * facet position
  21246. var t0 = 0.0;
  21247. var projx = 0.0;
  21248. var projy = 0.0;
  21249. var projz = 0.0;
  21250. // Get all the facets in the same partitioning block than (x, y, z)
  21251. var facetPositions = this.getFacetLocalPositions();
  21252. var facetNormals = this.getFacetLocalNormals();
  21253. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21254. if (!facetsInBlock) {
  21255. return null;
  21256. }
  21257. // Get the closest facet to (x, y, z)
  21258. var shortest = Number.MAX_VALUE; // init distance vars
  21259. var tmpDistance = shortest;
  21260. var fib; // current facet in the block
  21261. var norm; // current facet normal
  21262. var p0; // current facet barycenter position
  21263. // loop on all the facets in the current partitioning block
  21264. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21265. fib = facetsInBlock[idx];
  21266. norm = facetNormals[fib];
  21267. p0 = facetPositions[fib];
  21268. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21269. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21270. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21271. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21272. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21273. projx = x + norm.x * t0;
  21274. projy = y + norm.y * t0;
  21275. projz = z + norm.z * t0;
  21276. tmpx = projx - x;
  21277. tmpy = projy - y;
  21278. tmpz = projz - z;
  21279. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21280. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21281. shortest = tmpDistance;
  21282. closest = fib;
  21283. if (projected) {
  21284. projected.x = projx;
  21285. projected.y = projy;
  21286. projected.z = projz;
  21287. }
  21288. }
  21289. }
  21290. }
  21291. return closest;
  21292. };
  21293. /**
  21294. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21295. * @returns the parameters
  21296. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21297. */
  21298. AbstractMesh.prototype.getFacetDataParameters = function () {
  21299. return this._facetParameters;
  21300. };
  21301. /**
  21302. * Disables the feature FacetData and frees the related memory
  21303. * @returns the current mesh
  21304. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21305. */
  21306. AbstractMesh.prototype.disableFacetData = function () {
  21307. if (this._facetDataEnabled) {
  21308. this._facetDataEnabled = false;
  21309. this._facetPositions = new Array();
  21310. this._facetNormals = new Array();
  21311. this._facetPartitioning = new Array();
  21312. this._facetParameters = null;
  21313. this._depthSortedIndices = new Uint32Array(0);
  21314. }
  21315. return this;
  21316. };
  21317. /**
  21318. * Updates the AbstractMesh indices array
  21319. * @param indices defines the data source
  21320. * @returns the current mesh
  21321. */
  21322. AbstractMesh.prototype.updateIndices = function (indices) {
  21323. return this;
  21324. };
  21325. /**
  21326. * Creates new normals data for the mesh
  21327. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21328. * @returns the current mesh
  21329. */
  21330. AbstractMesh.prototype.createNormals = function (updatable) {
  21331. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21332. var indices = this.getIndices();
  21333. var normals;
  21334. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21335. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21336. }
  21337. else {
  21338. normals = [];
  21339. }
  21340. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21341. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21342. return this;
  21343. };
  21344. /**
  21345. * Align the mesh with a normal
  21346. * @param normal defines the normal to use
  21347. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21348. * @returns the current mesh
  21349. */
  21350. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21351. if (!upDirection) {
  21352. upDirection = BABYLON.Axis.Y;
  21353. }
  21354. var axisX = BABYLON.Tmp.Vector3[0];
  21355. var axisZ = BABYLON.Tmp.Vector3[1];
  21356. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21357. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21358. if (this.rotationQuaternion) {
  21359. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21360. }
  21361. else {
  21362. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21363. }
  21364. return this;
  21365. };
  21366. /** @hidden */
  21367. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21368. this._isOccluded = false;
  21369. };
  21370. /** No occlusion */
  21371. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21372. /** Occlusion set to optimisitic */
  21373. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21374. /** Occlusion set to strict */
  21375. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21376. /** Use an accurante occlusion algorithm */
  21377. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21378. /** Use a conservative occlusion algorithm */
  21379. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21380. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21381. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21382. /** Culling strategy with bounding sphere only and then frustum culling */
  21383. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21384. return AbstractMesh;
  21385. }(BABYLON.TransformNode));
  21386. BABYLON.AbstractMesh = AbstractMesh;
  21387. })(BABYLON || (BABYLON = {}));
  21388. //# sourceMappingURL=babylon.abstractMesh.js.map
  21389. var BABYLON;
  21390. (function (BABYLON) {
  21391. /**
  21392. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21393. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21394. * 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.
  21395. */
  21396. var Light = /** @class */ (function (_super) {
  21397. __extends(Light, _super);
  21398. /**
  21399. * Creates a Light object in the scene.
  21400. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21401. * @param name The firendly name of the light
  21402. * @param scene The scene the light belongs too
  21403. */
  21404. function Light(name, scene) {
  21405. var _this = _super.call(this, name, scene) || this;
  21406. /**
  21407. * Diffuse gives the basic color to an object.
  21408. */
  21409. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21410. /**
  21411. * Specular produces a highlight color on an object.
  21412. * Note: This is note affecting PBR materials.
  21413. */
  21414. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21415. /**
  21416. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21417. * falling off base on range or angle.
  21418. * This can be set to any values in Light.FALLOFF_x.
  21419. *
  21420. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21421. * other types of materials.
  21422. */
  21423. _this.falloffType = Light.FALLOFF_DEFAULT;
  21424. /**
  21425. * Strength of the light.
  21426. * Note: By default it is define in the framework own unit.
  21427. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21428. */
  21429. _this.intensity = 1.0;
  21430. _this._range = Number.MAX_VALUE;
  21431. _this._inverseSquaredRange = 0;
  21432. /**
  21433. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21434. * of light.
  21435. */
  21436. _this._photometricScale = 1.0;
  21437. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21438. _this._radius = 0.00001;
  21439. /**
  21440. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21441. * exceeding the number allowed of the materials.
  21442. */
  21443. _this.renderPriority = 0;
  21444. _this._shadowEnabled = true;
  21445. _this._excludeWithLayerMask = 0;
  21446. _this._includeOnlyWithLayerMask = 0;
  21447. _this._lightmapMode = 0;
  21448. /**
  21449. * @hidden Internal use only.
  21450. */
  21451. _this._excludedMeshesIds = new Array();
  21452. /**
  21453. * @hidden Internal use only.
  21454. */
  21455. _this._includedOnlyMeshesIds = new Array();
  21456. _this.getScene().addLight(_this);
  21457. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21458. _this._buildUniformLayout();
  21459. _this.includedOnlyMeshes = new Array();
  21460. _this.excludedMeshes = new Array();
  21461. _this._resyncMeshes();
  21462. return _this;
  21463. }
  21464. Object.defineProperty(Light.prototype, "range", {
  21465. /**
  21466. * Defines how far from the source the light is impacting in scene units.
  21467. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21468. */
  21469. get: function () {
  21470. return this._range;
  21471. },
  21472. /**
  21473. * Defines how far from the source the light is impacting in scene units.
  21474. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21475. */
  21476. set: function (value) {
  21477. this._range = value;
  21478. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21479. },
  21480. enumerable: true,
  21481. configurable: true
  21482. });
  21483. Object.defineProperty(Light.prototype, "intensityMode", {
  21484. /**
  21485. * Gets the photometric scale used to interpret the intensity.
  21486. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21487. */
  21488. get: function () {
  21489. return this._intensityMode;
  21490. },
  21491. /**
  21492. * Sets the photometric scale used to interpret the intensity.
  21493. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21494. */
  21495. set: function (value) {
  21496. this._intensityMode = value;
  21497. this._computePhotometricScale();
  21498. },
  21499. enumerable: true,
  21500. configurable: true
  21501. });
  21502. ;
  21503. ;
  21504. Object.defineProperty(Light.prototype, "radius", {
  21505. /**
  21506. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21507. */
  21508. get: function () {
  21509. return this._radius;
  21510. },
  21511. /**
  21512. * sets the light radius used by PBR Materials to simulate soft area lights.
  21513. */
  21514. set: function (value) {
  21515. this._radius = value;
  21516. this._computePhotometricScale();
  21517. },
  21518. enumerable: true,
  21519. configurable: true
  21520. });
  21521. ;
  21522. ;
  21523. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21524. /**
  21525. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21526. * the current shadow generator.
  21527. */
  21528. get: function () {
  21529. return this._shadowEnabled;
  21530. },
  21531. /**
  21532. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21533. * the current shadow generator.
  21534. */
  21535. set: function (value) {
  21536. if (this._shadowEnabled === value) {
  21537. return;
  21538. }
  21539. this._shadowEnabled = value;
  21540. this._markMeshesAsLightDirty();
  21541. },
  21542. enumerable: true,
  21543. configurable: true
  21544. });
  21545. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21546. /**
  21547. * Gets the only meshes impacted by this light.
  21548. */
  21549. get: function () {
  21550. return this._includedOnlyMeshes;
  21551. },
  21552. /**
  21553. * Sets the only meshes impacted by this light.
  21554. */
  21555. set: function (value) {
  21556. this._includedOnlyMeshes = value;
  21557. this._hookArrayForIncludedOnly(value);
  21558. },
  21559. enumerable: true,
  21560. configurable: true
  21561. });
  21562. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21563. /**
  21564. * Gets the meshes not impacted by this light.
  21565. */
  21566. get: function () {
  21567. return this._excludedMeshes;
  21568. },
  21569. /**
  21570. * Sets the meshes not impacted by this light.
  21571. */
  21572. set: function (value) {
  21573. this._excludedMeshes = value;
  21574. this._hookArrayForExcluded(value);
  21575. },
  21576. enumerable: true,
  21577. configurable: true
  21578. });
  21579. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21580. /**
  21581. * Gets the layer id use to find what meshes are not impacted by the light.
  21582. * Inactive if 0
  21583. */
  21584. get: function () {
  21585. return this._excludeWithLayerMask;
  21586. },
  21587. /**
  21588. * Sets the layer id use to find what meshes are not impacted by the light.
  21589. * Inactive if 0
  21590. */
  21591. set: function (value) {
  21592. this._excludeWithLayerMask = value;
  21593. this._resyncMeshes();
  21594. },
  21595. enumerable: true,
  21596. configurable: true
  21597. });
  21598. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21599. /**
  21600. * Gets the layer id use to find what meshes are impacted by the light.
  21601. * Inactive if 0
  21602. */
  21603. get: function () {
  21604. return this._includeOnlyWithLayerMask;
  21605. },
  21606. /**
  21607. * Sets the layer id use to find what meshes are impacted by the light.
  21608. * Inactive if 0
  21609. */
  21610. set: function (value) {
  21611. this._includeOnlyWithLayerMask = value;
  21612. this._resyncMeshes();
  21613. },
  21614. enumerable: true,
  21615. configurable: true
  21616. });
  21617. Object.defineProperty(Light.prototype, "lightmapMode", {
  21618. /**
  21619. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21620. */
  21621. get: function () {
  21622. return this._lightmapMode;
  21623. },
  21624. /**
  21625. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21626. */
  21627. set: function (value) {
  21628. if (this._lightmapMode === value) {
  21629. return;
  21630. }
  21631. this._lightmapMode = value;
  21632. this._markMeshesAsLightDirty();
  21633. },
  21634. enumerable: true,
  21635. configurable: true
  21636. });
  21637. /**
  21638. * Returns the string "Light".
  21639. * @returns the class name
  21640. */
  21641. Light.prototype.getClassName = function () {
  21642. return "Light";
  21643. };
  21644. /**
  21645. * Converts the light information to a readable string for debug purpose.
  21646. * @param fullDetails Supports for multiple levels of logging within scene loading
  21647. * @returns the human readable light info
  21648. */
  21649. Light.prototype.toString = function (fullDetails) {
  21650. var ret = "Name: " + this.name;
  21651. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21652. if (this.animations) {
  21653. for (var i = 0; i < this.animations.length; i++) {
  21654. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21655. }
  21656. }
  21657. if (fullDetails) {
  21658. }
  21659. return ret;
  21660. };
  21661. /**
  21662. * Set the enabled state of this node.
  21663. * @param value - the new enabled state
  21664. */
  21665. Light.prototype.setEnabled = function (value) {
  21666. _super.prototype.setEnabled.call(this, value);
  21667. this._resyncMeshes();
  21668. };
  21669. /**
  21670. * Returns the Light associated shadow generator if any.
  21671. * @return the associated shadow generator.
  21672. */
  21673. Light.prototype.getShadowGenerator = function () {
  21674. return this._shadowGenerator;
  21675. };
  21676. /**
  21677. * Returns a Vector3, the absolute light position in the World.
  21678. * @returns the world space position of the light
  21679. */
  21680. Light.prototype.getAbsolutePosition = function () {
  21681. return BABYLON.Vector3.Zero();
  21682. };
  21683. /**
  21684. * Specifies if the light will affect the passed mesh.
  21685. * @param mesh The mesh to test against the light
  21686. * @return true the mesh is affected otherwise, false.
  21687. */
  21688. Light.prototype.canAffectMesh = function (mesh) {
  21689. if (!mesh) {
  21690. return true;
  21691. }
  21692. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21693. return false;
  21694. }
  21695. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21696. return false;
  21697. }
  21698. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21699. return false;
  21700. }
  21701. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21702. return false;
  21703. }
  21704. return true;
  21705. };
  21706. /**
  21707. * Sort function to order lights for rendering.
  21708. * @param a First Light object to compare to second.
  21709. * @param b Second Light object to compare first.
  21710. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21711. */
  21712. Light.CompareLightsPriority = function (a, b) {
  21713. //shadow-casting lights have priority over non-shadow-casting lights
  21714. //the renderPrioirty is a secondary sort criterion
  21715. if (a.shadowEnabled !== b.shadowEnabled) {
  21716. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21717. }
  21718. return b.renderPriority - a.renderPriority;
  21719. };
  21720. /**
  21721. * Releases resources associated with this node.
  21722. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21723. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21724. */
  21725. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21726. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21727. if (this._shadowGenerator) {
  21728. this._shadowGenerator.dispose();
  21729. this._shadowGenerator = null;
  21730. }
  21731. // Animations
  21732. this.getScene().stopAnimation(this);
  21733. // Remove from meshes
  21734. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21735. var mesh = _a[_i];
  21736. mesh._removeLightSource(this);
  21737. }
  21738. this._uniformBuffer.dispose();
  21739. // Remove from scene
  21740. this.getScene().removeLight(this);
  21741. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21742. };
  21743. /**
  21744. * Returns the light type ID (integer).
  21745. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21746. */
  21747. Light.prototype.getTypeID = function () {
  21748. return 0;
  21749. };
  21750. /**
  21751. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21752. * @returns the scaled intensity in intensity mode unit
  21753. */
  21754. Light.prototype.getScaledIntensity = function () {
  21755. return this._photometricScale * this.intensity;
  21756. };
  21757. /**
  21758. * Returns a new Light object, named "name", from the current one.
  21759. * @param name The name of the cloned light
  21760. * @returns the new created light
  21761. */
  21762. Light.prototype.clone = function (name) {
  21763. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21764. if (!constructor) {
  21765. return null;
  21766. }
  21767. return BABYLON.SerializationHelper.Clone(constructor, this);
  21768. };
  21769. /**
  21770. * Serializes the current light into a Serialization object.
  21771. * @returns the serialized object.
  21772. */
  21773. Light.prototype.serialize = function () {
  21774. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21775. // Type
  21776. serializationObject.type = this.getTypeID();
  21777. // Parent
  21778. if (this.parent) {
  21779. serializationObject.parentId = this.parent.id;
  21780. }
  21781. // Inclusion / exclusions
  21782. if (this.excludedMeshes.length > 0) {
  21783. serializationObject.excludedMeshesIds = [];
  21784. this.excludedMeshes.forEach(function (mesh) {
  21785. serializationObject.excludedMeshesIds.push(mesh.id);
  21786. });
  21787. }
  21788. if (this.includedOnlyMeshes.length > 0) {
  21789. serializationObject.includedOnlyMeshesIds = [];
  21790. this.includedOnlyMeshes.forEach(function (mesh) {
  21791. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21792. });
  21793. }
  21794. // Animations
  21795. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21796. serializationObject.ranges = this.serializeAnimationRanges();
  21797. return serializationObject;
  21798. };
  21799. /**
  21800. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21801. * This new light is named "name" and added to the passed scene.
  21802. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21803. * @param name The friendly name of the light
  21804. * @param scene The scene the new light will belong to
  21805. * @returns the constructor function
  21806. */
  21807. Light.GetConstructorFromName = function (type, name, scene) {
  21808. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21809. if (constructorFunc) {
  21810. return constructorFunc;
  21811. }
  21812. // Default to no light for none present once.
  21813. return null;
  21814. };
  21815. /**
  21816. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21817. * @param parsedLight The JSON representation of the light
  21818. * @param scene The scene to create the parsed light in
  21819. * @returns the created light after parsing
  21820. */
  21821. Light.Parse = function (parsedLight, scene) {
  21822. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21823. if (!constructor) {
  21824. return null;
  21825. }
  21826. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21827. // Inclusion / exclusions
  21828. if (parsedLight.excludedMeshesIds) {
  21829. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21830. }
  21831. if (parsedLight.includedOnlyMeshesIds) {
  21832. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21833. }
  21834. // Parent
  21835. if (parsedLight.parentId) {
  21836. light._waitingParentId = parsedLight.parentId;
  21837. }
  21838. // Animations
  21839. if (parsedLight.animations) {
  21840. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21841. var parsedAnimation = parsedLight.animations[animationIndex];
  21842. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21843. }
  21844. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21845. }
  21846. if (parsedLight.autoAnimate) {
  21847. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21848. }
  21849. return light;
  21850. };
  21851. Light.prototype._hookArrayForExcluded = function (array) {
  21852. var _this = this;
  21853. var oldPush = array.push;
  21854. array.push = function () {
  21855. var items = [];
  21856. for (var _i = 0; _i < arguments.length; _i++) {
  21857. items[_i] = arguments[_i];
  21858. }
  21859. var result = oldPush.apply(array, items);
  21860. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21861. var item = items_1[_a];
  21862. item._resyncLighSource(_this);
  21863. }
  21864. return result;
  21865. };
  21866. var oldSplice = array.splice;
  21867. array.splice = function (index, deleteCount) {
  21868. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21869. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21870. var item = deleted_1[_i];
  21871. item._resyncLighSource(_this);
  21872. }
  21873. return deleted;
  21874. };
  21875. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21876. var item = array_1[_i];
  21877. item._resyncLighSource(this);
  21878. }
  21879. };
  21880. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21881. var _this = this;
  21882. var oldPush = array.push;
  21883. array.push = function () {
  21884. var items = [];
  21885. for (var _i = 0; _i < arguments.length; _i++) {
  21886. items[_i] = arguments[_i];
  21887. }
  21888. var result = oldPush.apply(array, items);
  21889. _this._resyncMeshes();
  21890. return result;
  21891. };
  21892. var oldSplice = array.splice;
  21893. array.splice = function (index, deleteCount) {
  21894. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21895. _this._resyncMeshes();
  21896. return deleted;
  21897. };
  21898. this._resyncMeshes();
  21899. };
  21900. Light.prototype._resyncMeshes = function () {
  21901. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21902. var mesh = _a[_i];
  21903. mesh._resyncLighSource(this);
  21904. }
  21905. };
  21906. /**
  21907. * Forces the meshes to update their light related information in their rendering used effects
  21908. * @hidden Internal Use Only
  21909. */
  21910. Light.prototype._markMeshesAsLightDirty = function () {
  21911. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21912. var mesh = _a[_i];
  21913. if (mesh._lightSources.indexOf(this) !== -1) {
  21914. mesh._markSubMeshesAsLightDirty();
  21915. }
  21916. }
  21917. };
  21918. /**
  21919. * Recomputes the cached photometric scale if needed.
  21920. */
  21921. Light.prototype._computePhotometricScale = function () {
  21922. this._photometricScale = this._getPhotometricScale();
  21923. this.getScene().resetCachedMaterial();
  21924. };
  21925. /**
  21926. * Returns the Photometric Scale according to the light type and intensity mode.
  21927. */
  21928. Light.prototype._getPhotometricScale = function () {
  21929. var photometricScale = 0.0;
  21930. var lightTypeID = this.getTypeID();
  21931. //get photometric mode
  21932. var photometricMode = this.intensityMode;
  21933. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21934. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21935. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21936. }
  21937. else {
  21938. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21939. }
  21940. }
  21941. //compute photometric scale
  21942. switch (lightTypeID) {
  21943. case Light.LIGHTTYPEID_POINTLIGHT:
  21944. case Light.LIGHTTYPEID_SPOTLIGHT:
  21945. switch (photometricMode) {
  21946. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21947. photometricScale = 1.0 / (4.0 * Math.PI);
  21948. break;
  21949. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21950. photometricScale = 1.0;
  21951. break;
  21952. case Light.INTENSITYMODE_LUMINANCE:
  21953. photometricScale = this.radius * this.radius;
  21954. break;
  21955. }
  21956. break;
  21957. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21958. switch (photometricMode) {
  21959. case Light.INTENSITYMODE_ILLUMINANCE:
  21960. photometricScale = 1.0;
  21961. break;
  21962. case Light.INTENSITYMODE_LUMINANCE:
  21963. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21964. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21965. var apexAngleRadians = this.radius;
  21966. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21967. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21968. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21969. photometricScale = solidAngle;
  21970. break;
  21971. }
  21972. break;
  21973. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21974. // No fall off in hemisperic light.
  21975. photometricScale = 1.0;
  21976. break;
  21977. }
  21978. return photometricScale;
  21979. };
  21980. /**
  21981. * Reorder the light in the scene according to their defined priority.
  21982. * @hidden Internal Use Only
  21983. */
  21984. Light.prototype._reorderLightsInScene = function () {
  21985. var scene = this.getScene();
  21986. if (this._renderPriority != 0) {
  21987. scene.requireLightSorting = true;
  21988. }
  21989. this.getScene().sortLightsByPriority();
  21990. };
  21991. /**
  21992. * Falloff Default: light is falling off following the material specification:
  21993. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  21994. */
  21995. Light.FALLOFF_DEFAULT = 0;
  21996. /**
  21997. * Falloff Physical: light is falling off following the inverse squared distance law.
  21998. */
  21999. Light.FALLOFF_PHYSICAL = 1;
  22000. /**
  22001. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22002. * to enhance interoperability with other engines.
  22003. */
  22004. Light.FALLOFF_GLTF = 2;
  22005. /**
  22006. * Falloff Standard: light is falling off like in the standard material
  22007. * to enhance interoperability with other materials.
  22008. */
  22009. Light.FALLOFF_STANDARD = 3;
  22010. //lightmapMode Consts
  22011. /**
  22012. * If every light affecting the material is in this lightmapMode,
  22013. * material.lightmapTexture adds or multiplies
  22014. * (depends on material.useLightmapAsShadowmap)
  22015. * after every other light calculations.
  22016. */
  22017. Light.LIGHTMAP_DEFAULT = 0;
  22018. /**
  22019. * material.lightmapTexture as only diffuse lighting from this light
  22020. * adds only specular lighting from this light
  22021. * adds dynamic shadows
  22022. */
  22023. Light.LIGHTMAP_SPECULAR = 1;
  22024. /**
  22025. * material.lightmapTexture as only lighting
  22026. * no light calculation from this light
  22027. * only adds dynamic shadows from this light
  22028. */
  22029. Light.LIGHTMAP_SHADOWSONLY = 2;
  22030. // Intensity Mode Consts
  22031. /**
  22032. * Each light type uses the default quantity according to its type:
  22033. * point/spot lights use luminous intensity
  22034. * directional lights use illuminance
  22035. */
  22036. Light.INTENSITYMODE_AUTOMATIC = 0;
  22037. /**
  22038. * lumen (lm)
  22039. */
  22040. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22041. /**
  22042. * candela (lm/sr)
  22043. */
  22044. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22045. /**
  22046. * lux (lm/m^2)
  22047. */
  22048. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22049. /**
  22050. * nit (cd/m^2)
  22051. */
  22052. Light.INTENSITYMODE_LUMINANCE = 4;
  22053. // Light types ids const.
  22054. /**
  22055. * Light type const id of the point light.
  22056. */
  22057. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22058. /**
  22059. * Light type const id of the directional light.
  22060. */
  22061. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22062. /**
  22063. * Light type const id of the spot light.
  22064. */
  22065. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22066. /**
  22067. * Light type const id of the hemispheric light.
  22068. */
  22069. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22070. __decorate([
  22071. BABYLON.serializeAsColor3()
  22072. ], Light.prototype, "diffuse", void 0);
  22073. __decorate([
  22074. BABYLON.serializeAsColor3()
  22075. ], Light.prototype, "specular", void 0);
  22076. __decorate([
  22077. BABYLON.serialize()
  22078. ], Light.prototype, "falloffType", void 0);
  22079. __decorate([
  22080. BABYLON.serialize()
  22081. ], Light.prototype, "intensity", void 0);
  22082. __decorate([
  22083. BABYLON.serialize()
  22084. ], Light.prototype, "range", null);
  22085. __decorate([
  22086. BABYLON.serialize()
  22087. ], Light.prototype, "intensityMode", null);
  22088. __decorate([
  22089. BABYLON.serialize()
  22090. ], Light.prototype, "radius", null);
  22091. __decorate([
  22092. BABYLON.serialize()
  22093. ], Light.prototype, "_renderPriority", void 0);
  22094. __decorate([
  22095. BABYLON.expandToProperty("_reorderLightsInScene")
  22096. ], Light.prototype, "renderPriority", void 0);
  22097. __decorate([
  22098. BABYLON.serialize("shadowEnabled")
  22099. ], Light.prototype, "_shadowEnabled", void 0);
  22100. __decorate([
  22101. BABYLON.serialize("excludeWithLayerMask")
  22102. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22103. __decorate([
  22104. BABYLON.serialize("includeOnlyWithLayerMask")
  22105. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22106. __decorate([
  22107. BABYLON.serialize("lightmapMode")
  22108. ], Light.prototype, "_lightmapMode", void 0);
  22109. return Light;
  22110. }(BABYLON.Node));
  22111. BABYLON.Light = Light;
  22112. })(BABYLON || (BABYLON = {}));
  22113. //# sourceMappingURL=babylon.light.js.map
  22114. var BABYLON;
  22115. (function (BABYLON) {
  22116. var Camera = /** @class */ (function (_super) {
  22117. __extends(Camera, _super);
  22118. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22119. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22120. var _this = _super.call(this, name, scene) || this;
  22121. /**
  22122. * The vector the camera should consider as up.
  22123. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22124. */
  22125. _this.upVector = BABYLON.Vector3.Up();
  22126. _this.orthoLeft = null;
  22127. _this.orthoRight = null;
  22128. _this.orthoBottom = null;
  22129. _this.orthoTop = null;
  22130. /**
  22131. * FOV is set in Radians. (default is 0.8)
  22132. */
  22133. _this.fov = 0.8;
  22134. _this.minZ = 1;
  22135. _this.maxZ = 10000.0;
  22136. _this.inertia = 0.9;
  22137. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22138. _this.isIntermediate = false;
  22139. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22140. /**
  22141. * Restricts the camera to viewing objects with the same layerMask.
  22142. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22143. */
  22144. _this.layerMask = 0x0FFFFFFF;
  22145. /**
  22146. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22147. */
  22148. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22149. // Camera rig members
  22150. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22151. /** @hidden */
  22152. _this._rigCameras = new Array();
  22153. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22154. /** @hidden */
  22155. _this._skipRendering = false;
  22156. _this.customRenderTargets = new Array();
  22157. // Observables
  22158. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22159. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22160. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22161. _this.onRestoreStateObservable = new BABYLON.Observable();
  22162. // Cache
  22163. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22164. _this._projectionMatrix = new BABYLON.Matrix();
  22165. _this._doNotComputeProjectionMatrix = false;
  22166. _this._postProcesses = new Array();
  22167. _this._transformMatrix = BABYLON.Matrix.Zero();
  22168. _this._activeMeshes = new BABYLON.SmartArray(256);
  22169. _this._globalPosition = BABYLON.Vector3.Zero();
  22170. _this._refreshFrustumPlanes = true;
  22171. _this.getScene().addCamera(_this);
  22172. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22173. _this.getScene().activeCamera = _this;
  22174. }
  22175. _this.position = position;
  22176. return _this;
  22177. }
  22178. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22179. get: function () {
  22180. return Camera._PERSPECTIVE_CAMERA;
  22181. },
  22182. enumerable: true,
  22183. configurable: true
  22184. });
  22185. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22186. get: function () {
  22187. return Camera._ORTHOGRAPHIC_CAMERA;
  22188. },
  22189. enumerable: true,
  22190. configurable: true
  22191. });
  22192. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22193. /**
  22194. * This is the default FOV mode for perspective cameras.
  22195. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22196. *
  22197. */
  22198. get: function () {
  22199. return Camera._FOVMODE_VERTICAL_FIXED;
  22200. },
  22201. enumerable: true,
  22202. configurable: true
  22203. });
  22204. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22205. /**
  22206. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22207. *
  22208. */
  22209. get: function () {
  22210. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22211. },
  22212. enumerable: true,
  22213. configurable: true
  22214. });
  22215. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22216. get: function () {
  22217. return Camera._RIG_MODE_NONE;
  22218. },
  22219. enumerable: true,
  22220. configurable: true
  22221. });
  22222. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22223. get: function () {
  22224. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22225. },
  22226. enumerable: true,
  22227. configurable: true
  22228. });
  22229. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22230. get: function () {
  22231. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22232. },
  22233. enumerable: true,
  22234. configurable: true
  22235. });
  22236. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22237. get: function () {
  22238. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22239. },
  22240. enumerable: true,
  22241. configurable: true
  22242. });
  22243. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22244. get: function () {
  22245. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22246. },
  22247. enumerable: true,
  22248. configurable: true
  22249. });
  22250. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22251. get: function () {
  22252. return Camera._RIG_MODE_VR;
  22253. },
  22254. enumerable: true,
  22255. configurable: true
  22256. });
  22257. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22258. get: function () {
  22259. return Camera._RIG_MODE_WEBVR;
  22260. },
  22261. enumerable: true,
  22262. configurable: true
  22263. });
  22264. /**
  22265. * Store current camera state (fov, position, etc..)
  22266. */
  22267. Camera.prototype.storeState = function () {
  22268. this._stateStored = true;
  22269. this._storedFov = this.fov;
  22270. return this;
  22271. };
  22272. /**
  22273. * Restores the camera state values if it has been stored. You must call storeState() first
  22274. */
  22275. Camera.prototype._restoreStateValues = function () {
  22276. if (!this._stateStored) {
  22277. return false;
  22278. }
  22279. this.fov = this._storedFov;
  22280. return true;
  22281. };
  22282. /**
  22283. * Restored camera state. You must call storeState() first
  22284. */
  22285. Camera.prototype.restoreState = function () {
  22286. if (this._restoreStateValues()) {
  22287. this.onRestoreStateObservable.notifyObservers(this);
  22288. return true;
  22289. }
  22290. return false;
  22291. };
  22292. Camera.prototype.getClassName = function () {
  22293. return "Camera";
  22294. };
  22295. /**
  22296. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22297. */
  22298. Camera.prototype.toString = function (fullDetails) {
  22299. var ret = "Name: " + this.name;
  22300. ret += ", type: " + this.getClassName();
  22301. if (this.animations) {
  22302. for (var i = 0; i < this.animations.length; i++) {
  22303. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22304. }
  22305. }
  22306. if (fullDetails) {
  22307. }
  22308. return ret;
  22309. };
  22310. Object.defineProperty(Camera.prototype, "globalPosition", {
  22311. get: function () {
  22312. return this._globalPosition;
  22313. },
  22314. enumerable: true,
  22315. configurable: true
  22316. });
  22317. Camera.prototype.getActiveMeshes = function () {
  22318. return this._activeMeshes;
  22319. };
  22320. Camera.prototype.isActiveMesh = function (mesh) {
  22321. return (this._activeMeshes.indexOf(mesh) !== -1);
  22322. };
  22323. /**
  22324. * Is this camera ready to be used/rendered
  22325. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22326. * @return true if the camera is ready
  22327. */
  22328. Camera.prototype.isReady = function (completeCheck) {
  22329. if (completeCheck === void 0) { completeCheck = false; }
  22330. if (completeCheck) {
  22331. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22332. var pp = _a[_i];
  22333. if (pp && !pp.isReady()) {
  22334. return false;
  22335. }
  22336. }
  22337. }
  22338. return _super.prototype.isReady.call(this, completeCheck);
  22339. };
  22340. //Cache
  22341. /** @hidden */
  22342. Camera.prototype._initCache = function () {
  22343. _super.prototype._initCache.call(this);
  22344. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22345. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22346. this._cache.mode = undefined;
  22347. this._cache.minZ = undefined;
  22348. this._cache.maxZ = undefined;
  22349. this._cache.fov = undefined;
  22350. this._cache.fovMode = undefined;
  22351. this._cache.aspectRatio = undefined;
  22352. this._cache.orthoLeft = undefined;
  22353. this._cache.orthoRight = undefined;
  22354. this._cache.orthoBottom = undefined;
  22355. this._cache.orthoTop = undefined;
  22356. this._cache.renderWidth = undefined;
  22357. this._cache.renderHeight = undefined;
  22358. };
  22359. /** @hidden */
  22360. Camera.prototype._updateCache = function (ignoreParentClass) {
  22361. if (!ignoreParentClass) {
  22362. _super.prototype._updateCache.call(this);
  22363. }
  22364. this._cache.position.copyFrom(this.position);
  22365. this._cache.upVector.copyFrom(this.upVector);
  22366. };
  22367. // Synchronized
  22368. /** @hidden */
  22369. Camera.prototype._isSynchronized = function () {
  22370. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22371. };
  22372. /** @hidden */
  22373. Camera.prototype._isSynchronizedViewMatrix = function () {
  22374. if (!_super.prototype._isSynchronized.call(this))
  22375. return false;
  22376. return this._cache.position.equals(this.position)
  22377. && this._cache.upVector.equals(this.upVector)
  22378. && this.isSynchronizedWithParent();
  22379. };
  22380. /** @hidden */
  22381. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22382. var check = this._cache.mode === this.mode
  22383. && this._cache.minZ === this.minZ
  22384. && this._cache.maxZ === this.maxZ;
  22385. if (!check) {
  22386. return false;
  22387. }
  22388. var engine = this.getEngine();
  22389. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22390. check = this._cache.fov === this.fov
  22391. && this._cache.fovMode === this.fovMode
  22392. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22393. }
  22394. else {
  22395. check = this._cache.orthoLeft === this.orthoLeft
  22396. && this._cache.orthoRight === this.orthoRight
  22397. && this._cache.orthoBottom === this.orthoBottom
  22398. && this._cache.orthoTop === this.orthoTop
  22399. && this._cache.renderWidth === engine.getRenderWidth()
  22400. && this._cache.renderHeight === engine.getRenderHeight();
  22401. }
  22402. return check;
  22403. };
  22404. // Controls
  22405. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22406. };
  22407. Camera.prototype.detachControl = function (element) {
  22408. };
  22409. Camera.prototype.update = function () {
  22410. this._checkInputs();
  22411. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22412. this._updateRigCameras();
  22413. }
  22414. };
  22415. /** @hidden */
  22416. Camera.prototype._checkInputs = function () {
  22417. this.onAfterCheckInputsObservable.notifyObservers(this);
  22418. };
  22419. Object.defineProperty(Camera.prototype, "rigCameras", {
  22420. get: function () {
  22421. return this._rigCameras;
  22422. },
  22423. enumerable: true,
  22424. configurable: true
  22425. });
  22426. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22427. get: function () {
  22428. return this._rigPostProcess;
  22429. },
  22430. enumerable: true,
  22431. configurable: true
  22432. });
  22433. /**
  22434. * Internal, gets the first post proces.
  22435. * @returns the first post process to be run on this camera.
  22436. */
  22437. Camera.prototype._getFirstPostProcess = function () {
  22438. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22439. if (this._postProcesses[ppIndex] !== null) {
  22440. return this._postProcesses[ppIndex];
  22441. }
  22442. }
  22443. return null;
  22444. };
  22445. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22446. // invalidate framebuffer
  22447. var firstPostProcess = this._getFirstPostProcess();
  22448. if (firstPostProcess) {
  22449. firstPostProcess.markTextureDirty();
  22450. }
  22451. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22452. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22453. var cam = this._rigCameras[i];
  22454. var rigPostProcess = cam._rigPostProcess;
  22455. // for VR rig, there does not have to be a post process
  22456. if (rigPostProcess) {
  22457. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22458. if (isPass) {
  22459. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22460. cam.isIntermediate = this._postProcesses.length === 0;
  22461. }
  22462. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22463. rigPostProcess.markTextureDirty();
  22464. }
  22465. else {
  22466. cam._postProcesses = this._postProcesses.slice(0);
  22467. }
  22468. }
  22469. };
  22470. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22471. if (insertAt === void 0) { insertAt = null; }
  22472. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22473. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22474. return 0;
  22475. }
  22476. if (insertAt == null || insertAt < 0) {
  22477. this._postProcesses.push(postProcess);
  22478. }
  22479. else if (this._postProcesses[insertAt] === null) {
  22480. this._postProcesses[insertAt] = postProcess;
  22481. }
  22482. else {
  22483. this._postProcesses.splice(insertAt, 0, postProcess);
  22484. }
  22485. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22486. return this._postProcesses.indexOf(postProcess);
  22487. };
  22488. Camera.prototype.detachPostProcess = function (postProcess) {
  22489. var idx = this._postProcesses.indexOf(postProcess);
  22490. if (idx !== -1) {
  22491. this._postProcesses[idx] = null;
  22492. }
  22493. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22494. };
  22495. Camera.prototype.getWorldMatrix = function () {
  22496. if (this._isSynchronizedViewMatrix()) {
  22497. return this._worldMatrix;
  22498. }
  22499. // Getting the the view matrix will also compute the world matrix.
  22500. this.getViewMatrix();
  22501. return this._worldMatrix;
  22502. };
  22503. /** @hidden */
  22504. Camera.prototype._getViewMatrix = function () {
  22505. return BABYLON.Matrix.Identity();
  22506. };
  22507. Camera.prototype.getViewMatrix = function (force) {
  22508. if (!force && this._isSynchronizedViewMatrix()) {
  22509. return this._computedViewMatrix;
  22510. }
  22511. this.updateCache();
  22512. this._computedViewMatrix = this._getViewMatrix();
  22513. this._currentRenderId = this.getScene().getRenderId();
  22514. this._childRenderId = this._currentRenderId;
  22515. this._refreshFrustumPlanes = true;
  22516. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22517. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22518. }
  22519. this.onViewMatrixChangedObservable.notifyObservers(this);
  22520. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22521. return this._computedViewMatrix;
  22522. };
  22523. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22524. this._doNotComputeProjectionMatrix = true;
  22525. if (projection !== undefined) {
  22526. this._projectionMatrix = projection;
  22527. }
  22528. };
  22529. ;
  22530. Camera.prototype.unfreezeProjectionMatrix = function () {
  22531. this._doNotComputeProjectionMatrix = false;
  22532. };
  22533. ;
  22534. Camera.prototype.getProjectionMatrix = function (force) {
  22535. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22536. return this._projectionMatrix;
  22537. }
  22538. // Cache
  22539. this._cache.mode = this.mode;
  22540. this._cache.minZ = this.minZ;
  22541. this._cache.maxZ = this.maxZ;
  22542. // Matrix
  22543. this._refreshFrustumPlanes = true;
  22544. var engine = this.getEngine();
  22545. var scene = this.getScene();
  22546. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22547. this._cache.fov = this.fov;
  22548. this._cache.fovMode = this.fovMode;
  22549. this._cache.aspectRatio = engine.getAspectRatio(this);
  22550. if (this.minZ <= 0) {
  22551. this.minZ = 0.1;
  22552. }
  22553. if (scene.useRightHandedSystem) {
  22554. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22555. }
  22556. else {
  22557. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22558. }
  22559. }
  22560. else {
  22561. var halfWidth = engine.getRenderWidth() / 2.0;
  22562. var halfHeight = engine.getRenderHeight() / 2.0;
  22563. if (scene.useRightHandedSystem) {
  22564. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22565. }
  22566. else {
  22567. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22568. }
  22569. this._cache.orthoLeft = this.orthoLeft;
  22570. this._cache.orthoRight = this.orthoRight;
  22571. this._cache.orthoBottom = this.orthoBottom;
  22572. this._cache.orthoTop = this.orthoTop;
  22573. this._cache.renderWidth = engine.getRenderWidth();
  22574. this._cache.renderHeight = engine.getRenderHeight();
  22575. }
  22576. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22577. return this._projectionMatrix;
  22578. };
  22579. /**
  22580. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22581. * @returns a Matrix
  22582. */
  22583. Camera.prototype.getTransformationMatrix = function () {
  22584. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22585. return this._transformMatrix;
  22586. };
  22587. Camera.prototype.updateFrustumPlanes = function () {
  22588. if (!this._refreshFrustumPlanes) {
  22589. return;
  22590. }
  22591. this.getTransformationMatrix();
  22592. if (!this._frustumPlanes) {
  22593. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22594. }
  22595. else {
  22596. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22597. }
  22598. this._refreshFrustumPlanes = false;
  22599. };
  22600. Camera.prototype.isInFrustum = function (target) {
  22601. this.updateFrustumPlanes();
  22602. return target.isInFrustum(this._frustumPlanes);
  22603. };
  22604. Camera.prototype.isCompletelyInFrustum = function (target) {
  22605. this.updateFrustumPlanes();
  22606. return target.isCompletelyInFrustum(this._frustumPlanes);
  22607. };
  22608. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22609. if (length === void 0) { length = 100; }
  22610. if (!transform) {
  22611. transform = this.getWorldMatrix();
  22612. }
  22613. if (!origin) {
  22614. origin = this.position;
  22615. }
  22616. var forward = new BABYLON.Vector3(0, 0, 1);
  22617. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22618. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22619. return new BABYLON.Ray(origin, direction, length);
  22620. };
  22621. /**
  22622. * Releases resources associated with this node.
  22623. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22624. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22625. */
  22626. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22627. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22628. // Observables
  22629. this.onViewMatrixChangedObservable.clear();
  22630. this.onProjectionMatrixChangedObservable.clear();
  22631. this.onAfterCheckInputsObservable.clear();
  22632. this.onRestoreStateObservable.clear();
  22633. // Inputs
  22634. if (this.inputs) {
  22635. this.inputs.clear();
  22636. }
  22637. // Animations
  22638. this.getScene().stopAnimation(this);
  22639. // Remove from scene
  22640. this.getScene().removeCamera(this);
  22641. while (this._rigCameras.length > 0) {
  22642. var camera = this._rigCameras.pop();
  22643. if (camera) {
  22644. camera.dispose();
  22645. }
  22646. }
  22647. // Postprocesses
  22648. if (this._rigPostProcess) {
  22649. this._rigPostProcess.dispose(this);
  22650. this._rigPostProcess = null;
  22651. this._postProcesses = [];
  22652. }
  22653. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22654. this._rigPostProcess = null;
  22655. this._postProcesses = [];
  22656. }
  22657. else {
  22658. var i = this._postProcesses.length;
  22659. while (--i >= 0) {
  22660. var postProcess = this._postProcesses[i];
  22661. if (postProcess) {
  22662. postProcess.dispose(this);
  22663. }
  22664. }
  22665. }
  22666. // Render targets
  22667. var i = this.customRenderTargets.length;
  22668. while (--i >= 0) {
  22669. this.customRenderTargets[i].dispose();
  22670. }
  22671. this.customRenderTargets = [];
  22672. // Active Meshes
  22673. this._activeMeshes.dispose();
  22674. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22675. };
  22676. Object.defineProperty(Camera.prototype, "leftCamera", {
  22677. // ---- Camera rigs section ----
  22678. get: function () {
  22679. if (this._rigCameras.length < 1) {
  22680. return null;
  22681. }
  22682. return this._rigCameras[0];
  22683. },
  22684. enumerable: true,
  22685. configurable: true
  22686. });
  22687. Object.defineProperty(Camera.prototype, "rightCamera", {
  22688. get: function () {
  22689. if (this._rigCameras.length < 2) {
  22690. return null;
  22691. }
  22692. return this._rigCameras[1];
  22693. },
  22694. enumerable: true,
  22695. configurable: true
  22696. });
  22697. Camera.prototype.getLeftTarget = function () {
  22698. if (this._rigCameras.length < 1) {
  22699. return null;
  22700. }
  22701. return this._rigCameras[0].getTarget();
  22702. };
  22703. Camera.prototype.getRightTarget = function () {
  22704. if (this._rigCameras.length < 2) {
  22705. return null;
  22706. }
  22707. return this._rigCameras[1].getTarget();
  22708. };
  22709. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22710. if (this.cameraRigMode === mode) {
  22711. return;
  22712. }
  22713. while (this._rigCameras.length > 0) {
  22714. var camera = this._rigCameras.pop();
  22715. if (camera) {
  22716. camera.dispose();
  22717. }
  22718. }
  22719. this.cameraRigMode = mode;
  22720. this._cameraRigParams = {};
  22721. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22722. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22723. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22724. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22725. // create the rig cameras, unless none
  22726. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22727. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22728. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22729. if (leftCamera && rightCamera) {
  22730. this._rigCameras.push(leftCamera);
  22731. this._rigCameras.push(rightCamera);
  22732. }
  22733. }
  22734. switch (this.cameraRigMode) {
  22735. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22736. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22737. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22738. break;
  22739. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22740. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22741. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22742. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22743. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22744. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22745. break;
  22746. case Camera.RIG_MODE_VR:
  22747. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22748. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22749. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22750. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22751. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22752. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22753. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22754. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22755. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22756. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22757. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22758. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22759. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22760. if (metrics.compensateDistortion) {
  22761. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22762. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22763. }
  22764. break;
  22765. case Camera.RIG_MODE_WEBVR:
  22766. if (rigParams.vrDisplay) {
  22767. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22768. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22769. //Left eye
  22770. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22771. this._rigCameras[0].setCameraRigParameter("left", true);
  22772. //leaving this for future reference
  22773. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22774. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22775. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22776. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22777. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22778. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22779. this._rigCameras[0].parent = this;
  22780. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22781. //Right eye
  22782. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22783. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22784. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22785. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22786. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22787. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22788. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22789. this._rigCameras[1].parent = this;
  22790. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22791. if (Camera.UseAlternateWebVRRendering) {
  22792. this._rigCameras[1]._skipRendering = true;
  22793. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22794. }
  22795. }
  22796. break;
  22797. }
  22798. this._cascadePostProcessesToRigCams();
  22799. this.update();
  22800. };
  22801. Camera.prototype._getVRProjectionMatrix = function () {
  22802. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22803. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22804. return this._projectionMatrix;
  22805. };
  22806. Camera.prototype._updateCameraRotationMatrix = function () {
  22807. //Here for WebVR
  22808. };
  22809. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22810. //Here for WebVR
  22811. };
  22812. /**
  22813. * This function MUST be overwritten by the different WebVR cameras available.
  22814. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22815. */
  22816. Camera.prototype._getWebVRProjectionMatrix = function () {
  22817. return BABYLON.Matrix.Identity();
  22818. };
  22819. /**
  22820. * This function MUST be overwritten by the different WebVR cameras available.
  22821. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22822. */
  22823. Camera.prototype._getWebVRViewMatrix = function () {
  22824. return BABYLON.Matrix.Identity();
  22825. };
  22826. Camera.prototype.setCameraRigParameter = function (name, value) {
  22827. if (!this._cameraRigParams) {
  22828. this._cameraRigParams = {};
  22829. }
  22830. this._cameraRigParams[name] = value;
  22831. //provisionnally:
  22832. if (name === "interaxialDistance") {
  22833. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22834. }
  22835. };
  22836. /**
  22837. * needs to be overridden by children so sub has required properties to be copied
  22838. */
  22839. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22840. return null;
  22841. };
  22842. /**
  22843. * May need to be overridden by children
  22844. * @hidden
  22845. */
  22846. Camera.prototype._updateRigCameras = function () {
  22847. for (var i = 0; i < this._rigCameras.length; i++) {
  22848. this._rigCameras[i].minZ = this.minZ;
  22849. this._rigCameras[i].maxZ = this.maxZ;
  22850. this._rigCameras[i].fov = this.fov;
  22851. }
  22852. // only update viewport when ANAGLYPH
  22853. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22854. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22855. }
  22856. };
  22857. /** @hidden */
  22858. Camera.prototype._setupInputs = function () {
  22859. };
  22860. Camera.prototype.serialize = function () {
  22861. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22862. // Type
  22863. serializationObject.type = this.getClassName();
  22864. // Parent
  22865. if (this.parent) {
  22866. serializationObject.parentId = this.parent.id;
  22867. }
  22868. if (this.inputs) {
  22869. this.inputs.serialize(serializationObject);
  22870. }
  22871. // Animations
  22872. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22873. serializationObject.ranges = this.serializeAnimationRanges();
  22874. return serializationObject;
  22875. };
  22876. Camera.prototype.clone = function (name) {
  22877. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22878. };
  22879. Camera.prototype.getDirection = function (localAxis) {
  22880. var result = BABYLON.Vector3.Zero();
  22881. this.getDirectionToRef(localAxis, result);
  22882. return result;
  22883. };
  22884. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22885. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22886. };
  22887. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22888. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22889. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22890. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22891. interaxial_distance: interaxial_distance,
  22892. isStereoscopicSideBySide: isStereoscopicSideBySide
  22893. });
  22894. if (constructorFunc) {
  22895. return constructorFunc;
  22896. }
  22897. // Default to universal camera
  22898. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22899. };
  22900. Camera.prototype.computeWorldMatrix = function () {
  22901. return this.getWorldMatrix();
  22902. };
  22903. Camera.Parse = function (parsedCamera, scene) {
  22904. var type = parsedCamera.type;
  22905. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22906. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22907. // Parent
  22908. if (parsedCamera.parentId) {
  22909. camera._waitingParentId = parsedCamera.parentId;
  22910. }
  22911. //If camera has an input manager, let it parse inputs settings
  22912. if (camera.inputs) {
  22913. camera.inputs.parse(parsedCamera);
  22914. camera._setupInputs();
  22915. }
  22916. if (camera.setPosition) { // need to force position
  22917. camera.position.copyFromFloats(0, 0, 0);
  22918. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22919. }
  22920. // Target
  22921. if (parsedCamera.target) {
  22922. if (camera.setTarget) {
  22923. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22924. }
  22925. }
  22926. // Apply 3d rig, when found
  22927. if (parsedCamera.cameraRigMode) {
  22928. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22929. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22930. }
  22931. // Animations
  22932. if (parsedCamera.animations) {
  22933. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22934. var parsedAnimation = parsedCamera.animations[animationIndex];
  22935. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22936. }
  22937. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22938. }
  22939. if (parsedCamera.autoAnimate) {
  22940. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22941. }
  22942. return camera;
  22943. };
  22944. // Statics
  22945. Camera._PERSPECTIVE_CAMERA = 0;
  22946. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22947. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22948. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22949. Camera._RIG_MODE_NONE = 0;
  22950. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22951. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22952. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22953. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22954. Camera._RIG_MODE_VR = 20;
  22955. Camera._RIG_MODE_WEBVR = 21;
  22956. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22957. Camera.UseAlternateWebVRRendering = false;
  22958. __decorate([
  22959. BABYLON.serializeAsVector3()
  22960. ], Camera.prototype, "position", void 0);
  22961. __decorate([
  22962. BABYLON.serializeAsVector3()
  22963. ], Camera.prototype, "upVector", void 0);
  22964. __decorate([
  22965. BABYLON.serialize()
  22966. ], Camera.prototype, "orthoLeft", void 0);
  22967. __decorate([
  22968. BABYLON.serialize()
  22969. ], Camera.prototype, "orthoRight", void 0);
  22970. __decorate([
  22971. BABYLON.serialize()
  22972. ], Camera.prototype, "orthoBottom", void 0);
  22973. __decorate([
  22974. BABYLON.serialize()
  22975. ], Camera.prototype, "orthoTop", void 0);
  22976. __decorate([
  22977. BABYLON.serialize()
  22978. ], Camera.prototype, "fov", void 0);
  22979. __decorate([
  22980. BABYLON.serialize()
  22981. ], Camera.prototype, "minZ", void 0);
  22982. __decorate([
  22983. BABYLON.serialize()
  22984. ], Camera.prototype, "maxZ", void 0);
  22985. __decorate([
  22986. BABYLON.serialize()
  22987. ], Camera.prototype, "inertia", void 0);
  22988. __decorate([
  22989. BABYLON.serialize()
  22990. ], Camera.prototype, "mode", void 0);
  22991. __decorate([
  22992. BABYLON.serialize()
  22993. ], Camera.prototype, "layerMask", void 0);
  22994. __decorate([
  22995. BABYLON.serialize()
  22996. ], Camera.prototype, "fovMode", void 0);
  22997. __decorate([
  22998. BABYLON.serialize()
  22999. ], Camera.prototype, "cameraRigMode", void 0);
  23000. __decorate([
  23001. BABYLON.serialize()
  23002. ], Camera.prototype, "interaxialDistance", void 0);
  23003. __decorate([
  23004. BABYLON.serialize()
  23005. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23006. return Camera;
  23007. }(BABYLON.Node));
  23008. BABYLON.Camera = Camera;
  23009. })(BABYLON || (BABYLON = {}));
  23010. //# sourceMappingURL=babylon.camera.js.map
  23011. var BABYLON;
  23012. (function (BABYLON) {
  23013. var RenderingManager = /** @class */ (function () {
  23014. function RenderingManager(scene) {
  23015. /**
  23016. * @hidden
  23017. */
  23018. this._useSceneAutoClearSetup = false;
  23019. this._renderingGroups = new Array();
  23020. this._autoClearDepthStencil = {};
  23021. this._customOpaqueSortCompareFn = {};
  23022. this._customAlphaTestSortCompareFn = {};
  23023. this._customTransparentSortCompareFn = {};
  23024. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23025. this._scene = scene;
  23026. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23027. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23028. }
  23029. }
  23030. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23031. if (depth === void 0) { depth = true; }
  23032. if (stencil === void 0) { stencil = true; }
  23033. if (this._depthStencilBufferAlreadyCleaned) {
  23034. return;
  23035. }
  23036. this._scene.getEngine().clear(null, false, depth, stencil);
  23037. this._depthStencilBufferAlreadyCleaned = true;
  23038. };
  23039. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23040. // Update the observable context (not null as it only goes away on dispose)
  23041. var info = this._renderingGroupInfo;
  23042. info.scene = this._scene;
  23043. info.camera = this._scene.activeCamera;
  23044. // Dispatch sprites
  23045. if (this._scene.spriteManagers && renderSprites) {
  23046. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23047. var manager = this._scene.spriteManagers[index];
  23048. this.dispatchSprites(manager);
  23049. }
  23050. }
  23051. // Render
  23052. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23053. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23054. var renderingGroup = this._renderingGroups[index];
  23055. if (!renderingGroup)
  23056. continue;
  23057. var renderingGroupMask = Math.pow(2, index);
  23058. info.renderingGroupId = index;
  23059. // Before Observable
  23060. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23061. // Clear depth/stencil if needed
  23062. if (RenderingManager.AUTOCLEAR) {
  23063. var autoClear = this._useSceneAutoClearSetup ?
  23064. this._scene.getAutoClearDepthStencilSetup(index) :
  23065. this._autoClearDepthStencil[index];
  23066. if (autoClear && autoClear.autoClear) {
  23067. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23068. }
  23069. }
  23070. // Render
  23071. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23072. var step = _a[_i];
  23073. step.action(index);
  23074. }
  23075. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23076. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23077. var step = _c[_b];
  23078. step.action(index);
  23079. }
  23080. // After Observable
  23081. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23082. }
  23083. };
  23084. RenderingManager.prototype.reset = function () {
  23085. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23086. var renderingGroup = this._renderingGroups[index];
  23087. if (renderingGroup) {
  23088. renderingGroup.prepare();
  23089. }
  23090. }
  23091. };
  23092. RenderingManager.prototype.dispose = function () {
  23093. this.freeRenderingGroups();
  23094. this._renderingGroups.length = 0;
  23095. this._renderingGroupInfo = null;
  23096. };
  23097. /**
  23098. * Clear the info related to rendering groups preventing retention points during dispose.
  23099. */
  23100. RenderingManager.prototype.freeRenderingGroups = function () {
  23101. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23102. var renderingGroup = this._renderingGroups[index];
  23103. if (renderingGroup) {
  23104. renderingGroup.dispose();
  23105. }
  23106. }
  23107. };
  23108. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23109. if (this._renderingGroups[renderingGroupId] === undefined) {
  23110. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23111. }
  23112. };
  23113. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23114. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23115. this._prepareRenderingGroup(renderingGroupId);
  23116. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23117. };
  23118. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23119. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23120. this._prepareRenderingGroup(renderingGroupId);
  23121. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23122. };
  23123. /**
  23124. * @param subMesh The submesh to dispatch
  23125. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23126. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23127. */
  23128. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23129. if (mesh === undefined) {
  23130. mesh = subMesh.getMesh();
  23131. }
  23132. var renderingGroupId = mesh.renderingGroupId || 0;
  23133. this._prepareRenderingGroup(renderingGroupId);
  23134. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23135. };
  23136. /**
  23137. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23138. * This allowed control for front to back rendering or reversly depending of the special needs.
  23139. *
  23140. * @param renderingGroupId The rendering group id corresponding to its index
  23141. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23142. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23143. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23144. */
  23145. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23146. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23147. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23148. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23149. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23150. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23151. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23152. if (this._renderingGroups[renderingGroupId]) {
  23153. var group = this._renderingGroups[renderingGroupId];
  23154. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23155. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23156. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23157. }
  23158. };
  23159. /**
  23160. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23161. *
  23162. * @param renderingGroupId The rendering group id corresponding to its index
  23163. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23164. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23165. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23166. */
  23167. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23168. if (depth === void 0) { depth = true; }
  23169. if (stencil === void 0) { stencil = true; }
  23170. this._autoClearDepthStencil[renderingGroupId] = {
  23171. autoClear: autoClearDepthStencil,
  23172. depth: depth,
  23173. stencil: stencil
  23174. };
  23175. };
  23176. /**
  23177. * Gets the current auto clear configuration for one rendering group of the rendering
  23178. * manager.
  23179. * @param index the rendering group index to get the information for
  23180. * @returns The auto clear setup for the requested rendering group
  23181. */
  23182. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23183. return this._autoClearDepthStencil[index];
  23184. };
  23185. /**
  23186. * The max id used for rendering groups (not included)
  23187. */
  23188. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23189. /**
  23190. * The min id used for rendering groups (included)
  23191. */
  23192. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23193. /**
  23194. * Used to globally prevent autoclearing scenes.
  23195. */
  23196. RenderingManager.AUTOCLEAR = true;
  23197. return RenderingManager;
  23198. }());
  23199. BABYLON.RenderingManager = RenderingManager;
  23200. })(BABYLON || (BABYLON = {}));
  23201. //# sourceMappingURL=babylon.renderingManager.js.map
  23202. var BABYLON;
  23203. (function (BABYLON) {
  23204. var RenderingGroup = /** @class */ (function () {
  23205. /**
  23206. * Creates a new rendering group.
  23207. * @param index The rendering group index
  23208. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23209. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23210. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23211. */
  23212. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23213. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23214. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23215. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23216. this.index = index;
  23217. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23218. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23219. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23220. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23221. this._particleSystems = new BABYLON.SmartArray(256);
  23222. this._spriteManagers = new BABYLON.SmartArray(256);
  23223. this._edgesRenderers = new BABYLON.SmartArray(16);
  23224. this._scene = scene;
  23225. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23226. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23227. this.transparentSortCompareFn = transparentSortCompareFn;
  23228. }
  23229. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23230. /**
  23231. * Set the opaque sort comparison function.
  23232. * If null the sub meshes will be render in the order they were created
  23233. */
  23234. set: function (value) {
  23235. this._opaqueSortCompareFn = value;
  23236. if (value) {
  23237. this._renderOpaque = this.renderOpaqueSorted;
  23238. }
  23239. else {
  23240. this._renderOpaque = RenderingGroup.renderUnsorted;
  23241. }
  23242. },
  23243. enumerable: true,
  23244. configurable: true
  23245. });
  23246. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23247. /**
  23248. * Set the alpha test sort comparison function.
  23249. * If null the sub meshes will be render in the order they were created
  23250. */
  23251. set: function (value) {
  23252. this._alphaTestSortCompareFn = value;
  23253. if (value) {
  23254. this._renderAlphaTest = this.renderAlphaTestSorted;
  23255. }
  23256. else {
  23257. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23258. }
  23259. },
  23260. enumerable: true,
  23261. configurable: true
  23262. });
  23263. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23264. /**
  23265. * Set the transparent sort comparison function.
  23266. * If null the sub meshes will be render in the order they were created
  23267. */
  23268. set: function (value) {
  23269. if (value) {
  23270. this._transparentSortCompareFn = value;
  23271. }
  23272. else {
  23273. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23274. }
  23275. this._renderTransparent = this.renderTransparentSorted;
  23276. },
  23277. enumerable: true,
  23278. configurable: true
  23279. });
  23280. /**
  23281. * Render all the sub meshes contained in the group.
  23282. * @param customRenderFunction Used to override the default render behaviour of the group.
  23283. * @returns true if rendered some submeshes.
  23284. */
  23285. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23286. if (customRenderFunction) {
  23287. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23288. return;
  23289. }
  23290. var engine = this._scene.getEngine();
  23291. // Depth only
  23292. if (this._depthOnlySubMeshes.length !== 0) {
  23293. engine.setColorWrite(false);
  23294. this._renderAlphaTest(this._depthOnlySubMeshes);
  23295. engine.setColorWrite(true);
  23296. }
  23297. // Opaque
  23298. if (this._opaqueSubMeshes.length !== 0) {
  23299. this._renderOpaque(this._opaqueSubMeshes);
  23300. }
  23301. // Alpha test
  23302. if (this._alphaTestSubMeshes.length !== 0) {
  23303. this._renderAlphaTest(this._alphaTestSubMeshes);
  23304. }
  23305. var stencilState = engine.getStencilBuffer();
  23306. engine.setStencilBuffer(false);
  23307. // Sprites
  23308. if (renderSprites) {
  23309. this._renderSprites();
  23310. }
  23311. // Particles
  23312. if (renderParticles) {
  23313. this._renderParticles(activeMeshes);
  23314. }
  23315. if (this.onBeforeTransparentRendering) {
  23316. this.onBeforeTransparentRendering();
  23317. }
  23318. // Transparent
  23319. if (this._transparentSubMeshes.length !== 0) {
  23320. this._renderTransparent(this._transparentSubMeshes);
  23321. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23322. }
  23323. // Set back stencil to false in case it changes before the edge renderer.
  23324. engine.setStencilBuffer(false);
  23325. // Edges
  23326. if (this._edgesRenderers.length) {
  23327. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23328. this._edgesRenderers.data[edgesRendererIndex].render();
  23329. }
  23330. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23331. }
  23332. // Restore Stencil state.
  23333. engine.setStencilBuffer(stencilState);
  23334. };
  23335. /**
  23336. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23337. * @param subMeshes The submeshes to render
  23338. */
  23339. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23340. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23341. };
  23342. /**
  23343. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23344. * @param subMeshes The submeshes to render
  23345. */
  23346. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23347. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23348. };
  23349. /**
  23350. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23351. * @param subMeshes The submeshes to render
  23352. */
  23353. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23354. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23355. };
  23356. /**
  23357. * Renders the submeshes in a specified order.
  23358. * @param subMeshes The submeshes to sort before render
  23359. * @param sortCompareFn The comparison function use to sort
  23360. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23361. * @param transparent Specifies to activate blending if true
  23362. */
  23363. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23364. var subIndex = 0;
  23365. var subMesh;
  23366. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23367. for (; subIndex < subMeshes.length; subIndex++) {
  23368. subMesh = subMeshes.data[subIndex];
  23369. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23370. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23371. }
  23372. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23373. if (sortCompareFn) {
  23374. sortedArray.sort(sortCompareFn);
  23375. }
  23376. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23377. subMesh = sortedArray[subIndex];
  23378. if (transparent) {
  23379. var material = subMesh.getMaterial();
  23380. if (material && material.needDepthPrePass) {
  23381. var engine = material.getScene().getEngine();
  23382. engine.setColorWrite(false);
  23383. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23384. subMesh.render(false);
  23385. engine.setColorWrite(true);
  23386. }
  23387. }
  23388. subMesh.render(transparent);
  23389. }
  23390. };
  23391. /**
  23392. * Renders the submeshes in the order they were dispatched (no sort applied).
  23393. * @param subMeshes The submeshes to render
  23394. */
  23395. RenderingGroup.renderUnsorted = function (subMeshes) {
  23396. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23397. var submesh = subMeshes.data[subIndex];
  23398. submesh.render(false);
  23399. }
  23400. };
  23401. /**
  23402. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23403. * are rendered back to front if in the same alpha index.
  23404. *
  23405. * @param a The first submesh
  23406. * @param b The second submesh
  23407. * @returns The result of the comparison
  23408. */
  23409. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23410. // Alpha index first
  23411. if (a._alphaIndex > b._alphaIndex) {
  23412. return 1;
  23413. }
  23414. if (a._alphaIndex < b._alphaIndex) {
  23415. return -1;
  23416. }
  23417. // Then distance to camera
  23418. return RenderingGroup.backToFrontSortCompare(a, b);
  23419. };
  23420. /**
  23421. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23422. * are rendered back to front.
  23423. *
  23424. * @param a The first submesh
  23425. * @param b The second submesh
  23426. * @returns The result of the comparison
  23427. */
  23428. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23429. // Then distance to camera
  23430. if (a._distanceToCamera < b._distanceToCamera) {
  23431. return 1;
  23432. }
  23433. if (a._distanceToCamera > b._distanceToCamera) {
  23434. return -1;
  23435. }
  23436. return 0;
  23437. };
  23438. /**
  23439. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23440. * are rendered front to back (prevent overdraw).
  23441. *
  23442. * @param a The first submesh
  23443. * @param b The second submesh
  23444. * @returns The result of the comparison
  23445. */
  23446. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23447. // Then distance to camera
  23448. if (a._distanceToCamera < b._distanceToCamera) {
  23449. return -1;
  23450. }
  23451. if (a._distanceToCamera > b._distanceToCamera) {
  23452. return 1;
  23453. }
  23454. return 0;
  23455. };
  23456. /**
  23457. * Resets the different lists of submeshes to prepare a new frame.
  23458. */
  23459. RenderingGroup.prototype.prepare = function () {
  23460. this._opaqueSubMeshes.reset();
  23461. this._transparentSubMeshes.reset();
  23462. this._alphaTestSubMeshes.reset();
  23463. this._depthOnlySubMeshes.reset();
  23464. this._particleSystems.reset();
  23465. this._spriteManagers.reset();
  23466. this._edgesRenderers.reset();
  23467. };
  23468. RenderingGroup.prototype.dispose = function () {
  23469. this._opaqueSubMeshes.dispose();
  23470. this._transparentSubMeshes.dispose();
  23471. this._alphaTestSubMeshes.dispose();
  23472. this._depthOnlySubMeshes.dispose();
  23473. this._particleSystems.dispose();
  23474. this._spriteManagers.dispose();
  23475. this._edgesRenderers.dispose();
  23476. };
  23477. /**
  23478. * Inserts the submesh in its correct queue depending on its material.
  23479. * @param subMesh The submesh to dispatch
  23480. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23481. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23482. */
  23483. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23484. // Get mesh and materials if not provided
  23485. if (mesh === undefined) {
  23486. mesh = subMesh.getMesh();
  23487. }
  23488. if (material === undefined) {
  23489. material = subMesh.getMaterial();
  23490. }
  23491. if (material === null || material === undefined) {
  23492. return;
  23493. }
  23494. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23495. this._transparentSubMeshes.push(subMesh);
  23496. }
  23497. else if (material.needAlphaTesting()) { // Alpha test
  23498. if (material.needDepthPrePass) {
  23499. this._depthOnlySubMeshes.push(subMesh);
  23500. }
  23501. this._alphaTestSubMeshes.push(subMesh);
  23502. }
  23503. else {
  23504. if (material.needDepthPrePass) {
  23505. this._depthOnlySubMeshes.push(subMesh);
  23506. }
  23507. this._opaqueSubMeshes.push(subMesh); // Opaque
  23508. }
  23509. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23510. this._edgesRenderers.push(mesh._edgesRenderer);
  23511. }
  23512. };
  23513. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23514. this._spriteManagers.push(spriteManager);
  23515. };
  23516. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23517. this._particleSystems.push(particleSystem);
  23518. };
  23519. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23520. if (this._particleSystems.length === 0) {
  23521. return;
  23522. }
  23523. // Particles
  23524. var activeCamera = this._scene.activeCamera;
  23525. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23526. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23527. var particleSystem = this._particleSystems.data[particleIndex];
  23528. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23529. continue;
  23530. }
  23531. var emitter = particleSystem.emitter;
  23532. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23533. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23534. }
  23535. }
  23536. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23537. };
  23538. RenderingGroup.prototype._renderSprites = function () {
  23539. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23540. return;
  23541. }
  23542. // Sprites
  23543. var activeCamera = this._scene.activeCamera;
  23544. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23545. for (var id = 0; id < this._spriteManagers.length; id++) {
  23546. var spriteManager = this._spriteManagers.data[id];
  23547. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23548. spriteManager.render();
  23549. }
  23550. }
  23551. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23552. };
  23553. return RenderingGroup;
  23554. }());
  23555. BABYLON.RenderingGroup = RenderingGroup;
  23556. })(BABYLON || (BABYLON = {}));
  23557. //# sourceMappingURL=babylon.renderingGroup.js.map
  23558. var BABYLON;
  23559. (function (BABYLON) {
  23560. /**
  23561. * Groups all the scene component constants in one place to ease maintenance.
  23562. * @hidden
  23563. */
  23564. var SceneComponentConstants = /** @class */ (function () {
  23565. function SceneComponentConstants() {
  23566. }
  23567. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23568. SceneComponentConstants.NAME_LAYER = "Layer";
  23569. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23570. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23571. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23572. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23573. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23574. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23575. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23576. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23577. SceneComponentConstants.NAME_SPRITE = "Sprite";
  23578. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  23579. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  23580. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  23581. SceneComponentConstants.NAME_OCTREE = "Octree";
  23582. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  23583. SceneComponentConstants.NAME_AUDIO = "Audio";
  23584. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23585. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23586. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23587. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23588. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23589. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23590. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23591. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  23592. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  23593. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23594. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  23595. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23596. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23597. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  23598. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23599. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23600. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  23601. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  23602. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  23603. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  23604. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  23605. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  23606. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  23607. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  23608. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  23609. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  23610. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  23611. return SceneComponentConstants;
  23612. }());
  23613. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23614. /**
  23615. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23616. * @hidden
  23617. */
  23618. var Stage = /** @class */ (function (_super) {
  23619. __extends(Stage, _super);
  23620. /**
  23621. * Hide ctor from the rest of the world.
  23622. * @param items The items to add.
  23623. */
  23624. function Stage(items) {
  23625. return _super.apply(this, items) || this;
  23626. }
  23627. /**
  23628. * Creates a new Stage.
  23629. * @returns A new instance of a Stage
  23630. */
  23631. Stage.Create = function () {
  23632. return Object.create(Stage.prototype);
  23633. };
  23634. /**
  23635. * Registers a step in an ordered way in the targeted stage.
  23636. * @param index Defines the position to register the step in
  23637. * @param component Defines the component attached to the step
  23638. * @param action Defines the action to launch during the step
  23639. */
  23640. Stage.prototype.registerStep = function (index, component, action) {
  23641. var i = 0;
  23642. var maxIndex = Number.MAX_VALUE;
  23643. for (; i < this.length && i < maxIndex; i++) {
  23644. var step = this[i];
  23645. maxIndex = step.index;
  23646. }
  23647. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23648. };
  23649. /**
  23650. * Clears all the steps from the stage.
  23651. */
  23652. Stage.prototype.clear = function () {
  23653. this.length = 0;
  23654. };
  23655. return Stage;
  23656. }(Array));
  23657. BABYLON.Stage = Stage;
  23658. })(BABYLON || (BABYLON = {}));
  23659. //# sourceMappingURL=babylon.sceneComponent.js.map
  23660. var BABYLON;
  23661. (function (BABYLON) {
  23662. /**
  23663. * Base class of the scene acting as a container for the different elements composing a scene.
  23664. * This class is dynamically extended by the different components of the scene increasing
  23665. * flexibility and reducing coupling
  23666. */
  23667. var AbstractScene = /** @class */ (function () {
  23668. function AbstractScene() {
  23669. /**
  23670. * Gets the list of root nodes (ie. nodes with no parent)
  23671. */
  23672. this.rootNodes = new Array();
  23673. /** All of the cameras added to this scene
  23674. * @see http://doc.babylonjs.com/babylon101/cameras
  23675. */
  23676. this.cameras = new Array();
  23677. /**
  23678. * All of the lights added to this scene
  23679. * @see http://doc.babylonjs.com/babylon101/lights
  23680. */
  23681. this.lights = new Array();
  23682. /**
  23683. * All of the (abstract) meshes added to this scene
  23684. */
  23685. this.meshes = new Array();
  23686. /**
  23687. * The list of skeletons added to the scene
  23688. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23689. */
  23690. this.skeletons = new Array();
  23691. /**
  23692. * All of the particle systems added to this scene
  23693. * @see http://doc.babylonjs.com/babylon101/particles
  23694. */
  23695. this.particleSystems = new Array();
  23696. /**
  23697. * Gets a list of Animations associated with the scene
  23698. */
  23699. this.animations = [];
  23700. /**
  23701. * All of the animation groups added to this scene
  23702. * @see http://doc.babylonjs.com/how_to/group
  23703. */
  23704. this.animationGroups = new Array();
  23705. /**
  23706. * All of the multi-materials added to this scene
  23707. * @see http://doc.babylonjs.com/how_to/multi_materials
  23708. */
  23709. this.multiMaterials = new Array();
  23710. /**
  23711. * All of the materials added to this scene
  23712. * @see http://doc.babylonjs.com/babylon101/materials
  23713. */
  23714. this.materials = new Array();
  23715. /**
  23716. * The list of morph target managers added to the scene
  23717. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23718. */
  23719. this.morphTargetManagers = new Array();
  23720. /**
  23721. * The list of geometries used in the scene.
  23722. */
  23723. this.geometries = new Array();
  23724. /**
  23725. * All of the tranform nodes added to this scene
  23726. * @see http://doc.babylonjs.com/how_to/transformnode
  23727. */
  23728. this.transformNodes = new Array();
  23729. /**
  23730. * ActionManagers available on the scene.
  23731. */
  23732. this.actionManagers = new Array();
  23733. /**
  23734. * Textures to keep.
  23735. */
  23736. this.textures = new Array();
  23737. }
  23738. /**
  23739. * Adds a parser in the list of available ones
  23740. * @param name Defines the name of the parser
  23741. * @param parser Defines the parser to add
  23742. */
  23743. AbstractScene.AddParser = function (name, parser) {
  23744. this._BabylonFileParsers[name] = parser;
  23745. };
  23746. /**
  23747. * Gets a general parser from the list of avaialble ones
  23748. * @param name Defines the name of the parser
  23749. * @returns the requested parser or null
  23750. */
  23751. AbstractScene.GetParser = function (name) {
  23752. if (this._BabylonFileParsers[name]) {
  23753. return this._BabylonFileParsers[name];
  23754. }
  23755. return null;
  23756. };
  23757. /**
  23758. * Adds n individual parser in the list of available ones
  23759. * @param name Defines the name of the parser
  23760. * @param parser Defines the parser to add
  23761. */
  23762. AbstractScene.AddIndividualParser = function (name, parser) {
  23763. this._IndividualBabylonFileParsers[name] = parser;
  23764. };
  23765. /**
  23766. * Gets an individual parser from the list of avaialble ones
  23767. * @param name Defines the name of the parser
  23768. * @returns the requested parser or null
  23769. */
  23770. AbstractScene.GetIndividualParser = function (name) {
  23771. if (this._IndividualBabylonFileParsers[name]) {
  23772. return this._IndividualBabylonFileParsers[name];
  23773. }
  23774. return null;
  23775. };
  23776. /**
  23777. * Parser json data and populate both a scene and its associated container object
  23778. * @param jsonData Defines the data to parse
  23779. * @param scene Defines the scene to parse the data for
  23780. * @param container Defines the container attached to the parsing sequence
  23781. * @param rootUrl Defines the root url of the data
  23782. */
  23783. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23784. for (var parserName in this._BabylonFileParsers) {
  23785. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23786. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23787. }
  23788. }
  23789. };
  23790. /**
  23791. * Stores the list of available parsers in the application.
  23792. */
  23793. AbstractScene._BabylonFileParsers = {};
  23794. /**
  23795. * Stores the list of available individual parsers in the application.
  23796. */
  23797. AbstractScene._IndividualBabylonFileParsers = {};
  23798. return AbstractScene;
  23799. }());
  23800. BABYLON.AbstractScene = AbstractScene;
  23801. })(BABYLON || (BABYLON = {}));
  23802. //# sourceMappingURL=babylon.abstractScene.js.map
  23803. var BABYLON;
  23804. (function (BABYLON) {
  23805. /** @hidden */
  23806. var ClickInfo = /** @class */ (function () {
  23807. function ClickInfo() {
  23808. this._singleClick = false;
  23809. this._doubleClick = false;
  23810. this._hasSwiped = false;
  23811. this._ignore = false;
  23812. }
  23813. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23814. get: function () {
  23815. return this._singleClick;
  23816. },
  23817. set: function (b) {
  23818. this._singleClick = b;
  23819. },
  23820. enumerable: true,
  23821. configurable: true
  23822. });
  23823. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23824. get: function () {
  23825. return this._doubleClick;
  23826. },
  23827. set: function (b) {
  23828. this._doubleClick = b;
  23829. },
  23830. enumerable: true,
  23831. configurable: true
  23832. });
  23833. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23834. get: function () {
  23835. return this._hasSwiped;
  23836. },
  23837. set: function (b) {
  23838. this._hasSwiped = b;
  23839. },
  23840. enumerable: true,
  23841. configurable: true
  23842. });
  23843. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23844. get: function () {
  23845. return this._ignore;
  23846. },
  23847. set: function (b) {
  23848. this._ignore = b;
  23849. },
  23850. enumerable: true,
  23851. configurable: true
  23852. });
  23853. return ClickInfo;
  23854. }());
  23855. /**
  23856. * This class is used by the onRenderingGroupObservable
  23857. */
  23858. var RenderingGroupInfo = /** @class */ (function () {
  23859. function RenderingGroupInfo() {
  23860. }
  23861. return RenderingGroupInfo;
  23862. }());
  23863. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23864. /**
  23865. * Represents a scene to be rendered by the engine.
  23866. * @see http://doc.babylonjs.com/features/scene
  23867. */
  23868. var Scene = /** @class */ (function (_super) {
  23869. __extends(Scene, _super);
  23870. /**
  23871. * Creates a new Scene
  23872. * @param engine defines the engine to use to render this scene
  23873. */
  23874. function Scene(engine) {
  23875. var _this = _super.call(this) || this;
  23876. // Members
  23877. /**
  23878. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23879. */
  23880. _this.autoClear = true;
  23881. /**
  23882. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23883. */
  23884. _this.autoClearDepthAndStencil = true;
  23885. /**
  23886. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23887. */
  23888. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23889. /**
  23890. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23891. */
  23892. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23893. _this._forceWireframe = false;
  23894. _this._forcePointsCloud = false;
  23895. /**
  23896. * Gets or sets a boolean indicating if animations are enabled
  23897. */
  23898. _this.animationsEnabled = true;
  23899. _this._animationPropertiesOverride = null;
  23900. /**
  23901. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23902. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23903. */
  23904. _this.useConstantAnimationDeltaTime = false;
  23905. /**
  23906. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23907. * Please note that it requires to run a ray cast through the scene on every frame
  23908. */
  23909. _this.constantlyUpdateMeshUnderPointer = false;
  23910. /**
  23911. * Defines the HTML cursor to use when hovering over interactive elements
  23912. */
  23913. _this.hoverCursor = "pointer";
  23914. /**
  23915. * Defines the HTML default cursor to use (empty by default)
  23916. */
  23917. _this.defaultCursor = "";
  23918. /**
  23919. * This is used to call preventDefault() on pointer down
  23920. * in order to block unwanted artifacts like system double clicks
  23921. */
  23922. _this.preventDefaultOnPointerDown = true;
  23923. // Metadata
  23924. /**
  23925. * Gets or sets user defined metadata
  23926. */
  23927. _this.metadata = null;
  23928. /**
  23929. * Use this array to add regular expressions used to disable offline support for specific urls
  23930. */
  23931. _this.disableOfflineSupportExceptionRules = new Array();
  23932. /**
  23933. * An event triggered when the scene is disposed.
  23934. */
  23935. _this.onDisposeObservable = new BABYLON.Observable();
  23936. _this._onDisposeObserver = null;
  23937. /**
  23938. * An event triggered before rendering the scene (right after animations and physics)
  23939. */
  23940. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23941. _this._onBeforeRenderObserver = null;
  23942. /**
  23943. * An event triggered after rendering the scene
  23944. */
  23945. _this.onAfterRenderObservable = new BABYLON.Observable();
  23946. _this._onAfterRenderObserver = null;
  23947. /**
  23948. * An event triggered before animating the scene
  23949. */
  23950. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23951. /**
  23952. * An event triggered after animations processing
  23953. */
  23954. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23955. /**
  23956. * An event triggered before draw calls are ready to be sent
  23957. */
  23958. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23959. /**
  23960. * An event triggered after draw calls have been sent
  23961. */
  23962. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23963. /**
  23964. * An event triggered when the scene is ready
  23965. */
  23966. _this.onReadyObservable = new BABYLON.Observable();
  23967. /**
  23968. * An event triggered before rendering a camera
  23969. */
  23970. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23971. _this._onBeforeCameraRenderObserver = null;
  23972. /**
  23973. * An event triggered after rendering a camera
  23974. */
  23975. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23976. _this._onAfterCameraRenderObserver = null;
  23977. /**
  23978. * An event triggered when active meshes evaluation is about to start
  23979. */
  23980. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23981. /**
  23982. * An event triggered when active meshes evaluation is done
  23983. */
  23984. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23985. /**
  23986. * An event triggered when particles rendering is about to start
  23987. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23988. */
  23989. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23990. /**
  23991. * An event triggered when particles rendering is done
  23992. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23993. */
  23994. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23995. /**
  23996. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23997. */
  23998. _this.onDataLoadedObservable = new BABYLON.Observable();
  23999. /**
  24000. * An event triggered when a camera is created
  24001. */
  24002. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24003. /**
  24004. * An event triggered when a camera is removed
  24005. */
  24006. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24007. /**
  24008. * An event triggered when a light is created
  24009. */
  24010. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24011. /**
  24012. * An event triggered when a light is removed
  24013. */
  24014. _this.onLightRemovedObservable = new BABYLON.Observable();
  24015. /**
  24016. * An event triggered when a geometry is created
  24017. */
  24018. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24019. /**
  24020. * An event triggered when a geometry is removed
  24021. */
  24022. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24023. /**
  24024. * An event triggered when a transform node is created
  24025. */
  24026. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24027. /**
  24028. * An event triggered when a transform node is removed
  24029. */
  24030. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24031. /**
  24032. * An event triggered when a mesh is created
  24033. */
  24034. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24035. /**
  24036. * An event triggered when a mesh is removed
  24037. */
  24038. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24039. /**
  24040. * An event triggered when render targets are about to be rendered
  24041. * Can happen multiple times per frame.
  24042. */
  24043. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24044. /**
  24045. * An event triggered when render targets were rendered.
  24046. * Can happen multiple times per frame.
  24047. */
  24048. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24049. /**
  24050. * An event triggered before calculating deterministic simulation step
  24051. */
  24052. _this.onBeforeStepObservable = new BABYLON.Observable();
  24053. /**
  24054. * An event triggered after calculating deterministic simulation step
  24055. */
  24056. _this.onAfterStepObservable = new BABYLON.Observable();
  24057. /**
  24058. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24059. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24060. * 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)
  24061. */
  24062. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24063. /**
  24064. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24065. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24066. * 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)
  24067. */
  24068. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24069. /**
  24070. * This Observable will when a mesh has been imported into the scene.
  24071. */
  24072. _this.onMeshImportedObservable = new BABYLON.Observable();
  24073. // Animations
  24074. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24075. /**
  24076. * 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).
  24077. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24078. */
  24079. _this.onPrePointerObservable = new BABYLON.Observable();
  24080. /**
  24081. * Observable event triggered each time an input event is received from the rendering canvas
  24082. */
  24083. _this.onPointerObservable = new BABYLON.Observable();
  24084. _this._meshPickProceed = false;
  24085. _this._currentPickResult = null;
  24086. _this._previousPickResult = null;
  24087. _this._totalPointersPressed = 0;
  24088. _this._doubleClickOccured = false;
  24089. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24090. _this.cameraToUseForPointers = null;
  24091. _this._pointerX = 0;
  24092. _this._pointerY = 0;
  24093. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24094. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24095. _this._startingPointerTime = 0;
  24096. _this._previousStartingPointerTime = 0;
  24097. _this._pointerCaptures = {};
  24098. // Deterministic lockstep
  24099. _this._timeAccumulator = 0;
  24100. _this._currentStepId = 0;
  24101. _this._currentInternalStep = 0;
  24102. // Keyboard
  24103. /**
  24104. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24105. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24106. */
  24107. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24108. /**
  24109. * Observable event triggered each time an keyboard event is received from the hosting window
  24110. */
  24111. _this.onKeyboardObservable = new BABYLON.Observable();
  24112. // Coordinates system
  24113. _this._useRightHandedSystem = false;
  24114. // Fog
  24115. _this._fogEnabled = true;
  24116. _this._fogMode = Scene.FOGMODE_NONE;
  24117. /**
  24118. * Gets or sets the fog color to use
  24119. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24120. */
  24121. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24122. /**
  24123. * Gets or sets the fog density to use
  24124. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24125. */
  24126. _this.fogDensity = 0.1;
  24127. /**
  24128. * Gets or sets the fog start distance to use
  24129. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24130. */
  24131. _this.fogStart = 0;
  24132. /**
  24133. * Gets or sets the fog end distance to use
  24134. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24135. */
  24136. _this.fogEnd = 1000.0;
  24137. // Lights
  24138. _this._shadowsEnabled = true;
  24139. _this._lightsEnabled = true;
  24140. /** All of the active cameras added to this scene. */
  24141. _this.activeCameras = new Array();
  24142. // Textures
  24143. _this._texturesEnabled = true;
  24144. // Particles
  24145. /**
  24146. * Gets or sets a boolean indicating if particles are enabled on this scene
  24147. */
  24148. _this.particlesEnabled = true;
  24149. // Sprites
  24150. /**
  24151. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24152. */
  24153. _this.spritesEnabled = true;
  24154. // Skeletons
  24155. _this._skeletonsEnabled = true;
  24156. // Lens flares
  24157. /**
  24158. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24159. */
  24160. _this.lensFlaresEnabled = true;
  24161. // Collisions
  24162. /**
  24163. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24164. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24165. */
  24166. _this.collisionsEnabled = true;
  24167. /**
  24168. * Defines the gravity applied to this scene (used only for collisions)
  24169. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24170. */
  24171. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24172. // Postprocesses
  24173. /**
  24174. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24175. */
  24176. _this.postProcessesEnabled = true;
  24177. /**
  24178. * The list of postprocesses added to the scene
  24179. */
  24180. _this.postProcesses = new Array();
  24181. // Customs render targets
  24182. /**
  24183. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24184. */
  24185. _this.renderTargetsEnabled = true;
  24186. /**
  24187. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24188. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24189. */
  24190. _this.dumpNextRenderTargets = false;
  24191. /**
  24192. * The list of user defined render targets added to the scene
  24193. */
  24194. _this.customRenderTargets = new Array();
  24195. /**
  24196. * Gets the list of meshes imported to the scene through SceneLoader
  24197. */
  24198. _this.importedMeshesFiles = new Array();
  24199. // Probes
  24200. /**
  24201. * Gets or sets a boolean indicating if probes are enabled on this scene
  24202. */
  24203. _this.probesEnabled = true;
  24204. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24205. // Procedural textures
  24206. /**
  24207. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24208. */
  24209. _this.proceduralTexturesEnabled = true;
  24210. // Performance counters
  24211. _this._totalVertices = new BABYLON.PerfCounter();
  24212. /** @hidden */
  24213. _this._activeIndices = new BABYLON.PerfCounter();
  24214. /** @hidden */
  24215. _this._activeParticles = new BABYLON.PerfCounter();
  24216. /** @hidden */
  24217. _this._activeBones = new BABYLON.PerfCounter();
  24218. _this._animationTime = 0;
  24219. /**
  24220. * Gets or sets a general scale for animation speed
  24221. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24222. */
  24223. _this.animationTimeScale = 1;
  24224. _this._renderId = 0;
  24225. _this._frameId = 0;
  24226. _this._executeWhenReadyTimeoutId = -1;
  24227. _this._intermediateRendering = false;
  24228. _this._viewUpdateFlag = -1;
  24229. _this._projectionUpdateFlag = -1;
  24230. _this._alternateViewUpdateFlag = -1;
  24231. _this._alternateProjectionUpdateFlag = -1;
  24232. /** @hidden */
  24233. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24234. _this._activeRequests = new Array();
  24235. _this._pendingData = new Array();
  24236. _this._isDisposed = false;
  24237. /**
  24238. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24239. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24240. */
  24241. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24242. _this._activeMeshes = new BABYLON.SmartArray(256);
  24243. _this._processedMaterials = new BABYLON.SmartArray(256);
  24244. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24245. /** @hidden */
  24246. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24247. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24248. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24249. /** @hidden */
  24250. _this._activeAnimatables = new Array();
  24251. _this._transformMatrix = BABYLON.Matrix.Zero();
  24252. _this._useAlternateCameraConfiguration = false;
  24253. _this._alternateRendering = false;
  24254. /**
  24255. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24256. * This is useful if there are more lights that the maximum simulteanous authorized
  24257. */
  24258. _this.requireLightSorting = false;
  24259. /**
  24260. * @hidden
  24261. * Backing store of defined scene components.
  24262. */
  24263. _this._components = [];
  24264. /**
  24265. * @hidden
  24266. * Backing store of defined scene components.
  24267. */
  24268. _this._serializableComponents = [];
  24269. /**
  24270. * List of components to register on the next registration step.
  24271. */
  24272. _this._transientComponents = [];
  24273. /**
  24274. * @hidden
  24275. * Defines the actions happening before camera updates.
  24276. */
  24277. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24278. /**
  24279. * @hidden
  24280. * Defines the actions happening before clear the canvas.
  24281. */
  24282. _this._beforeClearStage = BABYLON.Stage.Create();
  24283. /**
  24284. * @hidden
  24285. * Defines the actions when collecting render targets for the frame.
  24286. */
  24287. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24288. /**
  24289. * @hidden
  24290. * Defines the actions happening for one camera in the frame.
  24291. */
  24292. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24293. /**
  24294. * @hidden
  24295. * Defines the actions happening during the per mesh ready checks.
  24296. */
  24297. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24298. /**
  24299. * @hidden
  24300. * Defines the actions happening before evaluate active mesh checks.
  24301. */
  24302. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24303. /**
  24304. * @hidden
  24305. * Defines the actions happening during the evaluate sub mesh checks.
  24306. */
  24307. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24308. /**
  24309. * @hidden
  24310. * Defines the actions happening during the active mesh stage.
  24311. */
  24312. _this._activeMeshStage = BABYLON.Stage.Create();
  24313. /**
  24314. * @hidden
  24315. * Defines the actions happening during the per camera render target step.
  24316. */
  24317. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24318. /**
  24319. * @hidden
  24320. * Defines the actions happening just before the active camera is drawing.
  24321. */
  24322. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24323. /**
  24324. * @hidden
  24325. * Defines the actions happening just before a rendering group is drawing.
  24326. */
  24327. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24328. /**
  24329. * @hidden
  24330. * Defines the actions happening just before a mesh is drawing.
  24331. */
  24332. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24333. /**
  24334. * @hidden
  24335. * Defines the actions happening just after a mesh has been drawn.
  24336. */
  24337. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24338. /**
  24339. * @hidden
  24340. * Defines the actions happening just after a rendering group has been drawn.
  24341. */
  24342. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24343. /**
  24344. * @hidden
  24345. * Defines the actions happening just after the active camera has been drawn.
  24346. */
  24347. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24348. /**
  24349. * @hidden
  24350. * Defines the actions happening just after rendering all cameras and computing intersections.
  24351. */
  24352. _this._afterRenderStage = BABYLON.Stage.Create();
  24353. /**
  24354. * @hidden
  24355. * Defines the actions happening when a pointer move event happens.
  24356. */
  24357. _this._pointerMoveStage = BABYLON.Stage.Create();
  24358. /**
  24359. * @hidden
  24360. * Defines the actions happening when a pointer down event happens.
  24361. */
  24362. _this._pointerDownStage = BABYLON.Stage.Create();
  24363. /**
  24364. * @hidden
  24365. * Defines the actions happening when a pointer up event happens.
  24366. */
  24367. _this._pointerUpStage = BABYLON.Stage.Create();
  24368. _this._defaultMeshCandidates = {
  24369. data: [],
  24370. length: 0
  24371. };
  24372. _this._defaultSubMeshCandidates = {
  24373. data: [],
  24374. length: 0
  24375. };
  24376. _this._activeMeshesFrozen = false;
  24377. /** @hidden */
  24378. _this._allowPostProcessClearColor = true;
  24379. /**
  24380. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  24381. */
  24382. _this.getDeterministicFrameTime = function () {
  24383. return 1000.0 / 60.0; // frame time in ms
  24384. };
  24385. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24386. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24387. _this.blockMaterialDirtyMechanism = false;
  24388. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24389. _this._engine.scenes.push(_this);
  24390. _this._uid = null;
  24391. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24392. if (BABYLON.PostProcessManager) {
  24393. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24394. }
  24395. if (BABYLON.Tools.IsWindowObjectExist()) {
  24396. _this.attachControl();
  24397. }
  24398. //collision coordinator initialization. For now legacy per default.
  24399. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24400. // Uniform Buffer
  24401. _this._createUbo();
  24402. // Default Image processing definition
  24403. if (BABYLON.ImageProcessingConfiguration) {
  24404. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24405. }
  24406. _this.setDefaultCandidateProviders();
  24407. return _this;
  24408. }
  24409. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24410. /**
  24411. * Texture used in all pbr material as the reflection texture.
  24412. * As in the majority of the scene they are the same (exception for multi room and so on),
  24413. * this is easier to reference from here than from all the materials.
  24414. */
  24415. get: function () {
  24416. return this._environmentTexture;
  24417. },
  24418. /**
  24419. * Texture used in all pbr material as the reflection texture.
  24420. * As in the majority of the scene they are the same (exception for multi room and so on),
  24421. * this is easier to set here than in all the materials.
  24422. */
  24423. set: function (value) {
  24424. if (this._environmentTexture === value) {
  24425. return;
  24426. }
  24427. this._environmentTexture = value;
  24428. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24429. },
  24430. enumerable: true,
  24431. configurable: true
  24432. });
  24433. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24434. /**
  24435. * Default image processing configuration used either in the rendering
  24436. * Forward main pass or through the imageProcessingPostProcess if present.
  24437. * As in the majority of the scene they are the same (exception for multi camera),
  24438. * this is easier to reference from here than from all the materials and post process.
  24439. *
  24440. * No setter as we it is a shared configuration, you can set the values instead.
  24441. */
  24442. get: function () {
  24443. return this._imageProcessingConfiguration;
  24444. },
  24445. enumerable: true,
  24446. configurable: true
  24447. });
  24448. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24449. get: function () {
  24450. return this._forceWireframe;
  24451. },
  24452. /**
  24453. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24454. */
  24455. set: function (value) {
  24456. if (this._forceWireframe === value) {
  24457. return;
  24458. }
  24459. this._forceWireframe = value;
  24460. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24461. },
  24462. enumerable: true,
  24463. configurable: true
  24464. });
  24465. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24466. get: function () {
  24467. return this._forcePointsCloud;
  24468. },
  24469. /**
  24470. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24471. */
  24472. set: function (value) {
  24473. if (this._forcePointsCloud === value) {
  24474. return;
  24475. }
  24476. this._forcePointsCloud = value;
  24477. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24478. },
  24479. enumerable: true,
  24480. configurable: true
  24481. });
  24482. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24483. /**
  24484. * Gets or sets the animation properties override
  24485. */
  24486. get: function () {
  24487. return this._animationPropertiesOverride;
  24488. },
  24489. set: function (value) {
  24490. this._animationPropertiesOverride = value;
  24491. },
  24492. enumerable: true,
  24493. configurable: true
  24494. });
  24495. Object.defineProperty(Scene.prototype, "onDispose", {
  24496. /** Sets a function to be executed when this scene is disposed. */
  24497. set: function (callback) {
  24498. if (this._onDisposeObserver) {
  24499. this.onDisposeObservable.remove(this._onDisposeObserver);
  24500. }
  24501. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24502. },
  24503. enumerable: true,
  24504. configurable: true
  24505. });
  24506. Object.defineProperty(Scene.prototype, "beforeRender", {
  24507. /** Sets a function to be executed before rendering this scene */
  24508. set: function (callback) {
  24509. if (this._onBeforeRenderObserver) {
  24510. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24511. }
  24512. if (callback) {
  24513. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24514. }
  24515. },
  24516. enumerable: true,
  24517. configurable: true
  24518. });
  24519. Object.defineProperty(Scene.prototype, "afterRender", {
  24520. /** Sets a function to be executed after rendering this scene */
  24521. set: function (callback) {
  24522. if (this._onAfterRenderObserver) {
  24523. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24524. }
  24525. if (callback) {
  24526. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24527. }
  24528. },
  24529. enumerable: true,
  24530. configurable: true
  24531. });
  24532. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24533. /** Sets a function to be executed before rendering a camera*/
  24534. set: function (callback) {
  24535. if (this._onBeforeCameraRenderObserver) {
  24536. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24537. }
  24538. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24539. },
  24540. enumerable: true,
  24541. configurable: true
  24542. });
  24543. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24544. /** Sets a function to be executed after rendering a camera*/
  24545. set: function (callback) {
  24546. if (this._onAfterCameraRenderObserver) {
  24547. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24548. }
  24549. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24550. },
  24551. enumerable: true,
  24552. configurable: true
  24553. });
  24554. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24555. /**
  24556. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24557. */
  24558. get: function () {
  24559. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24560. },
  24561. enumerable: true,
  24562. configurable: true
  24563. });
  24564. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24565. get: function () {
  24566. return this._useRightHandedSystem;
  24567. },
  24568. /**
  24569. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24570. */
  24571. set: function (value) {
  24572. if (this._useRightHandedSystem === value) {
  24573. return;
  24574. }
  24575. this._useRightHandedSystem = value;
  24576. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24577. },
  24578. enumerable: true,
  24579. configurable: true
  24580. });
  24581. /**
  24582. * Sets the step Id used by deterministic lock step
  24583. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24584. * @param newStepId defines the step Id
  24585. */
  24586. Scene.prototype.setStepId = function (newStepId) {
  24587. this._currentStepId = newStepId;
  24588. };
  24589. ;
  24590. /**
  24591. * Gets the step Id used by deterministic lock step
  24592. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24593. * @returns the step Id
  24594. */
  24595. Scene.prototype.getStepId = function () {
  24596. return this._currentStepId;
  24597. };
  24598. ;
  24599. /**
  24600. * Gets the internal step used by deterministic lock step
  24601. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24602. * @returns the internal step
  24603. */
  24604. Scene.prototype.getInternalStep = function () {
  24605. return this._currentInternalStep;
  24606. };
  24607. ;
  24608. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24609. get: function () {
  24610. return this._fogEnabled;
  24611. },
  24612. /**
  24613. * Gets or sets a boolean indicating if fog is enabled on this scene
  24614. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24615. */
  24616. set: function (value) {
  24617. if (this._fogEnabled === value) {
  24618. return;
  24619. }
  24620. this._fogEnabled = value;
  24621. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24622. },
  24623. enumerable: true,
  24624. configurable: true
  24625. });
  24626. Object.defineProperty(Scene.prototype, "fogMode", {
  24627. get: function () {
  24628. return this._fogMode;
  24629. },
  24630. /**
  24631. * Gets or sets the fog mode to use
  24632. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24633. */
  24634. set: function (value) {
  24635. if (this._fogMode === value) {
  24636. return;
  24637. }
  24638. this._fogMode = value;
  24639. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24640. },
  24641. enumerable: true,
  24642. configurable: true
  24643. });
  24644. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24645. get: function () {
  24646. return this._shadowsEnabled;
  24647. },
  24648. /**
  24649. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24650. */
  24651. set: function (value) {
  24652. if (this._shadowsEnabled === value) {
  24653. return;
  24654. }
  24655. this._shadowsEnabled = value;
  24656. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24657. },
  24658. enumerable: true,
  24659. configurable: true
  24660. });
  24661. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24662. get: function () {
  24663. return this._lightsEnabled;
  24664. },
  24665. /**
  24666. * Gets or sets a boolean indicating if lights are enabled on this scene
  24667. */
  24668. set: function (value) {
  24669. if (this._lightsEnabled === value) {
  24670. return;
  24671. }
  24672. this._lightsEnabled = value;
  24673. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24674. },
  24675. enumerable: true,
  24676. configurable: true
  24677. });
  24678. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24679. /** The default material used on meshes when no material is affected */
  24680. get: function () {
  24681. if (!this._defaultMaterial) {
  24682. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24683. }
  24684. return this._defaultMaterial;
  24685. },
  24686. /** The default material used on meshes when no material is affected */
  24687. set: function (value) {
  24688. this._defaultMaterial = value;
  24689. },
  24690. enumerable: true,
  24691. configurable: true
  24692. });
  24693. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24694. get: function () {
  24695. return this._texturesEnabled;
  24696. },
  24697. /**
  24698. * Gets or sets a boolean indicating if textures are enabled on this scene
  24699. */
  24700. set: function (value) {
  24701. if (this._texturesEnabled === value) {
  24702. return;
  24703. }
  24704. this._texturesEnabled = value;
  24705. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24706. },
  24707. enumerable: true,
  24708. configurable: true
  24709. });
  24710. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24711. get: function () {
  24712. return this._skeletonsEnabled;
  24713. },
  24714. /**
  24715. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24716. */
  24717. set: function (value) {
  24718. if (this._skeletonsEnabled === value) {
  24719. return;
  24720. }
  24721. this._skeletonsEnabled = value;
  24722. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24723. },
  24724. enumerable: true,
  24725. configurable: true
  24726. });
  24727. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24728. /** @hidden */
  24729. get: function () {
  24730. return this._alternateRendering;
  24731. },
  24732. enumerable: true,
  24733. configurable: true
  24734. });
  24735. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24736. /**
  24737. * Gets the list of frustum planes (built from the active camera)
  24738. */
  24739. get: function () {
  24740. return this._frustumPlanes;
  24741. },
  24742. enumerable: true,
  24743. configurable: true
  24744. });
  24745. /**
  24746. * Registers the transient components if needed.
  24747. */
  24748. Scene.prototype._registerTransientComponents = function () {
  24749. // Register components that have been associated lately to the scene.
  24750. if (this._transientComponents.length > 0) {
  24751. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24752. var component = _a[_i];
  24753. component.register();
  24754. }
  24755. this._transientComponents = [];
  24756. }
  24757. };
  24758. /**
  24759. * @hidden
  24760. * Add a component to the scene.
  24761. * Note that the ccomponent could be registered on th next frame if this is called after
  24762. * the register component stage.
  24763. * @param component Defines the component to add to the scene
  24764. */
  24765. Scene.prototype._addComponent = function (component) {
  24766. this._components.push(component);
  24767. this._transientComponents.push(component);
  24768. var serializableComponent = component;
  24769. if (serializableComponent.addFromContainer) {
  24770. this._serializableComponents.push(serializableComponent);
  24771. }
  24772. };
  24773. /**
  24774. * @hidden
  24775. * Gets a component from the scene.
  24776. * @param name defines the name of the component to retrieve
  24777. * @returns the component or null if not present
  24778. */
  24779. Scene.prototype._getComponent = function (name) {
  24780. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24781. var component = _a[_i];
  24782. if (component.name === name) {
  24783. return component;
  24784. }
  24785. }
  24786. return null;
  24787. };
  24788. /**
  24789. * @hidden
  24790. */
  24791. Scene.prototype._getDefaultMeshCandidates = function () {
  24792. this._defaultMeshCandidates.data = this.meshes;
  24793. this._defaultMeshCandidates.length = this.meshes.length;
  24794. return this._defaultMeshCandidates;
  24795. };
  24796. /**
  24797. * @hidden
  24798. */
  24799. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  24800. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  24801. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  24802. return this._defaultSubMeshCandidates;
  24803. };
  24804. /**
  24805. * Sets the default candidate providers for the scene.
  24806. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  24807. * and getCollidingSubMeshCandidates to their default function
  24808. */
  24809. Scene.prototype.setDefaultCandidateProviders = function () {
  24810. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  24811. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24812. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24813. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24814. };
  24815. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24816. /**
  24817. * Gets a boolean indicating if collisions are processed on a web worker
  24818. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24819. */
  24820. get: function () {
  24821. return this._workerCollisions;
  24822. },
  24823. set: function (enabled) {
  24824. if (!BABYLON.CollisionCoordinatorLegacy) {
  24825. return;
  24826. }
  24827. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24828. this._workerCollisions = enabled;
  24829. if (this.collisionCoordinator) {
  24830. this.collisionCoordinator.destroy();
  24831. }
  24832. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24833. this.collisionCoordinator.init(this);
  24834. },
  24835. enumerable: true,
  24836. configurable: true
  24837. });
  24838. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24839. /**
  24840. * Gets the mesh that is currently under the pointer
  24841. */
  24842. get: function () {
  24843. return this._pointerOverMesh;
  24844. },
  24845. enumerable: true,
  24846. configurable: true
  24847. });
  24848. Object.defineProperty(Scene.prototype, "pointerX", {
  24849. /**
  24850. * Gets the current on-screen X position of the pointer
  24851. */
  24852. get: function () {
  24853. return this._pointerX;
  24854. },
  24855. enumerable: true,
  24856. configurable: true
  24857. });
  24858. Object.defineProperty(Scene.prototype, "pointerY", {
  24859. /**
  24860. * Gets the current on-screen Y position of the pointer
  24861. */
  24862. get: function () {
  24863. return this._pointerY;
  24864. },
  24865. enumerable: true,
  24866. configurable: true
  24867. });
  24868. /**
  24869. * Gets the cached material (ie. the latest rendered one)
  24870. * @returns the cached material
  24871. */
  24872. Scene.prototype.getCachedMaterial = function () {
  24873. return this._cachedMaterial;
  24874. };
  24875. /**
  24876. * Gets the cached effect (ie. the latest rendered one)
  24877. * @returns the cached effect
  24878. */
  24879. Scene.prototype.getCachedEffect = function () {
  24880. return this._cachedEffect;
  24881. };
  24882. /**
  24883. * Gets the cached visibility state (ie. the latest rendered one)
  24884. * @returns the cached visibility state
  24885. */
  24886. Scene.prototype.getCachedVisibility = function () {
  24887. return this._cachedVisibility;
  24888. };
  24889. /**
  24890. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24891. * @param material defines the current material
  24892. * @param effect defines the current effect
  24893. * @param visibility defines the current visibility state
  24894. * @returns true if one parameter is not cached
  24895. */
  24896. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24897. if (visibility === void 0) { visibility = 1; }
  24898. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24899. };
  24900. /**
  24901. * Gets the engine associated with the scene
  24902. * @returns an Engine
  24903. */
  24904. Scene.prototype.getEngine = function () {
  24905. return this._engine;
  24906. };
  24907. /**
  24908. * Gets the total number of vertices rendered per frame
  24909. * @returns the total number of vertices rendered per frame
  24910. */
  24911. Scene.prototype.getTotalVertices = function () {
  24912. return this._totalVertices.current;
  24913. };
  24914. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24915. /**
  24916. * Gets the performance counter for total vertices
  24917. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24918. */
  24919. get: function () {
  24920. return this._totalVertices;
  24921. },
  24922. enumerable: true,
  24923. configurable: true
  24924. });
  24925. /**
  24926. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24927. * @returns the total number of active indices rendered per frame
  24928. */
  24929. Scene.prototype.getActiveIndices = function () {
  24930. return this._activeIndices.current;
  24931. };
  24932. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24933. /**
  24934. * Gets the performance counter for active indices
  24935. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24936. */
  24937. get: function () {
  24938. return this._activeIndices;
  24939. },
  24940. enumerable: true,
  24941. configurable: true
  24942. });
  24943. /**
  24944. * Gets the total number of active particles rendered per frame
  24945. * @returns the total number of active particles rendered per frame
  24946. */
  24947. Scene.prototype.getActiveParticles = function () {
  24948. return this._activeParticles.current;
  24949. };
  24950. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24951. /**
  24952. * Gets the performance counter for active particles
  24953. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24954. */
  24955. get: function () {
  24956. return this._activeParticles;
  24957. },
  24958. enumerable: true,
  24959. configurable: true
  24960. });
  24961. /**
  24962. * Gets the total number of active bones rendered per frame
  24963. * @returns the total number of active bones rendered per frame
  24964. */
  24965. Scene.prototype.getActiveBones = function () {
  24966. return this._activeBones.current;
  24967. };
  24968. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24969. /**
  24970. * Gets the performance counter for active bones
  24971. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24972. */
  24973. get: function () {
  24974. return this._activeBones;
  24975. },
  24976. enumerable: true,
  24977. configurable: true
  24978. });
  24979. /** @hidden */
  24980. Scene.prototype.getInterFramePerfCounter = function () {
  24981. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24982. return 0;
  24983. };
  24984. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24985. /** @hidden */
  24986. get: function () {
  24987. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24988. return null;
  24989. },
  24990. enumerable: true,
  24991. configurable: true
  24992. });
  24993. /** @hidden */
  24994. Scene.prototype.getLastFrameDuration = function () {
  24995. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24996. return 0;
  24997. };
  24998. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24999. /** @hidden */
  25000. get: function () {
  25001. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25002. return null;
  25003. },
  25004. enumerable: true,
  25005. configurable: true
  25006. });
  25007. /** @hidden */
  25008. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25009. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25010. return 0;
  25011. };
  25012. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25013. /** @hidden */
  25014. get: function () {
  25015. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25016. return null;
  25017. },
  25018. enumerable: true,
  25019. configurable: true
  25020. });
  25021. /**
  25022. * Gets the array of active meshes
  25023. * @returns an array of AbstractMesh
  25024. */
  25025. Scene.prototype.getActiveMeshes = function () {
  25026. return this._activeMeshes;
  25027. };
  25028. /** @hidden */
  25029. Scene.prototype.getRenderTargetsDuration = function () {
  25030. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25031. return 0;
  25032. };
  25033. /** @hidden */
  25034. Scene.prototype.getRenderDuration = function () {
  25035. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25036. return 0;
  25037. };
  25038. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25039. /** @hidden */
  25040. get: function () {
  25041. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25042. return null;
  25043. },
  25044. enumerable: true,
  25045. configurable: true
  25046. });
  25047. /** @hidden */
  25048. Scene.prototype.getParticlesDuration = function () {
  25049. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25050. return 0;
  25051. };
  25052. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25053. /** @hidden */
  25054. get: function () {
  25055. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25056. return null;
  25057. },
  25058. enumerable: true,
  25059. configurable: true
  25060. });
  25061. /** @hidden */
  25062. Scene.prototype.getSpritesDuration = function () {
  25063. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25064. return 0;
  25065. };
  25066. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25067. /** @hidden */
  25068. get: function () {
  25069. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25070. return null;
  25071. },
  25072. enumerable: true,
  25073. configurable: true
  25074. });
  25075. /**
  25076. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25077. * @returns a number
  25078. */
  25079. Scene.prototype.getAnimationRatio = function () {
  25080. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25081. };
  25082. /**
  25083. * Gets an unique Id for the current render phase
  25084. * @returns a number
  25085. */
  25086. Scene.prototype.getRenderId = function () {
  25087. return this._renderId;
  25088. };
  25089. /**
  25090. * Gets an unique Id for the current frame
  25091. * @returns a number
  25092. */
  25093. Scene.prototype.getFrameId = function () {
  25094. return this._frameId;
  25095. };
  25096. /** Call this function if you want to manually increment the render Id*/
  25097. Scene.prototype.incrementRenderId = function () {
  25098. this._renderId++;
  25099. };
  25100. Scene.prototype._updatePointerPosition = function (evt) {
  25101. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25102. if (!canvasRect) {
  25103. return;
  25104. }
  25105. this._pointerX = evt.clientX - canvasRect.left;
  25106. this._pointerY = evt.clientY - canvasRect.top;
  25107. this._unTranslatedPointerX = this._pointerX;
  25108. this._unTranslatedPointerY = this._pointerY;
  25109. };
  25110. Scene.prototype._createUbo = function () {
  25111. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25112. this._sceneUbo.addUniform("viewProjection", 16);
  25113. this._sceneUbo.addUniform("view", 16);
  25114. };
  25115. Scene.prototype._createAlternateUbo = function () {
  25116. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25117. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25118. this._alternateSceneUbo.addUniform("view", 16);
  25119. };
  25120. // Pointers handling
  25121. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25122. if (pointerInfo.pickInfo) {
  25123. if (!pointerInfo.pickInfo.ray) {
  25124. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25125. }
  25126. }
  25127. };
  25128. /**
  25129. * Use this method to simulate a pointer move on a mesh
  25130. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25131. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25132. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25133. * @returns the current scene
  25134. */
  25135. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25136. var evt = new PointerEvent("pointermove", pointerEventInit);
  25137. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25138. return this;
  25139. }
  25140. return this._processPointerMove(pickResult, evt);
  25141. };
  25142. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25143. var canvas = this._engine.getRenderingCanvas();
  25144. if (!canvas) {
  25145. return this;
  25146. }
  25147. // Restore pointer
  25148. canvas.style.cursor = this.defaultCursor;
  25149. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25150. if (isMeshPicked) {
  25151. this.setPointerOverMesh(pickResult.pickedMesh);
  25152. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25153. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25154. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25155. }
  25156. else {
  25157. canvas.style.cursor = this.hoverCursor;
  25158. }
  25159. }
  25160. }
  25161. else {
  25162. this.setPointerOverMesh(null);
  25163. }
  25164. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25165. var step = _a[_i];
  25166. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25167. }
  25168. if (pickResult) {
  25169. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25170. if (this.onPointerMove) {
  25171. this.onPointerMove(evt, pickResult, type);
  25172. }
  25173. if (this.onPointerObservable.hasObservers()) {
  25174. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25175. this._setRayOnPointerInfo(pi);
  25176. this.onPointerObservable.notifyObservers(pi, type);
  25177. }
  25178. }
  25179. return this;
  25180. };
  25181. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25182. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25183. if (pickResult) {
  25184. pi.ray = pickResult.ray;
  25185. }
  25186. this.onPrePointerObservable.notifyObservers(pi, type);
  25187. if (pi.skipOnPointerObservable) {
  25188. return true;
  25189. }
  25190. else {
  25191. return false;
  25192. }
  25193. };
  25194. /**
  25195. * Use this method to simulate a pointer down on a mesh
  25196. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25197. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25198. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25199. * @returns the current scene
  25200. */
  25201. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25202. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25203. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25204. return this;
  25205. }
  25206. return this._processPointerDown(pickResult, evt);
  25207. };
  25208. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25209. var _this = this;
  25210. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25211. this._pickedDownMesh = pickResult.pickedMesh;
  25212. var actionManager = pickResult.pickedMesh.actionManager;
  25213. if (actionManager) {
  25214. if (actionManager.hasPickTriggers) {
  25215. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25216. switch (evt.button) {
  25217. case 0:
  25218. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25219. break;
  25220. case 1:
  25221. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25222. break;
  25223. case 2:
  25224. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25225. break;
  25226. }
  25227. }
  25228. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25229. window.setTimeout(function () {
  25230. 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);
  25231. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25232. if (_this._totalPointersPressed !== 0 &&
  25233. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25234. !_this._isPointerSwiping()) {
  25235. _this._startingPointerTime = 0;
  25236. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25237. }
  25238. }
  25239. }, Scene.LongPressDelay);
  25240. }
  25241. }
  25242. }
  25243. else {
  25244. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25245. var step = _a[_i];
  25246. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25247. }
  25248. }
  25249. if (pickResult) {
  25250. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25251. if (this.onPointerDown) {
  25252. this.onPointerDown(evt, pickResult, type);
  25253. }
  25254. if (this.onPointerObservable.hasObservers()) {
  25255. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25256. this._setRayOnPointerInfo(pi);
  25257. this.onPointerObservable.notifyObservers(pi, type);
  25258. }
  25259. }
  25260. return this;
  25261. };
  25262. /**
  25263. * Use this method to simulate a pointer up on a mesh
  25264. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25265. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25266. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25267. * @returns the current scene
  25268. */
  25269. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25270. var evt = new PointerEvent("pointerup", pointerEventInit);
  25271. var clickInfo = new ClickInfo();
  25272. clickInfo.singleClick = true;
  25273. clickInfo.ignore = true;
  25274. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25275. return this;
  25276. }
  25277. return this._processPointerUp(pickResult, evt, clickInfo);
  25278. };
  25279. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25280. if (pickResult && pickResult && pickResult.pickedMesh) {
  25281. this._pickedUpMesh = pickResult.pickedMesh;
  25282. if (this._pickedDownMesh === this._pickedUpMesh) {
  25283. if (this.onPointerPick) {
  25284. this.onPointerPick(evt, pickResult);
  25285. }
  25286. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25287. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25288. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25289. this._setRayOnPointerInfo(pi);
  25290. this.onPointerObservable.notifyObservers(pi, type_1);
  25291. }
  25292. }
  25293. if (pickResult.pickedMesh.actionManager) {
  25294. if (clickInfo.ignore) {
  25295. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25296. }
  25297. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25298. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25299. }
  25300. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25301. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25302. }
  25303. }
  25304. }
  25305. else {
  25306. if (!clickInfo.ignore) {
  25307. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25308. var step = _a[_i];
  25309. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25310. }
  25311. }
  25312. }
  25313. if (this._pickedDownMesh &&
  25314. this._pickedDownMesh.actionManager &&
  25315. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25316. this._pickedDownMesh !== this._pickedUpMesh) {
  25317. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25318. }
  25319. var type = BABYLON.PointerEventTypes.POINTERUP;
  25320. if (this.onPointerObservable.hasObservers()) {
  25321. if (!clickInfo.ignore) {
  25322. if (!clickInfo.hasSwiped) {
  25323. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25324. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25325. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25326. this._setRayOnPointerInfo(pi);
  25327. this.onPointerObservable.notifyObservers(pi, type_2);
  25328. }
  25329. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25330. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25331. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25332. this._setRayOnPointerInfo(pi);
  25333. this.onPointerObservable.notifyObservers(pi, type_3);
  25334. }
  25335. }
  25336. }
  25337. else {
  25338. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25339. this._setRayOnPointerInfo(pi);
  25340. this.onPointerObservable.notifyObservers(pi, type);
  25341. }
  25342. }
  25343. if (this.onPointerUp) {
  25344. this.onPointerUp(evt, pickResult, type);
  25345. }
  25346. return this;
  25347. };
  25348. /**
  25349. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25350. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25351. * @returns true if the pointer was captured
  25352. */
  25353. Scene.prototype.isPointerCaptured = function (pointerId) {
  25354. if (pointerId === void 0) { pointerId = 0; }
  25355. return this._pointerCaptures[pointerId];
  25356. };
  25357. /** @hidden */
  25358. Scene.prototype._isPointerSwiping = function () {
  25359. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25360. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25361. };
  25362. /**
  25363. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25364. * @param attachUp defines if you want to attach events to pointerup
  25365. * @param attachDown defines if you want to attach events to pointerdown
  25366. * @param attachMove defines if you want to attach events to pointermove
  25367. */
  25368. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25369. var _this = this;
  25370. if (attachUp === void 0) { attachUp = true; }
  25371. if (attachDown === void 0) { attachDown = true; }
  25372. if (attachMove === void 0) { attachMove = true; }
  25373. this._initActionManager = function (act, clickInfo) {
  25374. if (!_this._meshPickProceed) {
  25375. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25376. _this._currentPickResult = pickResult;
  25377. if (pickResult) {
  25378. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25379. }
  25380. _this._meshPickProceed = true;
  25381. }
  25382. return act;
  25383. };
  25384. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25385. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25386. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25387. btn !== _this._previousButtonPressed) {
  25388. _this._doubleClickOccured = false;
  25389. clickInfo.singleClick = true;
  25390. clickInfo.ignore = false;
  25391. cb(clickInfo, _this._currentPickResult);
  25392. }
  25393. };
  25394. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25395. var clickInfo = new ClickInfo();
  25396. _this._currentPickResult = null;
  25397. var act = null;
  25398. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25399. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25400. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25401. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25402. act = _this._initActionManager(act, clickInfo);
  25403. if (act)
  25404. checkPicking = act.hasPickTriggers;
  25405. }
  25406. if (checkPicking) {
  25407. var btn = evt.button;
  25408. clickInfo.hasSwiped = _this._isPointerSwiping();
  25409. if (!clickInfo.hasSwiped) {
  25410. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25411. if (!checkSingleClickImmediately) {
  25412. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25413. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25414. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25415. act = _this._initActionManager(act, clickInfo);
  25416. if (act)
  25417. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25418. }
  25419. }
  25420. if (checkSingleClickImmediately) {
  25421. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25422. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25423. btn !== _this._previousButtonPressed) {
  25424. clickInfo.singleClick = true;
  25425. cb(clickInfo, _this._currentPickResult);
  25426. }
  25427. }
  25428. // at least one double click is required to be check and exclusive double click is enabled
  25429. else {
  25430. // wait that no double click has been raised during the double click delay
  25431. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25432. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25433. }
  25434. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25435. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25436. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25437. act = _this._initActionManager(act, clickInfo);
  25438. if (act)
  25439. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25440. }
  25441. if (checkDoubleClick) {
  25442. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25443. if (btn === _this._previousButtonPressed &&
  25444. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25445. !_this._doubleClickOccured) {
  25446. // pointer has not moved for 2 clicks, it's a double click
  25447. if (!clickInfo.hasSwiped &&
  25448. !_this._isPointerSwiping()) {
  25449. _this._previousStartingPointerTime = 0;
  25450. _this._doubleClickOccured = true;
  25451. clickInfo.doubleClick = true;
  25452. clickInfo.ignore = false;
  25453. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25454. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25455. }
  25456. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25457. cb(clickInfo, _this._currentPickResult);
  25458. }
  25459. // if the two successive clicks are too far, it's just two simple clicks
  25460. else {
  25461. _this._doubleClickOccured = false;
  25462. _this._previousStartingPointerTime = _this._startingPointerTime;
  25463. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25464. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25465. _this._previousButtonPressed = btn;
  25466. if (Scene.ExclusiveDoubleClickMode) {
  25467. if (_this._previousDelayedSimpleClickTimeout) {
  25468. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25469. }
  25470. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25471. cb(clickInfo, _this._previousPickResult);
  25472. }
  25473. else {
  25474. cb(clickInfo, _this._currentPickResult);
  25475. }
  25476. }
  25477. }
  25478. // just the first click of the double has been raised
  25479. else {
  25480. _this._doubleClickOccured = false;
  25481. _this._previousStartingPointerTime = _this._startingPointerTime;
  25482. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25483. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25484. _this._previousButtonPressed = btn;
  25485. }
  25486. }
  25487. }
  25488. }
  25489. clickInfo.ignore = true;
  25490. cb(clickInfo, _this._currentPickResult);
  25491. };
  25492. this._onPointerMove = function (evt) {
  25493. _this._updatePointerPosition(evt);
  25494. // PreObservable support
  25495. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25496. return;
  25497. }
  25498. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25499. return;
  25500. }
  25501. if (!_this.pointerMovePredicate) {
  25502. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25503. }
  25504. // Meshes
  25505. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25506. _this._processPointerMove(pickResult, evt);
  25507. };
  25508. this._onPointerDown = function (evt) {
  25509. _this._totalPointersPressed++;
  25510. _this._pickedDownMesh = null;
  25511. _this._meshPickProceed = false;
  25512. _this._updatePointerPosition(evt);
  25513. if (_this.preventDefaultOnPointerDown && canvas) {
  25514. evt.preventDefault();
  25515. canvas.focus();
  25516. }
  25517. // PreObservable support
  25518. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25519. return;
  25520. }
  25521. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25522. return;
  25523. }
  25524. _this._pointerCaptures[evt.pointerId] = true;
  25525. _this._startingPointerPosition.x = _this._pointerX;
  25526. _this._startingPointerPosition.y = _this._pointerY;
  25527. _this._startingPointerTime = Date.now();
  25528. if (!_this.pointerDownPredicate) {
  25529. _this.pointerDownPredicate = function (mesh) {
  25530. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25531. };
  25532. }
  25533. // Meshes
  25534. _this._pickedDownMesh = null;
  25535. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25536. _this._processPointerDown(pickResult, evt);
  25537. };
  25538. this._onPointerUp = function (evt) {
  25539. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25540. return; // So we need to test it the pointer down was pressed before.
  25541. }
  25542. _this._totalPointersPressed--;
  25543. _this._pickedUpMesh = null;
  25544. _this._meshPickProceed = false;
  25545. _this._updatePointerPosition(evt);
  25546. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25547. // PreObservable support
  25548. if (_this.onPrePointerObservable.hasObservers()) {
  25549. if (!clickInfo.ignore) {
  25550. if (!clickInfo.hasSwiped) {
  25551. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25552. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25553. return;
  25554. }
  25555. }
  25556. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25557. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25558. return;
  25559. }
  25560. }
  25561. }
  25562. }
  25563. else {
  25564. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25565. return;
  25566. }
  25567. }
  25568. }
  25569. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25570. return;
  25571. }
  25572. _this._pointerCaptures[evt.pointerId] = false;
  25573. if (!_this.pointerUpPredicate) {
  25574. _this.pointerUpPredicate = function (mesh) {
  25575. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25576. };
  25577. }
  25578. // Meshes
  25579. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25580. _this._initActionManager(null, clickInfo);
  25581. }
  25582. if (!pickResult) {
  25583. pickResult = _this._currentPickResult;
  25584. }
  25585. _this._processPointerUp(pickResult, evt, clickInfo);
  25586. _this._previousPickResult = _this._currentPickResult;
  25587. });
  25588. };
  25589. this._onKeyDown = function (evt) {
  25590. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25591. if (_this.onPreKeyboardObservable.hasObservers()) {
  25592. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25593. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25594. if (pi.skipOnPointerObservable) {
  25595. return;
  25596. }
  25597. }
  25598. if (_this.onKeyboardObservable.hasObservers()) {
  25599. var pi = new BABYLON.KeyboardInfo(type, evt);
  25600. _this.onKeyboardObservable.notifyObservers(pi, type);
  25601. }
  25602. if (_this.actionManager) {
  25603. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25604. }
  25605. };
  25606. this._onKeyUp = function (evt) {
  25607. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25608. if (_this.onPreKeyboardObservable.hasObservers()) {
  25609. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25610. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25611. if (pi.skipOnPointerObservable) {
  25612. return;
  25613. }
  25614. }
  25615. if (_this.onKeyboardObservable.hasObservers()) {
  25616. var pi = new BABYLON.KeyboardInfo(type, evt);
  25617. _this.onKeyboardObservable.notifyObservers(pi, type);
  25618. }
  25619. if (_this.actionManager) {
  25620. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25621. }
  25622. };
  25623. var engine = this.getEngine();
  25624. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25625. if (!canvas) {
  25626. return;
  25627. }
  25628. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25629. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25630. });
  25631. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25632. if (!canvas) {
  25633. return;
  25634. }
  25635. canvas.removeEventListener("keydown", _this._onKeyDown);
  25636. canvas.removeEventListener("keyup", _this._onKeyUp);
  25637. });
  25638. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25639. var canvas = this._engine.getRenderingCanvas();
  25640. if (!canvas) {
  25641. return;
  25642. }
  25643. if (attachMove) {
  25644. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25645. // Wheel
  25646. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25647. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25648. }
  25649. if (attachDown) {
  25650. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25651. }
  25652. if (attachUp) {
  25653. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25654. }
  25655. canvas.tabIndex = 1;
  25656. };
  25657. /** Detaches all event handlers*/
  25658. Scene.prototype.detachControl = function () {
  25659. var engine = this.getEngine();
  25660. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25661. var canvas = engine.getRenderingCanvas();
  25662. if (!canvas) {
  25663. return;
  25664. }
  25665. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25666. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25667. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25668. if (this._onCanvasBlurObserver) {
  25669. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25670. }
  25671. if (this._onCanvasFocusObserver) {
  25672. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25673. }
  25674. // Wheel
  25675. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25676. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25677. // Keyboard
  25678. canvas.removeEventListener("keydown", this._onKeyDown);
  25679. canvas.removeEventListener("keyup", this._onKeyUp);
  25680. // Observables
  25681. this.onKeyboardObservable.clear();
  25682. this.onPreKeyboardObservable.clear();
  25683. this.onPointerObservable.clear();
  25684. this.onPrePointerObservable.clear();
  25685. };
  25686. /**
  25687. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25688. * Delay loaded resources are not taking in account
  25689. * @return true if all required resources are ready
  25690. */
  25691. Scene.prototype.isReady = function () {
  25692. if (this._isDisposed) {
  25693. return false;
  25694. }
  25695. if (this._pendingData.length > 0) {
  25696. return false;
  25697. }
  25698. var index;
  25699. var engine = this.getEngine();
  25700. // Geometries
  25701. for (index = 0; index < this.geometries.length; index++) {
  25702. var geometry = this.geometries[index];
  25703. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25704. return false;
  25705. }
  25706. }
  25707. // Meshes
  25708. for (index = 0; index < this.meshes.length; index++) {
  25709. var mesh = this.meshes[index];
  25710. if (!mesh.isEnabled()) {
  25711. continue;
  25712. }
  25713. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25714. continue;
  25715. }
  25716. if (!mesh.isReady(true)) {
  25717. return false;
  25718. }
  25719. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25720. // Is Ready For Mesh
  25721. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25722. var step = _a[_i];
  25723. if (!step.action(mesh, hardwareInstancedRendering)) {
  25724. return false;
  25725. }
  25726. }
  25727. }
  25728. // Post-processes
  25729. if (this.activeCameras && this.activeCameras.length > 0) {
  25730. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25731. var camera = _c[_b];
  25732. if (!camera.isReady(true)) {
  25733. return false;
  25734. }
  25735. }
  25736. }
  25737. else if (this.activeCamera) {
  25738. if (!this.activeCamera.isReady(true)) {
  25739. return false;
  25740. }
  25741. }
  25742. // Particles
  25743. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25744. var particleSystem = _e[_d];
  25745. if (!particleSystem.isReady()) {
  25746. return false;
  25747. }
  25748. }
  25749. return true;
  25750. };
  25751. /** Resets all cached information relative to material (including effect and visibility) */
  25752. Scene.prototype.resetCachedMaterial = function () {
  25753. this._cachedMaterial = null;
  25754. this._cachedEffect = null;
  25755. this._cachedVisibility = null;
  25756. };
  25757. /**
  25758. * Registers a function to be called before every frame render
  25759. * @param func defines the function to register
  25760. */
  25761. Scene.prototype.registerBeforeRender = function (func) {
  25762. this.onBeforeRenderObservable.add(func);
  25763. };
  25764. /**
  25765. * Unregisters a function called before every frame render
  25766. * @param func defines the function to unregister
  25767. */
  25768. Scene.prototype.unregisterBeforeRender = function (func) {
  25769. this.onBeforeRenderObservable.removeCallback(func);
  25770. };
  25771. /**
  25772. * Registers a function to be called after every frame render
  25773. * @param func defines the function to register
  25774. */
  25775. Scene.prototype.registerAfterRender = function (func) {
  25776. this.onAfterRenderObservable.add(func);
  25777. };
  25778. /**
  25779. * Unregisters a function called after every frame render
  25780. * @param func defines the function to unregister
  25781. */
  25782. Scene.prototype.unregisterAfterRender = function (func) {
  25783. this.onAfterRenderObservable.removeCallback(func);
  25784. };
  25785. Scene.prototype._executeOnceBeforeRender = function (func) {
  25786. var _this = this;
  25787. var execFunc = function () {
  25788. func();
  25789. setTimeout(function () {
  25790. _this.unregisterBeforeRender(execFunc);
  25791. });
  25792. };
  25793. this.registerBeforeRender(execFunc);
  25794. };
  25795. /**
  25796. * The provided function will run before render once and will be disposed afterwards.
  25797. * A timeout delay can be provided so that the function will be executed in N ms.
  25798. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25799. * @param func The function to be executed.
  25800. * @param timeout optional delay in ms
  25801. */
  25802. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25803. var _this = this;
  25804. if (timeout !== undefined) {
  25805. setTimeout(function () {
  25806. _this._executeOnceBeforeRender(func);
  25807. }, timeout);
  25808. }
  25809. else {
  25810. this._executeOnceBeforeRender(func);
  25811. }
  25812. };
  25813. /** @hidden */
  25814. Scene.prototype._addPendingData = function (data) {
  25815. this._pendingData.push(data);
  25816. };
  25817. /** @hidden */
  25818. Scene.prototype._removePendingData = function (data) {
  25819. var wasLoading = this.isLoading;
  25820. var index = this._pendingData.indexOf(data);
  25821. if (index !== -1) {
  25822. this._pendingData.splice(index, 1);
  25823. }
  25824. if (wasLoading && !this.isLoading) {
  25825. this.onDataLoadedObservable.notifyObservers(this);
  25826. }
  25827. };
  25828. /**
  25829. * Returns the number of items waiting to be loaded
  25830. * @returns the number of items waiting to be loaded
  25831. */
  25832. Scene.prototype.getWaitingItemsCount = function () {
  25833. return this._pendingData.length;
  25834. };
  25835. Object.defineProperty(Scene.prototype, "isLoading", {
  25836. /**
  25837. * Returns a boolean indicating if the scene is still loading data
  25838. */
  25839. get: function () {
  25840. return this._pendingData.length > 0;
  25841. },
  25842. enumerable: true,
  25843. configurable: true
  25844. });
  25845. /**
  25846. * Registers a function to be executed when the scene is ready
  25847. * @param {Function} func - the function to be executed
  25848. */
  25849. Scene.prototype.executeWhenReady = function (func) {
  25850. var _this = this;
  25851. this.onReadyObservable.add(func);
  25852. if (this._executeWhenReadyTimeoutId !== -1) {
  25853. return;
  25854. }
  25855. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25856. _this._checkIsReady();
  25857. }, 150);
  25858. };
  25859. /**
  25860. * Returns a promise that resolves when the scene is ready
  25861. * @returns A promise that resolves when the scene is ready
  25862. */
  25863. Scene.prototype.whenReadyAsync = function () {
  25864. var _this = this;
  25865. return new Promise(function (resolve) {
  25866. _this.executeWhenReady(function () {
  25867. resolve();
  25868. });
  25869. });
  25870. };
  25871. /** @hidden */
  25872. Scene.prototype._checkIsReady = function () {
  25873. var _this = this;
  25874. this._registerTransientComponents();
  25875. if (this.isReady()) {
  25876. this.onReadyObservable.notifyObservers(this);
  25877. this.onReadyObservable.clear();
  25878. this._executeWhenReadyTimeoutId = -1;
  25879. return;
  25880. }
  25881. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25882. _this._checkIsReady();
  25883. }, 150);
  25884. };
  25885. // Animations
  25886. /**
  25887. * Will start the animation sequence of a given target
  25888. * @param target defines the target
  25889. * @param from defines from which frame should animation start
  25890. * @param to defines until which frame should animation run.
  25891. * @param weight defines the weight to apply to the animation (1.0 by default)
  25892. * @param loop defines if the animation loops
  25893. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25894. * @param onAnimationEnd defines the function to be executed when the animation ends
  25895. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25896. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25897. * @returns the animatable object created for this animation
  25898. */
  25899. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25900. if (weight === void 0) { weight = 1.0; }
  25901. if (speedRatio === void 0) { speedRatio = 1.0; }
  25902. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25903. returnedAnimatable.weight = weight;
  25904. return returnedAnimatable;
  25905. };
  25906. /**
  25907. * Will start the animation sequence of a given target
  25908. * @param target defines the target
  25909. * @param from defines from which frame should animation start
  25910. * @param to defines until which frame should animation run.
  25911. * @param loop defines if the animation loops
  25912. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25913. * @param onAnimationEnd defines the function to be executed when the animation ends
  25914. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25915. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25916. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25917. * @returns the animatable object created for this animation
  25918. */
  25919. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25920. if (speedRatio === void 0) { speedRatio = 1.0; }
  25921. if (stopCurrent === void 0) { stopCurrent = true; }
  25922. if (from > to && speedRatio > 0) {
  25923. speedRatio *= -1;
  25924. }
  25925. if (stopCurrent) {
  25926. this.stopAnimation(target, undefined, targetMask);
  25927. }
  25928. if (!animatable) {
  25929. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25930. }
  25931. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25932. // Local animations
  25933. if (target.animations && shouldRunTargetAnimations) {
  25934. animatable.appendAnimations(target, target.animations);
  25935. }
  25936. // Children animations
  25937. if (target.getAnimatables) {
  25938. var animatables = target.getAnimatables();
  25939. for (var index = 0; index < animatables.length; index++) {
  25940. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25941. }
  25942. }
  25943. animatable.reset();
  25944. return animatable;
  25945. };
  25946. /**
  25947. * Begin a new animation on a given node
  25948. * @param target defines the target where the animation will take place
  25949. * @param animations defines the list of animations to start
  25950. * @param from defines the initial value
  25951. * @param to defines the final value
  25952. * @param loop defines if you want animation to loop (off by default)
  25953. * @param speedRatio defines the speed ratio to apply to all animations
  25954. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25955. * @returns the list of created animatables
  25956. */
  25957. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25958. if (speedRatio === undefined) {
  25959. speedRatio = 1.0;
  25960. }
  25961. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25962. return animatable;
  25963. };
  25964. /**
  25965. * Begin a new animation on a given node and its hierarchy
  25966. * @param target defines the root node where the animation will take place
  25967. * @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.
  25968. * @param animations defines the list of animations to start
  25969. * @param from defines the initial value
  25970. * @param to defines the final value
  25971. * @param loop defines if you want animation to loop (off by default)
  25972. * @param speedRatio defines the speed ratio to apply to all animations
  25973. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25974. * @returns the list of animatables created for all nodes
  25975. */
  25976. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25977. var children = target.getDescendants(directDescendantsOnly);
  25978. var result = [];
  25979. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25980. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25981. var child = children_1[_i];
  25982. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25983. }
  25984. return result;
  25985. };
  25986. /**
  25987. * Gets the animatable associated with a specific target
  25988. * @param target defines the target of the animatable
  25989. * @returns the required animatable if found
  25990. */
  25991. Scene.prototype.getAnimatableByTarget = function (target) {
  25992. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25993. if (this._activeAnimatables[index].target === target) {
  25994. return this._activeAnimatables[index];
  25995. }
  25996. }
  25997. return null;
  25998. };
  25999. /**
  26000. * Gets all animatables associated with a given target
  26001. * @param target defines the target to look animatables for
  26002. * @returns an array of Animatables
  26003. */
  26004. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26005. var result = [];
  26006. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26007. if (this._activeAnimatables[index].target === target) {
  26008. result.push(this._activeAnimatables[index]);
  26009. }
  26010. }
  26011. return result;
  26012. };
  26013. Object.defineProperty(Scene.prototype, "animatables", {
  26014. /**
  26015. * Gets all animatable attached to the scene
  26016. */
  26017. get: function () {
  26018. return this._activeAnimatables;
  26019. },
  26020. enumerable: true,
  26021. configurable: true
  26022. });
  26023. /**
  26024. * Will stop the animation of the given target
  26025. * @param target - the target
  26026. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26027. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  26028. */
  26029. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26030. var animatables = this.getAllAnimatablesByTarget(target);
  26031. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26032. var animatable = animatables_1[_i];
  26033. animatable.stop(animationName, targetMask);
  26034. }
  26035. };
  26036. /**
  26037. * Stops and removes all animations that have been applied to the scene
  26038. */
  26039. Scene.prototype.stopAllAnimations = function () {
  26040. if (this._activeAnimatables) {
  26041. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26042. this._activeAnimatables[i].stop();
  26043. }
  26044. this._activeAnimatables = [];
  26045. }
  26046. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26047. var group = _a[_i];
  26048. group.stop();
  26049. }
  26050. };
  26051. Scene.prototype._animate = function () {
  26052. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26053. return;
  26054. }
  26055. // Getting time
  26056. var now = BABYLON.Tools.Now;
  26057. if (!this._animationTimeLast) {
  26058. if (this._pendingData.length > 0) {
  26059. return;
  26060. }
  26061. this._animationTimeLast = now;
  26062. }
  26063. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26064. this._animationTime += deltaTime;
  26065. this._animationTimeLast = now;
  26066. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26067. this._activeAnimatables[index]._animate(this._animationTime);
  26068. }
  26069. // Late animation bindings
  26070. this._processLateAnimationBindings();
  26071. };
  26072. /** @hidden */
  26073. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26074. var target = runtimeAnimation.target;
  26075. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26076. if (!target._lateAnimationHolders) {
  26077. target._lateAnimationHolders = {};
  26078. }
  26079. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26080. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26081. totalWeight: 0,
  26082. animations: [],
  26083. originalValue: originalValue
  26084. };
  26085. }
  26086. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26087. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26088. };
  26089. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26090. var normalizer = 1.0;
  26091. var finalPosition = BABYLON.Tmp.Vector3[0];
  26092. var finalScaling = BABYLON.Tmp.Vector3[1];
  26093. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26094. var startIndex = 0;
  26095. var originalAnimation = holder.animations[0];
  26096. var originalValue = holder.originalValue;
  26097. var scale = 1;
  26098. if (holder.totalWeight < 1.0) {
  26099. // We need to mix the original value in
  26100. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26101. scale = 1.0 - holder.totalWeight;
  26102. }
  26103. else {
  26104. startIndex = 1;
  26105. // We need to normalize the weights
  26106. normalizer = holder.totalWeight;
  26107. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26108. scale = originalAnimation.weight / normalizer;
  26109. if (scale == 1) {
  26110. return originalAnimation.currentValue;
  26111. }
  26112. }
  26113. finalScaling.scaleInPlace(scale);
  26114. finalPosition.scaleInPlace(scale);
  26115. finalQuaternion.scaleInPlace(scale);
  26116. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26117. var runtimeAnimation = holder.animations[animIndex];
  26118. var scale = runtimeAnimation.weight / normalizer;
  26119. var currentPosition = BABYLON.Tmp.Vector3[2];
  26120. var currentScaling = BABYLON.Tmp.Vector3[3];
  26121. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26122. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26123. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26124. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26125. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26126. }
  26127. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26128. return originalAnimation._workValue;
  26129. };
  26130. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26131. var originalAnimation = holder.animations[0];
  26132. var originalValue = holder.originalValue;
  26133. if (holder.animations.length === 1) {
  26134. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26135. return refQuaternion;
  26136. }
  26137. var normalizer = 1.0;
  26138. var quaternions;
  26139. var weights;
  26140. if (holder.totalWeight < 1.0) {
  26141. var scale = 1.0 - holder.totalWeight;
  26142. quaternions = [];
  26143. weights = [];
  26144. quaternions.push(originalValue);
  26145. weights.push(scale);
  26146. }
  26147. else {
  26148. if (holder.animations.length === 2) { // Slerp as soon as we can
  26149. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26150. return refQuaternion;
  26151. }
  26152. quaternions = [];
  26153. weights = [];
  26154. normalizer = holder.totalWeight;
  26155. }
  26156. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26157. var runtimeAnimation = holder.animations[animIndex];
  26158. quaternions.push(runtimeAnimation.currentValue);
  26159. weights.push(runtimeAnimation.weight / normalizer);
  26160. }
  26161. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26162. var cumulativeAmount = 0;
  26163. var cumulativeQuaternion = null;
  26164. for (var index = 0; index < quaternions.length;) {
  26165. if (!cumulativeQuaternion) {
  26166. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26167. cumulativeQuaternion = refQuaternion;
  26168. cumulativeAmount = weights[index] + weights[index + 1];
  26169. index += 2;
  26170. continue;
  26171. }
  26172. cumulativeAmount += weights[index];
  26173. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26174. index++;
  26175. }
  26176. return cumulativeQuaternion;
  26177. };
  26178. Scene.prototype._processLateAnimationBindings = function () {
  26179. if (!this._registeredForLateAnimationBindings.length) {
  26180. return;
  26181. }
  26182. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26183. var target = this._registeredForLateAnimationBindings.data[index];
  26184. for (var path in target._lateAnimationHolders) {
  26185. var holder = target._lateAnimationHolders[path];
  26186. var originalAnimation = holder.animations[0];
  26187. var originalValue = holder.originalValue;
  26188. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26189. var finalValue = target[path];
  26190. if (matrixDecomposeMode) {
  26191. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26192. }
  26193. else {
  26194. var quaternionMode = originalValue.w !== undefined;
  26195. if (quaternionMode) {
  26196. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26197. }
  26198. else {
  26199. var startIndex = 0;
  26200. var normalizer = 1.0;
  26201. if (holder.totalWeight < 1.0) {
  26202. // We need to mix the original value in
  26203. if (originalValue.scale) {
  26204. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26205. }
  26206. else {
  26207. finalValue = originalValue * (1.0 - holder.totalWeight);
  26208. }
  26209. }
  26210. else {
  26211. // We need to normalize the weights
  26212. normalizer = holder.totalWeight;
  26213. var scale_1 = originalAnimation.weight / normalizer;
  26214. if (scale_1 !== 1) {
  26215. if (originalAnimation.currentValue.scale) {
  26216. finalValue = originalAnimation.currentValue.scale(scale_1);
  26217. }
  26218. else {
  26219. finalValue = originalAnimation.currentValue * scale_1;
  26220. }
  26221. }
  26222. else {
  26223. finalValue = originalAnimation.currentValue;
  26224. }
  26225. startIndex = 1;
  26226. }
  26227. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26228. var runtimeAnimation = holder.animations[animIndex];
  26229. var scale = runtimeAnimation.weight / normalizer;
  26230. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26231. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26232. }
  26233. else {
  26234. finalValue += runtimeAnimation.currentValue * scale;
  26235. }
  26236. }
  26237. }
  26238. }
  26239. target[path] = finalValue;
  26240. }
  26241. target._lateAnimationHolders = {};
  26242. }
  26243. this._registeredForLateAnimationBindings.reset();
  26244. };
  26245. // Matrix
  26246. /** @hidden */
  26247. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26248. this._useAlternateCameraConfiguration = active;
  26249. };
  26250. /**
  26251. * Gets the current view matrix
  26252. * @returns a Matrix
  26253. */
  26254. Scene.prototype.getViewMatrix = function () {
  26255. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26256. };
  26257. /**
  26258. * Gets the current projection matrix
  26259. * @returns a Matrix
  26260. */
  26261. Scene.prototype.getProjectionMatrix = function () {
  26262. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26263. };
  26264. /**
  26265. * Gets the current transform matrix
  26266. * @returns a Matrix made of View * Projection
  26267. */
  26268. Scene.prototype.getTransformMatrix = function () {
  26269. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26270. };
  26271. /**
  26272. * Sets the current transform matrix
  26273. * @param view defines the View matrix to use
  26274. * @param projection defines the Projection matrix to use
  26275. */
  26276. Scene.prototype.setTransformMatrix = function (view, projection) {
  26277. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26278. return;
  26279. }
  26280. this._viewUpdateFlag = view.updateFlag;
  26281. this._projectionUpdateFlag = projection.updateFlag;
  26282. this._viewMatrix = view;
  26283. this._projectionMatrix = projection;
  26284. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26285. // Update frustum
  26286. if (!this._frustumPlanes) {
  26287. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26288. }
  26289. else {
  26290. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26291. }
  26292. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26293. var otherCamera = this.activeCamera._alternateCamera;
  26294. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26295. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26296. }
  26297. if (this._sceneUbo.useUbo) {
  26298. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26299. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26300. this._sceneUbo.update();
  26301. }
  26302. };
  26303. /** @hidden */
  26304. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26305. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26306. return;
  26307. }
  26308. this._alternateViewUpdateFlag = view.updateFlag;
  26309. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26310. this._alternateViewMatrix = view;
  26311. this._alternateProjectionMatrix = projection;
  26312. if (!this._alternateTransformMatrix) {
  26313. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26314. }
  26315. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26316. if (!this._alternateSceneUbo) {
  26317. this._createAlternateUbo();
  26318. }
  26319. if (this._alternateSceneUbo.useUbo) {
  26320. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26321. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26322. this._alternateSceneUbo.update();
  26323. }
  26324. };
  26325. /**
  26326. * Gets the uniform buffer used to store scene data
  26327. * @returns a UniformBuffer
  26328. */
  26329. Scene.prototype.getSceneUniformBuffer = function () {
  26330. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26331. };
  26332. /**
  26333. * Gets an unique (relatively to the current scene) Id
  26334. * @returns an unique number for the scene
  26335. */
  26336. Scene.prototype.getUniqueId = function () {
  26337. var result = Scene._uniqueIdCounter;
  26338. Scene._uniqueIdCounter++;
  26339. return result;
  26340. };
  26341. /**
  26342. * Add a mesh to the list of scene's meshes
  26343. * @param newMesh defines the mesh to add
  26344. * @param recursive if all child meshes should also be added to the scene
  26345. */
  26346. Scene.prototype.addMesh = function (newMesh, recursive) {
  26347. var _this = this;
  26348. if (recursive === void 0) { recursive = false; }
  26349. this.meshes.push(newMesh);
  26350. //notify the collision coordinator
  26351. if (this.collisionCoordinator) {
  26352. this.collisionCoordinator.onMeshAdded(newMesh);
  26353. }
  26354. newMesh._resyncLightSources();
  26355. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26356. if (recursive) {
  26357. newMesh.getChildMeshes().forEach(function (m) {
  26358. _this.addMesh(m);
  26359. });
  26360. }
  26361. };
  26362. /**
  26363. * Remove a mesh for the list of scene's meshes
  26364. * @param toRemove defines the mesh to remove
  26365. * @param recursive if all child meshes should also be removed from the scene
  26366. * @returns the index where the mesh was in the mesh list
  26367. */
  26368. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26369. var _this = this;
  26370. if (recursive === void 0) { recursive = false; }
  26371. var index = this.meshes.indexOf(toRemove);
  26372. if (index !== -1) {
  26373. // Remove from the scene if mesh found
  26374. this.meshes.splice(index, 1);
  26375. }
  26376. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26377. if (recursive) {
  26378. toRemove.getChildMeshes().forEach(function (m) {
  26379. _this.removeMesh(m);
  26380. });
  26381. }
  26382. return index;
  26383. };
  26384. /**
  26385. * Add a transform node to the list of scene's transform nodes
  26386. * @param newTransformNode defines the transform node to add
  26387. */
  26388. Scene.prototype.addTransformNode = function (newTransformNode) {
  26389. this.transformNodes.push(newTransformNode);
  26390. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26391. };
  26392. /**
  26393. * Remove a transform node for the list of scene's transform nodes
  26394. * @param toRemove defines the transform node to remove
  26395. * @returns the index where the transform node was in the transform node list
  26396. */
  26397. Scene.prototype.removeTransformNode = function (toRemove) {
  26398. var index = this.transformNodes.indexOf(toRemove);
  26399. if (index !== -1) {
  26400. // Remove from the scene if found
  26401. this.transformNodes.splice(index, 1);
  26402. }
  26403. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26404. return index;
  26405. };
  26406. /**
  26407. * Remove a skeleton for the list of scene's skeletons
  26408. * @param toRemove defines the skeleton to remove
  26409. * @returns the index where the skeleton was in the skeleton list
  26410. */
  26411. Scene.prototype.removeSkeleton = function (toRemove) {
  26412. var index = this.skeletons.indexOf(toRemove);
  26413. if (index !== -1) {
  26414. // Remove from the scene if found
  26415. this.skeletons.splice(index, 1);
  26416. }
  26417. return index;
  26418. };
  26419. /**
  26420. * Remove a morph target for the list of scene's morph targets
  26421. * @param toRemove defines the morph target to remove
  26422. * @returns the index where the morph target was in the morph target list
  26423. */
  26424. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26425. var index = this.morphTargetManagers.indexOf(toRemove);
  26426. if (index !== -1) {
  26427. // Remove from the scene if found
  26428. this.morphTargetManagers.splice(index, 1);
  26429. }
  26430. return index;
  26431. };
  26432. /**
  26433. * Remove a light for the list of scene's lights
  26434. * @param toRemove defines the light to remove
  26435. * @returns the index where the light was in the light list
  26436. */
  26437. Scene.prototype.removeLight = function (toRemove) {
  26438. var index = this.lights.indexOf(toRemove);
  26439. if (index !== -1) {
  26440. // Remove from meshes
  26441. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26442. var mesh = _a[_i];
  26443. mesh._removeLightSource(toRemove);
  26444. }
  26445. // Remove from the scene if mesh found
  26446. this.lights.splice(index, 1);
  26447. this.sortLightsByPriority();
  26448. }
  26449. this.onLightRemovedObservable.notifyObservers(toRemove);
  26450. return index;
  26451. };
  26452. /**
  26453. * Remove a camera for the list of scene's cameras
  26454. * @param toRemove defines the camera to remove
  26455. * @returns the index where the camera was in the camera list
  26456. */
  26457. Scene.prototype.removeCamera = function (toRemove) {
  26458. var index = this.cameras.indexOf(toRemove);
  26459. if (index !== -1) {
  26460. // Remove from the scene if mesh found
  26461. this.cameras.splice(index, 1);
  26462. }
  26463. // Remove from activeCameras
  26464. var index2 = this.activeCameras.indexOf(toRemove);
  26465. if (index2 !== -1) {
  26466. // Remove from the scene if mesh found
  26467. this.activeCameras.splice(index2, 1);
  26468. }
  26469. // Reset the activeCamera
  26470. if (this.activeCamera === toRemove) {
  26471. if (this.cameras.length > 0) {
  26472. this.activeCamera = this.cameras[0];
  26473. }
  26474. else {
  26475. this.activeCamera = null;
  26476. }
  26477. }
  26478. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26479. return index;
  26480. };
  26481. /**
  26482. * Remove a particle system for the list of scene's particle systems
  26483. * @param toRemove defines the particle system to remove
  26484. * @returns the index where the particle system was in the particle system list
  26485. */
  26486. Scene.prototype.removeParticleSystem = function (toRemove) {
  26487. var index = this.particleSystems.indexOf(toRemove);
  26488. if (index !== -1) {
  26489. this.particleSystems.splice(index, 1);
  26490. }
  26491. return index;
  26492. };
  26493. /**
  26494. * Remove a animation for the list of scene's animations
  26495. * @param toRemove defines the animation to remove
  26496. * @returns the index where the animation was in the animation list
  26497. */
  26498. Scene.prototype.removeAnimation = function (toRemove) {
  26499. var index = this.animations.indexOf(toRemove);
  26500. if (index !== -1) {
  26501. this.animations.splice(index, 1);
  26502. }
  26503. return index;
  26504. };
  26505. /**
  26506. * Removes the given animation group from this scene.
  26507. * @param toRemove The animation group to remove
  26508. * @returns The index of the removed animation group
  26509. */
  26510. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26511. var index = this.animationGroups.indexOf(toRemove);
  26512. if (index !== -1) {
  26513. this.animationGroups.splice(index, 1);
  26514. }
  26515. return index;
  26516. };
  26517. /**
  26518. * Removes the given multi-material from this scene.
  26519. * @param toRemove The multi-material to remove
  26520. * @returns The index of the removed multi-material
  26521. */
  26522. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26523. var index = this.multiMaterials.indexOf(toRemove);
  26524. if (index !== -1) {
  26525. this.multiMaterials.splice(index, 1);
  26526. }
  26527. return index;
  26528. };
  26529. /**
  26530. * Removes the given material from this scene.
  26531. * @param toRemove The material to remove
  26532. * @returns The index of the removed material
  26533. */
  26534. Scene.prototype.removeMaterial = function (toRemove) {
  26535. var index = this.materials.indexOf(toRemove);
  26536. if (index !== -1) {
  26537. this.materials.splice(index, 1);
  26538. }
  26539. return index;
  26540. };
  26541. /**
  26542. * Removes the given action manager from this scene.
  26543. * @param toRemove The action manager to remove
  26544. * @returns The index of the removed action manager
  26545. */
  26546. Scene.prototype.removeActionManager = function (toRemove) {
  26547. var index = this.actionManagers.indexOf(toRemove);
  26548. if (index !== -1) {
  26549. this.actionManagers.splice(index, 1);
  26550. }
  26551. return index;
  26552. };
  26553. /**
  26554. * Removes the given texture from this scene.
  26555. * @param toRemove The texture to remove
  26556. * @returns The index of the removed texture
  26557. */
  26558. Scene.prototype.removeTexture = function (toRemove) {
  26559. var index = this.textures.indexOf(toRemove);
  26560. if (index !== -1) {
  26561. this.textures.splice(index, 1);
  26562. }
  26563. return index;
  26564. };
  26565. /**
  26566. * Adds the given light to this scene
  26567. * @param newLight The light to add
  26568. */
  26569. Scene.prototype.addLight = function (newLight) {
  26570. this.lights.push(newLight);
  26571. this.sortLightsByPriority();
  26572. // Add light to all meshes (To support if the light is removed and then readded)
  26573. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26574. var mesh = _a[_i];
  26575. if (mesh._lightSources.indexOf(newLight) === -1) {
  26576. mesh._lightSources.push(newLight);
  26577. mesh._resyncLightSources();
  26578. }
  26579. }
  26580. this.onNewLightAddedObservable.notifyObservers(newLight);
  26581. };
  26582. /**
  26583. * Sorts the list list based on light priorities
  26584. */
  26585. Scene.prototype.sortLightsByPriority = function () {
  26586. if (this.requireLightSorting) {
  26587. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26588. }
  26589. };
  26590. /**
  26591. * Adds the given camera to this scene
  26592. * @param newCamera The camera to add
  26593. */
  26594. Scene.prototype.addCamera = function (newCamera) {
  26595. this.cameras.push(newCamera);
  26596. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26597. };
  26598. /**
  26599. * Adds the given skeleton to this scene
  26600. * @param newSkeleton The skeleton to add
  26601. */
  26602. Scene.prototype.addSkeleton = function (newSkeleton) {
  26603. this.skeletons.push(newSkeleton);
  26604. };
  26605. /**
  26606. * Adds the given particle system to this scene
  26607. * @param newParticleSystem The particle system to add
  26608. */
  26609. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26610. this.particleSystems.push(newParticleSystem);
  26611. };
  26612. /**
  26613. * Adds the given animation to this scene
  26614. * @param newAnimation The animation to add
  26615. */
  26616. Scene.prototype.addAnimation = function (newAnimation) {
  26617. this.animations.push(newAnimation);
  26618. };
  26619. /**
  26620. * Adds the given animation group to this scene.
  26621. * @param newAnimationGroup The animation group to add
  26622. */
  26623. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26624. this.animationGroups.push(newAnimationGroup);
  26625. };
  26626. /**
  26627. * Adds the given multi-material to this scene
  26628. * @param newMultiMaterial The multi-material to add
  26629. */
  26630. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26631. this.multiMaterials.push(newMultiMaterial);
  26632. };
  26633. /**
  26634. * Adds the given material to this scene
  26635. * @param newMaterial The material to add
  26636. */
  26637. Scene.prototype.addMaterial = function (newMaterial) {
  26638. this.materials.push(newMaterial);
  26639. };
  26640. /**
  26641. * Adds the given morph target to this scene
  26642. * @param newMorphTargetManager The morph target to add
  26643. */
  26644. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26645. this.morphTargetManagers.push(newMorphTargetManager);
  26646. };
  26647. /**
  26648. * Adds the given geometry to this scene
  26649. * @param newGeometry The geometry to add
  26650. */
  26651. Scene.prototype.addGeometry = function (newGeometry) {
  26652. this.geometries.push(newGeometry);
  26653. };
  26654. /**
  26655. * Adds the given action manager to this scene
  26656. * @param newActionManager The action manager to add
  26657. */
  26658. Scene.prototype.addActionManager = function (newActionManager) {
  26659. this.actionManagers.push(newActionManager);
  26660. };
  26661. /**
  26662. * Adds the given texture to this scene.
  26663. * @param newTexture The texture to add
  26664. */
  26665. Scene.prototype.addTexture = function (newTexture) {
  26666. this.textures.push(newTexture);
  26667. };
  26668. /**
  26669. * Switch active camera
  26670. * @param newCamera defines the new active camera
  26671. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26672. */
  26673. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26674. if (attachControl === void 0) { attachControl = true; }
  26675. var canvas = this._engine.getRenderingCanvas();
  26676. if (!canvas) {
  26677. return;
  26678. }
  26679. if (this.activeCamera) {
  26680. this.activeCamera.detachControl(canvas);
  26681. }
  26682. this.activeCamera = newCamera;
  26683. if (attachControl) {
  26684. newCamera.attachControl(canvas);
  26685. }
  26686. };
  26687. /**
  26688. * sets the active camera of the scene using its ID
  26689. * @param id defines the camera's ID
  26690. * @return the new active camera or null if none found.
  26691. */
  26692. Scene.prototype.setActiveCameraByID = function (id) {
  26693. var camera = this.getCameraByID(id);
  26694. if (camera) {
  26695. this.activeCamera = camera;
  26696. return camera;
  26697. }
  26698. return null;
  26699. };
  26700. /**
  26701. * sets the active camera of the scene using its name
  26702. * @param name defines the camera's name
  26703. * @returns the new active camera or null if none found.
  26704. */
  26705. Scene.prototype.setActiveCameraByName = function (name) {
  26706. var camera = this.getCameraByName(name);
  26707. if (camera) {
  26708. this.activeCamera = camera;
  26709. return camera;
  26710. }
  26711. return null;
  26712. };
  26713. /**
  26714. * get an animation group using its name
  26715. * @param name defines the material's name
  26716. * @return the animation group or null if none found.
  26717. */
  26718. Scene.prototype.getAnimationGroupByName = function (name) {
  26719. for (var index = 0; index < this.animationGroups.length; index++) {
  26720. if (this.animationGroups[index].name === name) {
  26721. return this.animationGroups[index];
  26722. }
  26723. }
  26724. return null;
  26725. };
  26726. /**
  26727. * get a material using its id
  26728. * @param id defines the material's ID
  26729. * @return the material or null if none found.
  26730. */
  26731. Scene.prototype.getMaterialByID = function (id) {
  26732. for (var index = 0; index < this.materials.length; index++) {
  26733. if (this.materials[index].id === id) {
  26734. return this.materials[index];
  26735. }
  26736. }
  26737. return null;
  26738. };
  26739. /**
  26740. * Gets a material using its name
  26741. * @param name defines the material's name
  26742. * @return the material or null if none found.
  26743. */
  26744. Scene.prototype.getMaterialByName = function (name) {
  26745. for (var index = 0; index < this.materials.length; index++) {
  26746. if (this.materials[index].name === name) {
  26747. return this.materials[index];
  26748. }
  26749. }
  26750. return null;
  26751. };
  26752. /**
  26753. * Gets a camera using its id
  26754. * @param id defines the id to look for
  26755. * @returns the camera or null if not found
  26756. */
  26757. Scene.prototype.getCameraByID = function (id) {
  26758. for (var index = 0; index < this.cameras.length; index++) {
  26759. if (this.cameras[index].id === id) {
  26760. return this.cameras[index];
  26761. }
  26762. }
  26763. return null;
  26764. };
  26765. /**
  26766. * Gets a camera using its unique id
  26767. * @param uniqueId defines the unique id to look for
  26768. * @returns the camera or null if not found
  26769. */
  26770. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26771. for (var index = 0; index < this.cameras.length; index++) {
  26772. if (this.cameras[index].uniqueId === uniqueId) {
  26773. return this.cameras[index];
  26774. }
  26775. }
  26776. return null;
  26777. };
  26778. /**
  26779. * Gets a camera using its name
  26780. * @param name defines the camera's name
  26781. * @return the camera or null if none found.
  26782. */
  26783. Scene.prototype.getCameraByName = function (name) {
  26784. for (var index = 0; index < this.cameras.length; index++) {
  26785. if (this.cameras[index].name === name) {
  26786. return this.cameras[index];
  26787. }
  26788. }
  26789. return null;
  26790. };
  26791. /**
  26792. * Gets a bone using its id
  26793. * @param id defines the bone's id
  26794. * @return the bone or null if not found
  26795. */
  26796. Scene.prototype.getBoneByID = function (id) {
  26797. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26798. var skeleton = this.skeletons[skeletonIndex];
  26799. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26800. if (skeleton.bones[boneIndex].id === id) {
  26801. return skeleton.bones[boneIndex];
  26802. }
  26803. }
  26804. }
  26805. return null;
  26806. };
  26807. /**
  26808. * Gets a bone using its id
  26809. * @param name defines the bone's name
  26810. * @return the bone or null if not found
  26811. */
  26812. Scene.prototype.getBoneByName = function (name) {
  26813. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26814. var skeleton = this.skeletons[skeletonIndex];
  26815. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26816. if (skeleton.bones[boneIndex].name === name) {
  26817. return skeleton.bones[boneIndex];
  26818. }
  26819. }
  26820. }
  26821. return null;
  26822. };
  26823. /**
  26824. * Gets a light node using its name
  26825. * @param name defines the the light's name
  26826. * @return the light or null if none found.
  26827. */
  26828. Scene.prototype.getLightByName = function (name) {
  26829. for (var index = 0; index < this.lights.length; index++) {
  26830. if (this.lights[index].name === name) {
  26831. return this.lights[index];
  26832. }
  26833. }
  26834. return null;
  26835. };
  26836. /**
  26837. * Gets a light node using its id
  26838. * @param id defines the light's id
  26839. * @return the light or null if none found.
  26840. */
  26841. Scene.prototype.getLightByID = function (id) {
  26842. for (var index = 0; index < this.lights.length; index++) {
  26843. if (this.lights[index].id === id) {
  26844. return this.lights[index];
  26845. }
  26846. }
  26847. return null;
  26848. };
  26849. /**
  26850. * Gets a light node using its scene-generated unique ID
  26851. * @param uniqueId defines the light's unique id
  26852. * @return the light or null if none found.
  26853. */
  26854. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26855. for (var index = 0; index < this.lights.length; index++) {
  26856. if (this.lights[index].uniqueId === uniqueId) {
  26857. return this.lights[index];
  26858. }
  26859. }
  26860. return null;
  26861. };
  26862. /**
  26863. * Gets a particle system by id
  26864. * @param id defines the particle system id
  26865. * @return the corresponding system or null if none found
  26866. */
  26867. Scene.prototype.getParticleSystemByID = function (id) {
  26868. for (var index = 0; index < this.particleSystems.length; index++) {
  26869. if (this.particleSystems[index].id === id) {
  26870. return this.particleSystems[index];
  26871. }
  26872. }
  26873. return null;
  26874. };
  26875. /**
  26876. * Gets a geometry using its ID
  26877. * @param id defines the geometry's id
  26878. * @return the geometry or null if none found.
  26879. */
  26880. Scene.prototype.getGeometryByID = function (id) {
  26881. for (var index = 0; index < this.geometries.length; index++) {
  26882. if (this.geometries[index].id === id) {
  26883. return this.geometries[index];
  26884. }
  26885. }
  26886. return null;
  26887. };
  26888. /**
  26889. * Add a new geometry to this scene
  26890. * @param geometry defines the geometry to be added to the scene.
  26891. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26892. * @return a boolean defining if the geometry was added or not
  26893. */
  26894. Scene.prototype.pushGeometry = function (geometry, force) {
  26895. if (!force && this.getGeometryByID(geometry.id)) {
  26896. return false;
  26897. }
  26898. this.geometries.push(geometry);
  26899. //notify the collision coordinator
  26900. if (this.collisionCoordinator) {
  26901. this.collisionCoordinator.onGeometryAdded(geometry);
  26902. }
  26903. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26904. return true;
  26905. };
  26906. /**
  26907. * Removes an existing geometry
  26908. * @param geometry defines the geometry to be removed from the scene
  26909. * @return a boolean defining if the geometry was removed or not
  26910. */
  26911. Scene.prototype.removeGeometry = function (geometry) {
  26912. var index = this.geometries.indexOf(geometry);
  26913. if (index > -1) {
  26914. this.geometries.splice(index, 1);
  26915. //notify the collision coordinator
  26916. if (this.collisionCoordinator) {
  26917. this.collisionCoordinator.onGeometryDeleted(geometry);
  26918. }
  26919. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26920. return true;
  26921. }
  26922. return false;
  26923. };
  26924. /**
  26925. * Gets the list of geometries attached to the scene
  26926. * @returns an array of Geometry
  26927. */
  26928. Scene.prototype.getGeometries = function () {
  26929. return this.geometries;
  26930. };
  26931. /**
  26932. * Gets the first added mesh found of a given ID
  26933. * @param id defines the id to search for
  26934. * @return the mesh found or null if not found at all
  26935. */
  26936. Scene.prototype.getMeshByID = function (id) {
  26937. for (var index = 0; index < this.meshes.length; index++) {
  26938. if (this.meshes[index].id === id) {
  26939. return this.meshes[index];
  26940. }
  26941. }
  26942. return null;
  26943. };
  26944. /**
  26945. * Gets a list of meshes using their id
  26946. * @param id defines the id to search for
  26947. * @returns a list of meshes
  26948. */
  26949. Scene.prototype.getMeshesByID = function (id) {
  26950. return this.meshes.filter(function (m) {
  26951. return m.id === id;
  26952. });
  26953. };
  26954. /**
  26955. * Gets the first added transform node found of a given ID
  26956. * @param id defines the id to search for
  26957. * @return the found transform node or null if not found at all.
  26958. */
  26959. Scene.prototype.getTransformNodeByID = function (id) {
  26960. for (var index = 0; index < this.transformNodes.length; index++) {
  26961. if (this.transformNodes[index].id === id) {
  26962. return this.transformNodes[index];
  26963. }
  26964. }
  26965. return null;
  26966. };
  26967. /**
  26968. * Gets a list of transform nodes using their id
  26969. * @param id defines the id to search for
  26970. * @returns a list of transform nodes
  26971. */
  26972. Scene.prototype.getTransformNodesByID = function (id) {
  26973. return this.transformNodes.filter(function (m) {
  26974. return m.id === id;
  26975. });
  26976. };
  26977. /**
  26978. * Gets a mesh with its auto-generated unique id
  26979. * @param uniqueId defines the unique id to search for
  26980. * @return the found mesh or null if not found at all.
  26981. */
  26982. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26983. for (var index = 0; index < this.meshes.length; index++) {
  26984. if (this.meshes[index].uniqueId === uniqueId) {
  26985. return this.meshes[index];
  26986. }
  26987. }
  26988. return null;
  26989. };
  26990. /**
  26991. * Gets a the last added mesh using a given id
  26992. * @param id defines the id to search for
  26993. * @return the found mesh or null if not found at all.
  26994. */
  26995. Scene.prototype.getLastMeshByID = function (id) {
  26996. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26997. if (this.meshes[index].id === id) {
  26998. return this.meshes[index];
  26999. }
  27000. }
  27001. return null;
  27002. };
  27003. /**
  27004. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27005. * @param id defines the id to search for
  27006. * @return the found node or null if not found at all
  27007. */
  27008. Scene.prototype.getLastEntryByID = function (id) {
  27009. var index;
  27010. for (index = this.meshes.length - 1; index >= 0; index--) {
  27011. if (this.meshes[index].id === id) {
  27012. return this.meshes[index];
  27013. }
  27014. }
  27015. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27016. if (this.transformNodes[index].id === id) {
  27017. return this.transformNodes[index];
  27018. }
  27019. }
  27020. for (index = this.cameras.length - 1; index >= 0; index--) {
  27021. if (this.cameras[index].id === id) {
  27022. return this.cameras[index];
  27023. }
  27024. }
  27025. for (index = this.lights.length - 1; index >= 0; index--) {
  27026. if (this.lights[index].id === id) {
  27027. return this.lights[index];
  27028. }
  27029. }
  27030. return null;
  27031. };
  27032. /**
  27033. * Gets a node (Mesh, Camera, Light) using a given id
  27034. * @param id defines the id to search for
  27035. * @return the found node or null if not found at all
  27036. */
  27037. Scene.prototype.getNodeByID = function (id) {
  27038. var mesh = this.getMeshByID(id);
  27039. if (mesh) {
  27040. return mesh;
  27041. }
  27042. var light = this.getLightByID(id);
  27043. if (light) {
  27044. return light;
  27045. }
  27046. var camera = this.getCameraByID(id);
  27047. if (camera) {
  27048. return camera;
  27049. }
  27050. var bone = this.getBoneByID(id);
  27051. return bone;
  27052. };
  27053. /**
  27054. * Gets a node (Mesh, Camera, Light) using a given name
  27055. * @param name defines the name to search for
  27056. * @return the found node or null if not found at all.
  27057. */
  27058. Scene.prototype.getNodeByName = function (name) {
  27059. var mesh = this.getMeshByName(name);
  27060. if (mesh) {
  27061. return mesh;
  27062. }
  27063. var light = this.getLightByName(name);
  27064. if (light) {
  27065. return light;
  27066. }
  27067. var camera = this.getCameraByName(name);
  27068. if (camera) {
  27069. return camera;
  27070. }
  27071. var bone = this.getBoneByName(name);
  27072. return bone;
  27073. };
  27074. /**
  27075. * Gets a mesh using a given name
  27076. * @param name defines the name to search for
  27077. * @return the found mesh or null if not found at all.
  27078. */
  27079. Scene.prototype.getMeshByName = function (name) {
  27080. for (var index = 0; index < this.meshes.length; index++) {
  27081. if (this.meshes[index].name === name) {
  27082. return this.meshes[index];
  27083. }
  27084. }
  27085. return null;
  27086. };
  27087. /**
  27088. * Gets a transform node using a given name
  27089. * @param name defines the name to search for
  27090. * @return the found transform node or null if not found at all.
  27091. */
  27092. Scene.prototype.getTransformNodeByName = function (name) {
  27093. for (var index = 0; index < this.transformNodes.length; index++) {
  27094. if (this.transformNodes[index].name === name) {
  27095. return this.transformNodes[index];
  27096. }
  27097. }
  27098. return null;
  27099. };
  27100. /**
  27101. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27102. * @param id defines the id to search for
  27103. * @return the found skeleton or null if not found at all.
  27104. */
  27105. Scene.prototype.getLastSkeletonByID = function (id) {
  27106. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27107. if (this.skeletons[index].id === id) {
  27108. return this.skeletons[index];
  27109. }
  27110. }
  27111. return null;
  27112. };
  27113. /**
  27114. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27115. * @param id defines the id to search for
  27116. * @return the found skeleton or null if not found at all.
  27117. */
  27118. Scene.prototype.getSkeletonById = function (id) {
  27119. for (var index = 0; index < this.skeletons.length; index++) {
  27120. if (this.skeletons[index].id === id) {
  27121. return this.skeletons[index];
  27122. }
  27123. }
  27124. return null;
  27125. };
  27126. /**
  27127. * Gets a skeleton using a given name
  27128. * @param name defines the name to search for
  27129. * @return the found skeleton or null if not found at all.
  27130. */
  27131. Scene.prototype.getSkeletonByName = function (name) {
  27132. for (var index = 0; index < this.skeletons.length; index++) {
  27133. if (this.skeletons[index].name === name) {
  27134. return this.skeletons[index];
  27135. }
  27136. }
  27137. return null;
  27138. };
  27139. /**
  27140. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27141. * @param id defines the id to search for
  27142. * @return the found morph target manager or null if not found at all.
  27143. */
  27144. Scene.prototype.getMorphTargetManagerById = function (id) {
  27145. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27146. if (this.morphTargetManagers[index].uniqueId === id) {
  27147. return this.morphTargetManagers[index];
  27148. }
  27149. }
  27150. return null;
  27151. };
  27152. /**
  27153. * Gets a boolean indicating if the given mesh is active
  27154. * @param mesh defines the mesh to look for
  27155. * @returns true if the mesh is in the active list
  27156. */
  27157. Scene.prototype.isActiveMesh = function (mesh) {
  27158. return (this._activeMeshes.indexOf(mesh) !== -1);
  27159. };
  27160. Object.defineProperty(Scene.prototype, "uid", {
  27161. /**
  27162. * Return a unique id as a string which can serve as an identifier for the scene
  27163. */
  27164. get: function () {
  27165. if (!this._uid) {
  27166. this._uid = BABYLON.Tools.RandomId();
  27167. }
  27168. return this._uid;
  27169. },
  27170. enumerable: true,
  27171. configurable: true
  27172. });
  27173. /**
  27174. * Add an externaly attached data from its key.
  27175. * This method call will fail and return false, if such key already exists.
  27176. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27177. * @param key the unique key that identifies the data
  27178. * @param data the data object to associate to the key for this Engine instance
  27179. * @return true if no such key were already present and the data was added successfully, false otherwise
  27180. */
  27181. Scene.prototype.addExternalData = function (key, data) {
  27182. if (!this._externalData) {
  27183. this._externalData = new BABYLON.StringDictionary();
  27184. }
  27185. return this._externalData.add(key, data);
  27186. };
  27187. /**
  27188. * Get an externaly attached data from its key
  27189. * @param key the unique key that identifies the data
  27190. * @return the associated data, if present (can be null), or undefined if not present
  27191. */
  27192. Scene.prototype.getExternalData = function (key) {
  27193. if (!this._externalData) {
  27194. return null;
  27195. }
  27196. return this._externalData.get(key);
  27197. };
  27198. /**
  27199. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27200. * @param key the unique key that identifies the data
  27201. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27202. * @return the associated data, can be null if the factory returned null.
  27203. */
  27204. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27205. if (!this._externalData) {
  27206. this._externalData = new BABYLON.StringDictionary();
  27207. }
  27208. return this._externalData.getOrAddWithFactory(key, factory);
  27209. };
  27210. /**
  27211. * Remove an externaly attached data from the Engine instance
  27212. * @param key the unique key that identifies the data
  27213. * @return true if the data was successfully removed, false if it doesn't exist
  27214. */
  27215. Scene.prototype.removeExternalData = function (key) {
  27216. return this._externalData.remove(key);
  27217. };
  27218. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27219. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27220. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27221. var step = _a[_i];
  27222. step.action(mesh, subMesh);
  27223. }
  27224. var material = subMesh.getMaterial();
  27225. if (material !== null && material !== undefined) {
  27226. // Render targets
  27227. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27228. if (this._processedMaterials.indexOf(material) === -1) {
  27229. this._processedMaterials.push(material);
  27230. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27231. }
  27232. }
  27233. // Dispatch
  27234. this._activeIndices.addCount(subMesh.indexCount, false);
  27235. this._renderingManager.dispatch(subMesh, mesh, material);
  27236. }
  27237. }
  27238. };
  27239. /**
  27240. * Clear the processed materials smart array preventing retention point in material dispose.
  27241. */
  27242. Scene.prototype.freeProcessedMaterials = function () {
  27243. this._processedMaterials.dispose();
  27244. };
  27245. /**
  27246. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27247. */
  27248. Scene.prototype.freeActiveMeshes = function () {
  27249. this._activeMeshes.dispose();
  27250. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27251. this.activeCamera._activeMeshes.dispose();
  27252. }
  27253. if (this.activeCameras) {
  27254. for (var i = 0; i < this.activeCameras.length; i++) {
  27255. var activeCamera = this.activeCameras[i];
  27256. if (activeCamera && activeCamera._activeMeshes) {
  27257. activeCamera._activeMeshes.dispose();
  27258. }
  27259. }
  27260. }
  27261. };
  27262. /**
  27263. * Clear the info related to rendering groups preventing retention points during dispose.
  27264. */
  27265. Scene.prototype.freeRenderingGroups = function () {
  27266. if (this._renderingManager) {
  27267. this._renderingManager.freeRenderingGroups();
  27268. }
  27269. if (this.textures) {
  27270. for (var i = 0; i < this.textures.length; i++) {
  27271. var texture = this.textures[i];
  27272. if (texture && texture.renderList) {
  27273. texture.freeRenderingGroups();
  27274. }
  27275. }
  27276. }
  27277. };
  27278. /** @hidden */
  27279. Scene.prototype._isInIntermediateRendering = function () {
  27280. return this._intermediateRendering;
  27281. };
  27282. /**
  27283. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27284. * @returns the current scene
  27285. */
  27286. Scene.prototype.freezeActiveMeshes = function () {
  27287. if (!this.activeCamera) {
  27288. return this;
  27289. }
  27290. if (!this._frustumPlanes) {
  27291. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27292. }
  27293. this._evaluateActiveMeshes();
  27294. this._activeMeshesFrozen = true;
  27295. return this;
  27296. };
  27297. /**
  27298. * Use this function to restart evaluating active meshes on every frame
  27299. * @returns the current scene
  27300. */
  27301. Scene.prototype.unfreezeActiveMeshes = function () {
  27302. this._activeMeshesFrozen = false;
  27303. return this;
  27304. };
  27305. Scene.prototype._evaluateActiveMeshes = function () {
  27306. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27307. return;
  27308. }
  27309. if (!this.activeCamera) {
  27310. return;
  27311. }
  27312. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27313. this.activeCamera._activeMeshes.reset();
  27314. this._activeMeshes.reset();
  27315. this._renderingManager.reset();
  27316. this._processedMaterials.reset();
  27317. this._activeParticleSystems.reset();
  27318. this._activeSkeletons.reset();
  27319. this._softwareSkinnedMeshes.reset();
  27320. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27321. var step = _a[_i];
  27322. step.action();
  27323. }
  27324. // Determine mesh candidates
  27325. var meshes = this.getActiveMeshCandidates();
  27326. // Check each mesh
  27327. var len = meshes.length;
  27328. for (var i = 0; i < len; i++) {
  27329. var mesh = meshes.data[i];
  27330. if (mesh.isBlocked) {
  27331. continue;
  27332. }
  27333. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27334. if (!mesh.isReady() || !mesh.isEnabled()) {
  27335. continue;
  27336. }
  27337. mesh.computeWorldMatrix();
  27338. // Intersections
  27339. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27340. this._meshesForIntersections.pushNoDuplicate(mesh);
  27341. }
  27342. // Switch to current LOD
  27343. var meshLOD = mesh.getLOD(this.activeCamera);
  27344. if (meshLOD === undefined || meshLOD === null) {
  27345. continue;
  27346. }
  27347. mesh._preActivate();
  27348. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27349. this._activeMeshes.push(mesh);
  27350. this.activeCamera._activeMeshes.push(mesh);
  27351. mesh._activate(this._renderId);
  27352. if (meshLOD !== mesh) {
  27353. meshLOD._activate(this._renderId);
  27354. }
  27355. this._activeMesh(mesh, meshLOD);
  27356. }
  27357. }
  27358. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27359. // Particle systems
  27360. if (this.particlesEnabled) {
  27361. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27362. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27363. var particleSystem = this.particleSystems[particleIndex];
  27364. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27365. continue;
  27366. }
  27367. var emitter = particleSystem.emitter;
  27368. if (!emitter.position || emitter.isEnabled()) {
  27369. this._activeParticleSystems.push(particleSystem);
  27370. particleSystem.animate();
  27371. this._renderingManager.dispatchParticles(particleSystem);
  27372. }
  27373. }
  27374. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27375. }
  27376. };
  27377. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27378. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27379. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27380. mesh.skeleton.prepare();
  27381. }
  27382. if (!mesh.computeBonesUsingShaders) {
  27383. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27384. }
  27385. }
  27386. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27387. var step = _a[_i];
  27388. step.action(sourceMesh, mesh);
  27389. }
  27390. if (mesh !== undefined && mesh !== null
  27391. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27392. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  27393. var len = subMeshes.length;
  27394. for (var i = 0; i < len; i++) {
  27395. var subMesh = subMeshes.data[i];
  27396. this._evaluateSubMesh(subMesh, mesh);
  27397. }
  27398. }
  27399. };
  27400. /**
  27401. * Update the transform matrix to update from the current active camera
  27402. * @param force defines a boolean used to force the update even if cache is up to date
  27403. */
  27404. Scene.prototype.updateTransformMatrix = function (force) {
  27405. if (!this.activeCamera) {
  27406. return;
  27407. }
  27408. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27409. };
  27410. /**
  27411. * 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)
  27412. * @param alternateCamera defines the camera to use
  27413. */
  27414. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27415. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27416. };
  27417. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27418. if (camera && camera._skipRendering) {
  27419. return;
  27420. }
  27421. var engine = this._engine;
  27422. this.activeCamera = camera;
  27423. if (!this.activeCamera)
  27424. throw new Error("Active camera not set");
  27425. // Viewport
  27426. engine.setViewport(this.activeCamera.viewport);
  27427. // Camera
  27428. this.resetCachedMaterial();
  27429. this._renderId++;
  27430. this.updateTransformMatrix();
  27431. if (camera._alternateCamera) {
  27432. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27433. this._alternateRendering = true;
  27434. }
  27435. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27436. // Meshes
  27437. this._evaluateActiveMeshes();
  27438. // Software skinning
  27439. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27440. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27441. mesh.applySkeleton(mesh.skeleton);
  27442. }
  27443. // Render targets
  27444. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27445. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27446. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27447. }
  27448. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27449. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27450. }
  27451. // Collects render targets from external components.
  27452. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  27453. var step = _a[_i];
  27454. step.action(this._renderTargets);
  27455. }
  27456. if (this.renderTargetsEnabled) {
  27457. this._intermediateRendering = true;
  27458. if (this._renderTargets.length > 0) {
  27459. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27460. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27461. var renderTarget = this._renderTargets.data[renderIndex];
  27462. if (renderTarget._shouldRender()) {
  27463. this._renderId++;
  27464. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27465. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27466. }
  27467. }
  27468. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27469. this._renderId++;
  27470. }
  27471. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  27472. var step = _c[_b];
  27473. step.action(this.activeCamera);
  27474. }
  27475. this._intermediateRendering = false;
  27476. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27477. }
  27478. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27479. // Prepare Frame
  27480. if (this.postProcessManager) {
  27481. this.postProcessManager._prepareFrame();
  27482. }
  27483. // Before Camera Draw
  27484. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  27485. var step = _e[_d];
  27486. step.action(this.activeCamera);
  27487. }
  27488. // Render
  27489. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27490. this._renderingManager.render(null, null, true, true);
  27491. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27492. // After Camera Draw
  27493. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  27494. var step = _g[_f];
  27495. step.action(this.activeCamera);
  27496. }
  27497. // Finalize frame
  27498. if (this.postProcessManager) {
  27499. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27500. }
  27501. // Reset some special arrays
  27502. this._renderTargets.reset();
  27503. this._alternateRendering = false;
  27504. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27505. };
  27506. Scene.prototype._processSubCameras = function (camera) {
  27507. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27508. this._renderForCamera(camera);
  27509. return;
  27510. }
  27511. // rig cameras
  27512. for (var index = 0; index < camera._rigCameras.length; index++) {
  27513. this._renderForCamera(camera._rigCameras[index], camera);
  27514. }
  27515. this.activeCamera = camera;
  27516. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27517. };
  27518. Scene.prototype._checkIntersections = function () {
  27519. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27520. var sourceMesh = this._meshesForIntersections.data[index];
  27521. if (!sourceMesh.actionManager) {
  27522. continue;
  27523. }
  27524. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27525. var action = sourceMesh.actionManager.actions[actionIndex];
  27526. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27527. var parameters = action.getTriggerParameter();
  27528. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27529. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27530. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27531. if (areIntersecting && currentIntersectionInProgress === -1) {
  27532. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27533. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27534. sourceMesh._intersectionsInProgress.push(otherMesh);
  27535. }
  27536. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27537. sourceMesh._intersectionsInProgress.push(otherMesh);
  27538. }
  27539. }
  27540. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27541. //They intersected, and now they don't.
  27542. //is this trigger an exit trigger? execute an event.
  27543. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27544. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27545. }
  27546. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27547. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27548. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27549. return otherMesh === parameterMesh;
  27550. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27551. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27552. }
  27553. }
  27554. }
  27555. }
  27556. }
  27557. };
  27558. /** @hidden */
  27559. Scene.prototype._advancePhysicsEngineStep = function (step) {
  27560. // Do nothing. Code will be replaced if physics engine component is referenced
  27561. };
  27562. /**
  27563. * Render the scene
  27564. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27565. */
  27566. Scene.prototype.render = function (updateCameras) {
  27567. if (updateCameras === void 0) { updateCameras = true; }
  27568. if (this.isDisposed) {
  27569. return;
  27570. }
  27571. this._frameId++;
  27572. // Register components that have been associated lately to the scene.
  27573. this._registerTransientComponents();
  27574. this._activeParticles.fetchNewFrame();
  27575. this._totalVertices.fetchNewFrame();
  27576. this._activeIndices.fetchNewFrame();
  27577. this._activeBones.fetchNewFrame();
  27578. this._meshesForIntersections.reset();
  27579. this.resetCachedMaterial();
  27580. this.onBeforeAnimationsObservable.notifyObservers(this);
  27581. // Actions
  27582. if (this.actionManager) {
  27583. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27584. }
  27585. if (this._engine.isDeterministicLockStep()) {
  27586. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27587. var defaultFPS = (60.0 / 1000.0);
  27588. var defaultFrameTime = this.getDeterministicFrameTime();
  27589. var stepsTaken = 0;
  27590. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27591. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27592. internalSteps = Math.min(internalSteps, maxSubSteps);
  27593. do {
  27594. this.onBeforeStepObservable.notifyObservers(this);
  27595. // Animations
  27596. this._animationRatio = defaultFrameTime * defaultFPS;
  27597. this._animate();
  27598. this.onAfterAnimationsObservable.notifyObservers(this);
  27599. // Physics
  27600. this._advancePhysicsEngineStep(defaultFrameTime);
  27601. this.onAfterStepObservable.notifyObservers(this);
  27602. this._currentStepId++;
  27603. stepsTaken++;
  27604. deltaTime -= defaultFrameTime;
  27605. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27606. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27607. }
  27608. else {
  27609. // Animations
  27610. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27611. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27612. this._animate();
  27613. this.onAfterAnimationsObservable.notifyObservers(this);
  27614. // Physics
  27615. this._advancePhysicsEngineStep(deltaTime);
  27616. }
  27617. // Before camera update steps
  27618. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27619. var step = _a[_i];
  27620. step.action();
  27621. }
  27622. // Update Cameras
  27623. if (updateCameras) {
  27624. if (this.activeCameras.length > 0) {
  27625. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27626. var camera = this.activeCameras[cameraIndex];
  27627. camera.update();
  27628. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27629. // rig cameras
  27630. for (var index = 0; index < camera._rigCameras.length; index++) {
  27631. camera._rigCameras[index].update();
  27632. }
  27633. }
  27634. }
  27635. }
  27636. else if (this.activeCamera) {
  27637. this.activeCamera.update();
  27638. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27639. // rig cameras
  27640. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27641. this.activeCamera._rigCameras[index].update();
  27642. }
  27643. }
  27644. }
  27645. }
  27646. // Before render
  27647. this.onBeforeRenderObservable.notifyObservers(this);
  27648. // Customs render targets
  27649. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27650. var engine = this.getEngine();
  27651. var currentActiveCamera = this.activeCamera;
  27652. if (this.renderTargetsEnabled) {
  27653. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27654. this._intermediateRendering = true;
  27655. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27656. var renderTarget = this.customRenderTargets[customIndex];
  27657. if (renderTarget._shouldRender()) {
  27658. this._renderId++;
  27659. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27660. if (!this.activeCamera)
  27661. throw new Error("Active camera not set");
  27662. // Viewport
  27663. engine.setViewport(this.activeCamera.viewport);
  27664. // Camera
  27665. this.updateTransformMatrix();
  27666. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27667. }
  27668. }
  27669. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27670. this._intermediateRendering = false;
  27671. this._renderId++;
  27672. }
  27673. // Restore back buffer
  27674. if (this.customRenderTargets.length > 0) {
  27675. engine.restoreDefaultFramebuffer();
  27676. }
  27677. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27678. this.activeCamera = currentActiveCamera;
  27679. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  27680. var step = _c[_b];
  27681. step.action();
  27682. }
  27683. // Clear
  27684. if (this.autoClearDepthAndStencil || this.autoClear) {
  27685. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27686. }
  27687. // Collects render targets from external components.
  27688. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  27689. var step = _e[_d];
  27690. step.action(this._renderTargets);
  27691. }
  27692. // Multi-cameras?
  27693. if (this.activeCameras.length > 0) {
  27694. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27695. if (cameraIndex > 0) {
  27696. this._engine.clear(null, false, true, true);
  27697. }
  27698. this._processSubCameras(this.activeCameras[cameraIndex]);
  27699. }
  27700. }
  27701. else {
  27702. if (!this.activeCamera) {
  27703. throw new Error("No camera defined");
  27704. }
  27705. this._processSubCameras(this.activeCamera);
  27706. }
  27707. // Intersection checks
  27708. this._checkIntersections();
  27709. // Executes the after render stage actions.
  27710. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  27711. var step = _g[_f];
  27712. step.action();
  27713. }
  27714. // After render
  27715. if (this.afterRender) {
  27716. this.afterRender();
  27717. }
  27718. this.onAfterRenderObservable.notifyObservers(this);
  27719. // Cleaning
  27720. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27721. var data = this._toBeDisposed.data[index];
  27722. if (data) {
  27723. data.dispose();
  27724. }
  27725. }
  27726. this._toBeDisposed.reset();
  27727. if (this.dumpNextRenderTargets) {
  27728. this.dumpNextRenderTargets = false;
  27729. }
  27730. this._activeBones.addCount(0, true);
  27731. this._activeIndices.addCount(0, true);
  27732. this._activeParticles.addCount(0, true);
  27733. };
  27734. /**
  27735. * Freeze all materials
  27736. * A frozen material will not be updatable but should be faster to render
  27737. */
  27738. Scene.prototype.freezeMaterials = function () {
  27739. for (var i = 0; i < this.materials.length; i++) {
  27740. this.materials[i].freeze();
  27741. }
  27742. };
  27743. /**
  27744. * Unfreeze all materials
  27745. * A frozen material will not be updatable but should be faster to render
  27746. */
  27747. Scene.prototype.unfreezeMaterials = function () {
  27748. for (var i = 0; i < this.materials.length; i++) {
  27749. this.materials[i].unfreeze();
  27750. }
  27751. };
  27752. /**
  27753. * Releases all held ressources
  27754. */
  27755. Scene.prototype.dispose = function () {
  27756. this.beforeRender = null;
  27757. this.afterRender = null;
  27758. this.skeletons = [];
  27759. this.morphTargetManagers = [];
  27760. this._transientComponents = [];
  27761. this._isReadyForMeshStage.clear();
  27762. this._beforeEvaluateActiveMeshStage.clear();
  27763. this._evaluateSubMeshStage.clear();
  27764. this._activeMeshStage.clear();
  27765. this._cameraDrawRenderTargetStage.clear();
  27766. this._beforeCameraDrawStage.clear();
  27767. this._beforeRenderingGroupDrawStage.clear();
  27768. this._beforeRenderingMeshStage.clear();
  27769. this._afterRenderingMeshStage.clear();
  27770. this._afterRenderingGroupDrawStage.clear();
  27771. this._afterCameraDrawStage.clear();
  27772. this._afterRenderStage.clear();
  27773. this._beforeCameraUpdateStage.clear();
  27774. this._beforeClearStage.clear();
  27775. this._gatherRenderTargetsStage.clear();
  27776. this._gatherActiveCameraRenderTargetsStage.clear();
  27777. this._pointerMoveStage.clear();
  27778. this._pointerDownStage.clear();
  27779. this._pointerUpStage.clear();
  27780. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27781. var component = _a[_i];
  27782. component.dispose();
  27783. }
  27784. this.importedMeshesFiles = new Array();
  27785. this.stopAllAnimations();
  27786. this.resetCachedMaterial();
  27787. // Smart arrays
  27788. if (this.activeCamera) {
  27789. this.activeCamera._activeMeshes.dispose();
  27790. this.activeCamera = null;
  27791. }
  27792. this._activeMeshes.dispose();
  27793. this._renderingManager.dispose();
  27794. this._processedMaterials.dispose();
  27795. this._activeParticleSystems.dispose();
  27796. this._activeSkeletons.dispose();
  27797. this._softwareSkinnedMeshes.dispose();
  27798. this._renderTargets.dispose();
  27799. this._registeredForLateAnimationBindings.dispose();
  27800. this._meshesForIntersections.dispose();
  27801. this._toBeDisposed.dispose();
  27802. // Abort active requests
  27803. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  27804. var request = _c[_b];
  27805. request.abort();
  27806. }
  27807. // Events
  27808. this.onDisposeObservable.notifyObservers(this);
  27809. this.onDisposeObservable.clear();
  27810. this.onBeforeRenderObservable.clear();
  27811. this.onAfterRenderObservable.clear();
  27812. this.onBeforeRenderTargetsRenderObservable.clear();
  27813. this.onAfterRenderTargetsRenderObservable.clear();
  27814. this.onAfterStepObservable.clear();
  27815. this.onBeforeStepObservable.clear();
  27816. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27817. this.onAfterActiveMeshesEvaluationObservable.clear();
  27818. this.onBeforeParticlesRenderingObservable.clear();
  27819. this.onAfterParticlesRenderingObservable.clear();
  27820. this.onBeforeDrawPhaseObservable.clear();
  27821. this.onAfterDrawPhaseObservable.clear();
  27822. this.onBeforeAnimationsObservable.clear();
  27823. this.onAfterAnimationsObservable.clear();
  27824. this.onDataLoadedObservable.clear();
  27825. this.onBeforeRenderingGroupObservable.clear();
  27826. this.onAfterRenderingGroupObservable.clear();
  27827. this.onMeshImportedObservable.clear();
  27828. this.detachControl();
  27829. // Detach cameras
  27830. var canvas = this._engine.getRenderingCanvas();
  27831. if (canvas) {
  27832. var index;
  27833. for (index = 0; index < this.cameras.length; index++) {
  27834. this.cameras[index].detachControl(canvas);
  27835. }
  27836. }
  27837. // Release animation groups
  27838. while (this.animationGroups.length) {
  27839. this.animationGroups[0].dispose();
  27840. }
  27841. // Release lights
  27842. while (this.lights.length) {
  27843. this.lights[0].dispose();
  27844. }
  27845. // Release meshes
  27846. while (this.meshes.length) {
  27847. this.meshes[0].dispose(true);
  27848. }
  27849. while (this.transformNodes.length) {
  27850. this.removeTransformNode(this.transformNodes[0]);
  27851. }
  27852. // Release cameras
  27853. while (this.cameras.length) {
  27854. this.cameras[0].dispose();
  27855. }
  27856. // Release materials
  27857. if (this.defaultMaterial) {
  27858. this.defaultMaterial.dispose();
  27859. }
  27860. while (this.multiMaterials.length) {
  27861. this.multiMaterials[0].dispose();
  27862. }
  27863. while (this.materials.length) {
  27864. this.materials[0].dispose();
  27865. }
  27866. // Release particles
  27867. while (this.particleSystems.length) {
  27868. this.particleSystems[0].dispose();
  27869. }
  27870. // Release postProcesses
  27871. while (this.postProcesses.length) {
  27872. this.postProcesses[0].dispose();
  27873. }
  27874. // Release textures
  27875. while (this.textures.length) {
  27876. this.textures[0].dispose();
  27877. }
  27878. // Release UBO
  27879. this._sceneUbo.dispose();
  27880. if (this._alternateSceneUbo) {
  27881. this._alternateSceneUbo.dispose();
  27882. }
  27883. // Post-processes
  27884. this.postProcessManager.dispose();
  27885. // Remove from engine
  27886. index = this._engine.scenes.indexOf(this);
  27887. if (index > -1) {
  27888. this._engine.scenes.splice(index, 1);
  27889. }
  27890. this._engine.wipeCaches(true);
  27891. this._isDisposed = true;
  27892. };
  27893. Object.defineProperty(Scene.prototype, "isDisposed", {
  27894. /**
  27895. * Gets if the scene is already disposed
  27896. */
  27897. get: function () {
  27898. return this._isDisposed;
  27899. },
  27900. enumerable: true,
  27901. configurable: true
  27902. });
  27903. /**
  27904. * Call this function to reduce memory footprint of the scene.
  27905. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  27906. */
  27907. Scene.prototype.clearCachedVertexData = function () {
  27908. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27909. var mesh = this.meshes[meshIndex];
  27910. var geometry = mesh.geometry;
  27911. if (geometry) {
  27912. geometry._indices = [];
  27913. for (var vbName in geometry._vertexBuffers) {
  27914. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  27915. continue;
  27916. }
  27917. geometry._vertexBuffers[vbName]._buffer._data = null;
  27918. }
  27919. }
  27920. }
  27921. };
  27922. /**
  27923. * This function will remove the local cached buffer data from texture.
  27924. * It will save memory but will prevent the texture from being rebuilt
  27925. */
  27926. Scene.prototype.cleanCachedTextureBuffer = function () {
  27927. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  27928. var baseTexture = _a[_i];
  27929. var buffer = baseTexture._buffer;
  27930. if (buffer) {
  27931. baseTexture._buffer = null;
  27932. }
  27933. }
  27934. };
  27935. /**
  27936. * Get the world extend vectors with an optional filter
  27937. *
  27938. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27939. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27940. */
  27941. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27942. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27943. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27944. filterPredicate = filterPredicate || (function () { return true; });
  27945. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27946. mesh.computeWorldMatrix(true);
  27947. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  27948. return;
  27949. }
  27950. var boundingInfo = mesh.getBoundingInfo();
  27951. var minBox = boundingInfo.boundingBox.minimumWorld;
  27952. var maxBox = boundingInfo.boundingBox.maximumWorld;
  27953. BABYLON.Tools.CheckExtends(minBox, min, max);
  27954. BABYLON.Tools.CheckExtends(maxBox, min, max);
  27955. });
  27956. return {
  27957. min: min,
  27958. max: max
  27959. };
  27960. };
  27961. // Picking
  27962. /**
  27963. * Creates a ray that can be used to pick in the scene
  27964. * @param x defines the x coordinate of the origin (on-screen)
  27965. * @param y defines the y coordinate of the origin (on-screen)
  27966. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27967. * @param camera defines the camera to use for the picking
  27968. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27969. * @returns a Ray
  27970. */
  27971. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  27972. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27973. var result = BABYLON.Ray.Zero();
  27974. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  27975. return result;
  27976. };
  27977. /**
  27978. * Creates a ray that can be used to pick in the scene
  27979. * @param x defines the x coordinate of the origin (on-screen)
  27980. * @param y defines the y coordinate of the origin (on-screen)
  27981. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27982. * @param result defines the ray where to store the picking ray
  27983. * @param camera defines the camera to use for the picking
  27984. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27985. * @returns the current scene
  27986. */
  27987. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  27988. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27989. var engine = this._engine;
  27990. if (!camera) {
  27991. if (!this.activeCamera)
  27992. throw new Error("Active camera not set");
  27993. camera = this.activeCamera;
  27994. }
  27995. var cameraViewport = camera.viewport;
  27996. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27997. // Moving coordinates to local viewport world
  27998. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27999. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28000. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28001. return this;
  28002. };
  28003. /**
  28004. * Creates a ray that can be used to pick in the scene
  28005. * @param x defines the x coordinate of the origin (on-screen)
  28006. * @param y defines the y coordinate of the origin (on-screen)
  28007. * @param camera defines the camera to use for the picking
  28008. * @returns a Ray
  28009. */
  28010. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28011. var result = BABYLON.Ray.Zero();
  28012. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28013. return result;
  28014. };
  28015. /**
  28016. * Creates a ray that can be used to pick in the scene
  28017. * @param x defines the x coordinate of the origin (on-screen)
  28018. * @param y defines the y coordinate of the origin (on-screen)
  28019. * @param result defines the ray where to store the picking ray
  28020. * @param camera defines the camera to use for the picking
  28021. * @returns the current scene
  28022. */
  28023. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28024. if (!BABYLON.PickingInfo) {
  28025. return this;
  28026. }
  28027. var engine = this._engine;
  28028. if (!camera) {
  28029. if (!this.activeCamera)
  28030. throw new Error("Active camera not set");
  28031. camera = this.activeCamera;
  28032. }
  28033. var cameraViewport = camera.viewport;
  28034. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28035. var identity = BABYLON.Matrix.Identity();
  28036. // Moving coordinates to local viewport world
  28037. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28038. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28039. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28040. return this;
  28041. };
  28042. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28043. if (!BABYLON.PickingInfo) {
  28044. return null;
  28045. }
  28046. var pickingInfo = null;
  28047. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28048. var mesh = this.meshes[meshIndex];
  28049. if (predicate) {
  28050. if (!predicate(mesh)) {
  28051. continue;
  28052. }
  28053. }
  28054. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28055. continue;
  28056. }
  28057. var world = mesh.getWorldMatrix();
  28058. var ray = rayFunction(world);
  28059. var result = mesh.intersects(ray, fastCheck);
  28060. if (!result || !result.hit)
  28061. continue;
  28062. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28063. continue;
  28064. pickingInfo = result;
  28065. if (fastCheck) {
  28066. break;
  28067. }
  28068. }
  28069. return pickingInfo || new BABYLON.PickingInfo();
  28070. };
  28071. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28072. if (!BABYLON.PickingInfo) {
  28073. return null;
  28074. }
  28075. var pickingInfos = new Array();
  28076. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28077. var mesh = this.meshes[meshIndex];
  28078. if (predicate) {
  28079. if (!predicate(mesh)) {
  28080. continue;
  28081. }
  28082. }
  28083. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28084. continue;
  28085. }
  28086. var world = mesh.getWorldMatrix();
  28087. var ray = rayFunction(world);
  28088. var result = mesh.intersects(ray, false);
  28089. if (!result || !result.hit)
  28090. continue;
  28091. pickingInfos.push(result);
  28092. }
  28093. return pickingInfos;
  28094. };
  28095. /** Launch a ray to try to pick a mesh in the scene
  28096. * @param x position on screen
  28097. * @param y position on screen
  28098. * @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
  28099. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28100. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28101. * @returns a PickingInfo
  28102. */
  28103. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28104. var _this = this;
  28105. if (!BABYLON.PickingInfo) {
  28106. return null;
  28107. }
  28108. var result = this._internalPick(function (world) {
  28109. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28110. return _this._tempPickingRay;
  28111. }, predicate, fastCheck);
  28112. if (result) {
  28113. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28114. }
  28115. return result;
  28116. };
  28117. /** Use the given ray to pick a mesh in the scene
  28118. * @param ray The ray to use to pick meshes
  28119. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true
  28120. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28121. * @returns a PickingInfo
  28122. */
  28123. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28124. var _this = this;
  28125. var result = this._internalPick(function (world) {
  28126. if (!_this._pickWithRayInverseMatrix) {
  28127. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28128. }
  28129. world.invertToRef(_this._pickWithRayInverseMatrix);
  28130. if (!_this._cachedRayForTransform) {
  28131. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28132. }
  28133. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28134. return _this._cachedRayForTransform;
  28135. }, predicate, fastCheck);
  28136. if (result) {
  28137. result.ray = ray;
  28138. }
  28139. return result;
  28140. };
  28141. /**
  28142. * Launch a ray to try to pick a mesh in the scene
  28143. * @param x X position on screen
  28144. * @param y Y position on screen
  28145. * @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
  28146. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28147. * @returns an array of PickingInfo
  28148. */
  28149. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28150. var _this = this;
  28151. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28152. };
  28153. /**
  28154. * Launch a ray to try to pick a mesh in the scene
  28155. * @param ray Ray to use
  28156. * @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
  28157. * @returns an array of PickingInfo
  28158. */
  28159. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28160. var _this = this;
  28161. return this._internalMultiPick(function (world) {
  28162. if (!_this._pickWithRayInverseMatrix) {
  28163. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28164. }
  28165. world.invertToRef(_this._pickWithRayInverseMatrix);
  28166. if (!_this._cachedRayForTransform) {
  28167. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28168. }
  28169. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28170. return _this._cachedRayForTransform;
  28171. }, predicate);
  28172. };
  28173. /**
  28174. * Force the value of meshUnderPointer
  28175. * @param mesh defines the mesh to use
  28176. */
  28177. Scene.prototype.setPointerOverMesh = function (mesh) {
  28178. if (this._pointerOverMesh === mesh) {
  28179. return;
  28180. }
  28181. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28182. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28183. }
  28184. this._pointerOverMesh = mesh;
  28185. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28186. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28187. }
  28188. };
  28189. /**
  28190. * Gets the mesh under the pointer
  28191. * @returns a Mesh or null if no mesh is under the pointer
  28192. */
  28193. Scene.prototype.getPointerOverMesh = function () {
  28194. return this._pointerOverMesh;
  28195. };
  28196. // Misc.
  28197. /** @hidden */
  28198. Scene.prototype._rebuildGeometries = function () {
  28199. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28200. var geometry = _a[_i];
  28201. geometry._rebuild();
  28202. }
  28203. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28204. var mesh = _c[_b];
  28205. mesh._rebuild();
  28206. }
  28207. if (this.postProcessManager) {
  28208. this.postProcessManager._rebuild();
  28209. }
  28210. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28211. var component = _e[_d];
  28212. component.rebuild();
  28213. }
  28214. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28215. var system = _g[_f];
  28216. system.rebuild();
  28217. }
  28218. };
  28219. /** @hidden */
  28220. Scene.prototype._rebuildTextures = function () {
  28221. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28222. var texture = _a[_i];
  28223. texture._rebuild();
  28224. }
  28225. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28226. };
  28227. // Tags
  28228. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28229. if (tagsQuery === undefined) {
  28230. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28231. return list;
  28232. }
  28233. var listByTags = [];
  28234. forEach = forEach || (function (item) { return; });
  28235. for (var i in list) {
  28236. var item = list[i];
  28237. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28238. listByTags.push(item);
  28239. forEach(item);
  28240. }
  28241. }
  28242. return listByTags;
  28243. };
  28244. /**
  28245. * Get a list of meshes by tags
  28246. * @param tagsQuery defines the tags query to use
  28247. * @param forEach defines a predicate used to filter results
  28248. * @returns an array of Mesh
  28249. */
  28250. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28251. return this._getByTags(this.meshes, tagsQuery, forEach);
  28252. };
  28253. /**
  28254. * Get a list of cameras by tags
  28255. * @param tagsQuery defines the tags query to use
  28256. * @param forEach defines a predicate used to filter results
  28257. * @returns an array of Camera
  28258. */
  28259. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28260. return this._getByTags(this.cameras, tagsQuery, forEach);
  28261. };
  28262. /**
  28263. * Get a list of lights by tags
  28264. * @param tagsQuery defines the tags query to use
  28265. * @param forEach defines a predicate used to filter results
  28266. * @returns an array of Light
  28267. */
  28268. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28269. return this._getByTags(this.lights, tagsQuery, forEach);
  28270. };
  28271. /**
  28272. * Get a list of materials by tags
  28273. * @param tagsQuery defines the tags query to use
  28274. * @param forEach defines a predicate used to filter results
  28275. * @returns an array of Material
  28276. */
  28277. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28278. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28279. };
  28280. /**
  28281. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28282. * This allowed control for front to back rendering or reversly depending of the special needs.
  28283. *
  28284. * @param renderingGroupId The rendering group id corresponding to its index
  28285. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28286. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28287. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28288. */
  28289. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28290. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28291. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28292. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28293. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28294. };
  28295. /**
  28296. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28297. *
  28298. * @param renderingGroupId The rendering group id corresponding to its index
  28299. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28300. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28301. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28302. */
  28303. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28304. if (depth === void 0) { depth = true; }
  28305. if (stencil === void 0) { stencil = true; }
  28306. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28307. };
  28308. /**
  28309. * Gets the current auto clear configuration for one rendering group of the rendering
  28310. * manager.
  28311. * @param index the rendering group index to get the information for
  28312. * @returns The auto clear setup for the requested rendering group
  28313. */
  28314. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28315. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28316. };
  28317. /**
  28318. * Will flag all materials as dirty to trigger new shader compilation
  28319. * @param flag defines the flag used to specify which material part must be marked as dirty
  28320. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28321. */
  28322. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28323. if (this.blockMaterialDirtyMechanism) {
  28324. return;
  28325. }
  28326. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28327. var material = _a[_i];
  28328. if (predicate && !predicate(material)) {
  28329. continue;
  28330. }
  28331. material.markAsDirty(flag);
  28332. }
  28333. };
  28334. /** @hidden */
  28335. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28336. var _this = this;
  28337. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28338. this._activeRequests.push(request);
  28339. request.onCompleteObservable.add(function (request) {
  28340. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28341. });
  28342. return request;
  28343. };
  28344. /** @hidden */
  28345. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28346. var _this = this;
  28347. return new Promise(function (resolve, reject) {
  28348. _this._loadFile(url, function (data) {
  28349. resolve(data);
  28350. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28351. reject(exception);
  28352. });
  28353. });
  28354. };
  28355. // Statics
  28356. Scene._uniqueIdCounter = 0;
  28357. /** The fog is deactivated */
  28358. Scene.FOGMODE_NONE = 0;
  28359. /** The fog density is following an exponential function */
  28360. Scene.FOGMODE_EXP = 1;
  28361. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28362. Scene.FOGMODE_EXP2 = 2;
  28363. /** The fog density is following a linear function. */
  28364. Scene.FOGMODE_LINEAR = 3;
  28365. /**
  28366. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28367. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28368. */
  28369. Scene.MinDeltaTime = 1.0;
  28370. /**
  28371. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28372. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28373. */
  28374. Scene.MaxDeltaTime = 1000.0;
  28375. /** The distance in pixel that you have to move to prevent some events */
  28376. Scene.DragMovementThreshold = 10; // in pixels
  28377. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28378. Scene.LongPressDelay = 500; // in milliseconds
  28379. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28380. Scene.DoubleClickDelay = 300; // in milliseconds
  28381. /** If you need to check double click without raising a single click at first click, enable this flag */
  28382. Scene.ExclusiveDoubleClickMode = false;
  28383. return Scene;
  28384. }(BABYLON.AbstractScene));
  28385. BABYLON.Scene = Scene;
  28386. })(BABYLON || (BABYLON = {}));
  28387. //# sourceMappingURL=babylon.scene.js.map
  28388. var BABYLON;
  28389. (function (BABYLON) {
  28390. /**
  28391. * Set of assets to keep when moving a scene into an asset container.
  28392. */
  28393. var KeepAssets = /** @class */ (function (_super) {
  28394. __extends(KeepAssets, _super);
  28395. function KeepAssets() {
  28396. return _super !== null && _super.apply(this, arguments) || this;
  28397. }
  28398. return KeepAssets;
  28399. }(BABYLON.AbstractScene));
  28400. BABYLON.KeepAssets = KeepAssets;
  28401. /**
  28402. * Container with a set of assets that can be added or removed from a scene.
  28403. */
  28404. var AssetContainer = /** @class */ (function (_super) {
  28405. __extends(AssetContainer, _super);
  28406. /**
  28407. * Instantiates an AssetContainer.
  28408. * @param scene The scene the AssetContainer belongs to.
  28409. */
  28410. function AssetContainer(scene) {
  28411. var _this = _super.call(this) || this;
  28412. _this.scene = scene;
  28413. return _this;
  28414. }
  28415. /**
  28416. * Adds all the assets from the container to the scene.
  28417. */
  28418. AssetContainer.prototype.addAllToScene = function () {
  28419. var _this = this;
  28420. this.cameras.forEach(function (o) {
  28421. _this.scene.addCamera(o);
  28422. });
  28423. this.lights.forEach(function (o) {
  28424. _this.scene.addLight(o);
  28425. });
  28426. this.meshes.forEach(function (o) {
  28427. _this.scene.addMesh(o);
  28428. });
  28429. this.skeletons.forEach(function (o) {
  28430. _this.scene.addSkeleton(o);
  28431. });
  28432. this.animations.forEach(function (o) {
  28433. _this.scene.addAnimation(o);
  28434. });
  28435. this.animationGroups.forEach(function (o) {
  28436. _this.scene.addAnimationGroup(o);
  28437. });
  28438. this.multiMaterials.forEach(function (o) {
  28439. _this.scene.addMultiMaterial(o);
  28440. });
  28441. this.materials.forEach(function (o) {
  28442. _this.scene.addMaterial(o);
  28443. });
  28444. this.morphTargetManagers.forEach(function (o) {
  28445. _this.scene.addMorphTargetManager(o);
  28446. });
  28447. this.geometries.forEach(function (o) {
  28448. _this.scene.addGeometry(o);
  28449. });
  28450. this.transformNodes.forEach(function (o) {
  28451. _this.scene.addTransformNode(o);
  28452. });
  28453. this.actionManagers.forEach(function (o) {
  28454. _this.scene.addActionManager(o);
  28455. });
  28456. this.textures.forEach(function (o) {
  28457. _this.scene.addTexture(o);
  28458. });
  28459. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28460. var component = _a[_i];
  28461. component.addFromContainer(this.scene);
  28462. }
  28463. };
  28464. /**
  28465. * Removes all the assets in the container from the scene
  28466. */
  28467. AssetContainer.prototype.removeAllFromScene = function () {
  28468. var _this = this;
  28469. this.cameras.forEach(function (o) {
  28470. _this.scene.removeCamera(o);
  28471. });
  28472. this.lights.forEach(function (o) {
  28473. _this.scene.removeLight(o);
  28474. });
  28475. this.meshes.forEach(function (o) {
  28476. _this.scene.removeMesh(o);
  28477. });
  28478. this.skeletons.forEach(function (o) {
  28479. _this.scene.removeSkeleton(o);
  28480. });
  28481. this.animations.forEach(function (o) {
  28482. _this.scene.removeAnimation(o);
  28483. });
  28484. this.animationGroups.forEach(function (o) {
  28485. _this.scene.removeAnimationGroup(o);
  28486. });
  28487. this.multiMaterials.forEach(function (o) {
  28488. _this.scene.removeMultiMaterial(o);
  28489. });
  28490. this.materials.forEach(function (o) {
  28491. _this.scene.removeMaterial(o);
  28492. });
  28493. this.morphTargetManagers.forEach(function (o) {
  28494. _this.scene.removeMorphTargetManager(o);
  28495. });
  28496. this.geometries.forEach(function (o) {
  28497. _this.scene.removeGeometry(o);
  28498. });
  28499. this.transformNodes.forEach(function (o) {
  28500. _this.scene.removeTransformNode(o);
  28501. });
  28502. this.actionManagers.forEach(function (o) {
  28503. _this.scene.removeActionManager(o);
  28504. });
  28505. this.textures.forEach(function (o) {
  28506. _this.scene.removeTexture(o);
  28507. });
  28508. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28509. var component = _a[_i];
  28510. component.removeFromContainer(this.scene);
  28511. }
  28512. };
  28513. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28514. if (!sourceAssets) {
  28515. return;
  28516. }
  28517. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28518. var asset = sourceAssets_1[_i];
  28519. var move = true;
  28520. if (keepAssets) {
  28521. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28522. var keepAsset = keepAssets_1[_a];
  28523. if (asset === keepAsset) {
  28524. move = false;
  28525. break;
  28526. }
  28527. }
  28528. }
  28529. if (move) {
  28530. targetAssets.push(asset);
  28531. }
  28532. }
  28533. };
  28534. /**
  28535. * Removes all the assets contained in the scene and adds them to the container.
  28536. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28537. */
  28538. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28539. if (keepAssets === undefined) {
  28540. keepAssets = new KeepAssets();
  28541. }
  28542. for (var key in this) {
  28543. if (this.hasOwnProperty(key)) {
  28544. this[key] = this[key] || [];
  28545. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28546. }
  28547. }
  28548. this.removeAllFromScene();
  28549. };
  28550. /**
  28551. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  28552. * @returns the root mesh
  28553. */
  28554. AssetContainer.prototype.createRootMesh = function () {
  28555. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  28556. this.meshes.forEach(function (m) {
  28557. if (!m.parent) {
  28558. rootMesh.addChild(m);
  28559. }
  28560. });
  28561. this.meshes.unshift(rootMesh);
  28562. return rootMesh;
  28563. };
  28564. return AssetContainer;
  28565. }(BABYLON.AbstractScene));
  28566. BABYLON.AssetContainer = AssetContainer;
  28567. })(BABYLON || (BABYLON = {}));
  28568. //# sourceMappingURL=babylon.assetContainer.js.map
  28569. var BABYLON;
  28570. (function (BABYLON) {
  28571. var Buffer = /** @class */ (function () {
  28572. /**
  28573. * Constructor
  28574. * @param engine the engine
  28575. * @param data the data to use for this buffer
  28576. * @param updatable whether the data is updatable
  28577. * @param stride the stride (optional)
  28578. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28579. * @param instanced whether the buffer is instanced (optional)
  28580. * @param useBytes set to true if the stride in in bytes (optional)
  28581. */
  28582. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28583. if (stride === void 0) { stride = 0; }
  28584. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28585. if (instanced === void 0) { instanced = false; }
  28586. if (useBytes === void 0) { useBytes = false; }
  28587. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28588. this._engine = engine.getScene().getEngine();
  28589. }
  28590. else {
  28591. this._engine = engine;
  28592. }
  28593. this._updatable = updatable;
  28594. this._instanced = instanced;
  28595. this._data = data;
  28596. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28597. if (!postponeInternalCreation) { // by default
  28598. this.create();
  28599. }
  28600. }
  28601. /**
  28602. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28603. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28604. * @param offset defines offset in the buffer (0 by default)
  28605. * @param size defines the size in floats of attributes (position is 3 for instance)
  28606. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28607. * @param instanced defines if the vertex buffer contains indexed data
  28608. * @param useBytes defines if the offset and stride are in bytes
  28609. * @returns the new vertex buffer
  28610. */
  28611. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28612. if (useBytes === void 0) { useBytes = false; }
  28613. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28614. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28615. // a lot of these parameters are ignored as they are overriden by the buffer
  28616. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28617. };
  28618. // Properties
  28619. Buffer.prototype.isUpdatable = function () {
  28620. return this._updatable;
  28621. };
  28622. Buffer.prototype.getData = function () {
  28623. return this._data;
  28624. };
  28625. Buffer.prototype.getBuffer = function () {
  28626. return this._buffer;
  28627. };
  28628. /**
  28629. * Gets the stride in float32 units (i.e. byte stride / 4).
  28630. * May not be an integer if the byte stride is not divisible by 4.
  28631. * DEPRECATED. Use byteStride instead.
  28632. * @returns the stride in float32 units
  28633. */
  28634. Buffer.prototype.getStrideSize = function () {
  28635. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28636. };
  28637. // Methods
  28638. Buffer.prototype.create = function (data) {
  28639. if (data === void 0) { data = null; }
  28640. if (!data && this._buffer) {
  28641. return; // nothing to do
  28642. }
  28643. data = data || this._data;
  28644. if (!data) {
  28645. return;
  28646. }
  28647. if (!this._buffer) { // create buffer
  28648. if (this._updatable) {
  28649. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28650. this._data = data;
  28651. }
  28652. else {
  28653. this._buffer = this._engine.createVertexBuffer(data);
  28654. }
  28655. }
  28656. else if (this._updatable) { // update buffer
  28657. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28658. this._data = data;
  28659. }
  28660. };
  28661. /** @hidden */
  28662. Buffer.prototype._rebuild = function () {
  28663. this._buffer = null;
  28664. this.create(this._data);
  28665. };
  28666. Buffer.prototype.update = function (data) {
  28667. this.create(data);
  28668. };
  28669. /**
  28670. * Updates the data directly.
  28671. * @param data the new data
  28672. * @param offset the new offset
  28673. * @param vertexCount the vertex count (optional)
  28674. * @param useBytes set to true if the offset is in bytes
  28675. */
  28676. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28677. if (useBytes === void 0) { useBytes = false; }
  28678. if (!this._buffer) {
  28679. return;
  28680. }
  28681. if (this._updatable) { // update buffer
  28682. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  28683. this._data = null;
  28684. }
  28685. };
  28686. Buffer.prototype.dispose = function () {
  28687. if (!this._buffer) {
  28688. return;
  28689. }
  28690. if (this._engine._releaseBuffer(this._buffer)) {
  28691. this._buffer = null;
  28692. }
  28693. };
  28694. return Buffer;
  28695. }());
  28696. BABYLON.Buffer = Buffer;
  28697. })(BABYLON || (BABYLON = {}));
  28698. //# sourceMappingURL=babylon.buffer.js.map
  28699. var BABYLON;
  28700. (function (BABYLON) {
  28701. var VertexBuffer = /** @class */ (function () {
  28702. /**
  28703. * Constructor
  28704. * @param engine the engine
  28705. * @param data the data to use for this vertex buffer
  28706. * @param kind the vertex buffer kind
  28707. * @param updatable whether the data is updatable
  28708. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28709. * @param stride the stride (optional)
  28710. * @param instanced whether the buffer is instanced (optional)
  28711. * @param offset the offset of the data (optional)
  28712. * @param size the number of components (optional)
  28713. * @param type the type of the component (optional)
  28714. * @param normalized whether the data contains normalized data (optional)
  28715. * @param useBytes set to true if stride and offset are in bytes (optional)
  28716. */
  28717. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28718. if (normalized === void 0) { normalized = false; }
  28719. if (useBytes === void 0) { useBytes = false; }
  28720. if (data instanceof BABYLON.Buffer) {
  28721. this._buffer = data;
  28722. this._ownsBuffer = false;
  28723. }
  28724. else {
  28725. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28726. this._ownsBuffer = true;
  28727. }
  28728. this._kind = kind;
  28729. if (type == undefined) {
  28730. var data_1 = this.getData();
  28731. this.type = VertexBuffer.FLOAT;
  28732. if (data_1 instanceof Int8Array)
  28733. this.type = VertexBuffer.BYTE;
  28734. else if (data_1 instanceof Uint8Array)
  28735. this.type = VertexBuffer.UNSIGNED_BYTE;
  28736. else if (data_1 instanceof Int16Array)
  28737. this.type = VertexBuffer.SHORT;
  28738. else if (data_1 instanceof Uint16Array)
  28739. this.type = VertexBuffer.UNSIGNED_SHORT;
  28740. else if (data_1 instanceof Int32Array)
  28741. this.type = VertexBuffer.INT;
  28742. else if (data_1 instanceof Uint32Array)
  28743. this.type = VertexBuffer.UNSIGNED_INT;
  28744. }
  28745. else {
  28746. this.type = type;
  28747. }
  28748. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  28749. if (useBytes) {
  28750. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  28751. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  28752. this.byteOffset = offset || 0;
  28753. }
  28754. else {
  28755. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  28756. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  28757. this.byteOffset = (offset || 0) * typeByteLength;
  28758. }
  28759. this.normalized = normalized;
  28760. this._instanced = instanced !== undefined ? instanced : false;
  28761. this._instanceDivisor = instanced ? 1 : 0;
  28762. }
  28763. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  28764. /**
  28765. * Gets or sets the instance divisor when in instanced mode
  28766. */
  28767. get: function () {
  28768. return this._instanceDivisor;
  28769. },
  28770. set: function (value) {
  28771. this._instanceDivisor = value;
  28772. if (value == 0) {
  28773. this._instanced = false;
  28774. }
  28775. else {
  28776. this._instanced = true;
  28777. }
  28778. },
  28779. enumerable: true,
  28780. configurable: true
  28781. });
  28782. /** @hidden */
  28783. VertexBuffer.prototype._rebuild = function () {
  28784. if (!this._buffer) {
  28785. return;
  28786. }
  28787. this._buffer._rebuild();
  28788. };
  28789. /**
  28790. * Returns the kind of the VertexBuffer (string).
  28791. */
  28792. VertexBuffer.prototype.getKind = function () {
  28793. return this._kind;
  28794. };
  28795. // Properties
  28796. /**
  28797. * Boolean : is the VertexBuffer updatable ?
  28798. */
  28799. VertexBuffer.prototype.isUpdatable = function () {
  28800. return this._buffer.isUpdatable();
  28801. };
  28802. /**
  28803. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  28804. */
  28805. VertexBuffer.prototype.getData = function () {
  28806. return this._buffer.getData();
  28807. };
  28808. /**
  28809. * Returns the WebGLBuffer associated to the VertexBuffer.
  28810. */
  28811. VertexBuffer.prototype.getBuffer = function () {
  28812. return this._buffer.getBuffer();
  28813. };
  28814. /**
  28815. * Returns the stride as a multiple of the type byte length.
  28816. * DEPRECATED. Use byteStride instead.
  28817. */
  28818. VertexBuffer.prototype.getStrideSize = function () {
  28819. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  28820. };
  28821. /**
  28822. * Returns the offset as a multiple of the type byte length.
  28823. * DEPRECATED. Use byteOffset instead.
  28824. */
  28825. VertexBuffer.prototype.getOffset = function () {
  28826. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  28827. };
  28828. /**
  28829. * Returns the number of components per vertex attribute (integer).
  28830. */
  28831. VertexBuffer.prototype.getSize = function () {
  28832. return this._size;
  28833. };
  28834. /**
  28835. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  28836. */
  28837. VertexBuffer.prototype.getIsInstanced = function () {
  28838. return this._instanced;
  28839. };
  28840. /**
  28841. * Returns the instancing divisor, zero for non-instanced (integer).
  28842. */
  28843. VertexBuffer.prototype.getInstanceDivisor = function () {
  28844. return this._instanceDivisor;
  28845. };
  28846. // Methods
  28847. /**
  28848. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  28849. * Returns the created WebGLBuffer.
  28850. */
  28851. VertexBuffer.prototype.create = function (data) {
  28852. return this._buffer.create(data);
  28853. };
  28854. /**
  28855. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28856. * This function will create a new buffer if the current one is not updatable
  28857. * Returns the updated WebGLBuffer.
  28858. */
  28859. VertexBuffer.prototype.update = function (data) {
  28860. return this._buffer.update(data);
  28861. };
  28862. /**
  28863. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28864. * Returns the directly updated WebGLBuffer.
  28865. * @param data the new data
  28866. * @param offset the new offset
  28867. * @param useBytes set to true if the offset is in bytes
  28868. */
  28869. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  28870. if (useBytes === void 0) { useBytes = false; }
  28871. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  28872. };
  28873. /**
  28874. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  28875. */
  28876. VertexBuffer.prototype.dispose = function () {
  28877. if (this._ownsBuffer) {
  28878. this._buffer.dispose();
  28879. }
  28880. };
  28881. /**
  28882. * Enumerates each value of this vertex buffer as numbers.
  28883. * @param count the number of values to enumerate
  28884. * @param callback the callback function called for each value
  28885. */
  28886. VertexBuffer.prototype.forEach = function (count, callback) {
  28887. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  28888. };
  28889. Object.defineProperty(VertexBuffer, "PositionKind", {
  28890. get: function () {
  28891. return VertexBuffer._PositionKind;
  28892. },
  28893. enumerable: true,
  28894. configurable: true
  28895. });
  28896. Object.defineProperty(VertexBuffer, "NormalKind", {
  28897. get: function () {
  28898. return VertexBuffer._NormalKind;
  28899. },
  28900. enumerable: true,
  28901. configurable: true
  28902. });
  28903. Object.defineProperty(VertexBuffer, "TangentKind", {
  28904. get: function () {
  28905. return VertexBuffer._TangentKind;
  28906. },
  28907. enumerable: true,
  28908. configurable: true
  28909. });
  28910. Object.defineProperty(VertexBuffer, "UVKind", {
  28911. get: function () {
  28912. return VertexBuffer._UVKind;
  28913. },
  28914. enumerable: true,
  28915. configurable: true
  28916. });
  28917. Object.defineProperty(VertexBuffer, "UV2Kind", {
  28918. get: function () {
  28919. return VertexBuffer._UV2Kind;
  28920. },
  28921. enumerable: true,
  28922. configurable: true
  28923. });
  28924. Object.defineProperty(VertexBuffer, "UV3Kind", {
  28925. get: function () {
  28926. return VertexBuffer._UV3Kind;
  28927. },
  28928. enumerable: true,
  28929. configurable: true
  28930. });
  28931. Object.defineProperty(VertexBuffer, "UV4Kind", {
  28932. get: function () {
  28933. return VertexBuffer._UV4Kind;
  28934. },
  28935. enumerable: true,
  28936. configurable: true
  28937. });
  28938. Object.defineProperty(VertexBuffer, "UV5Kind", {
  28939. get: function () {
  28940. return VertexBuffer._UV5Kind;
  28941. },
  28942. enumerable: true,
  28943. configurable: true
  28944. });
  28945. Object.defineProperty(VertexBuffer, "UV6Kind", {
  28946. get: function () {
  28947. return VertexBuffer._UV6Kind;
  28948. },
  28949. enumerable: true,
  28950. configurable: true
  28951. });
  28952. Object.defineProperty(VertexBuffer, "ColorKind", {
  28953. get: function () {
  28954. return VertexBuffer._ColorKind;
  28955. },
  28956. enumerable: true,
  28957. configurable: true
  28958. });
  28959. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  28960. get: function () {
  28961. return VertexBuffer._MatricesIndicesKind;
  28962. },
  28963. enumerable: true,
  28964. configurable: true
  28965. });
  28966. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  28967. get: function () {
  28968. return VertexBuffer._MatricesWeightsKind;
  28969. },
  28970. enumerable: true,
  28971. configurable: true
  28972. });
  28973. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  28974. get: function () {
  28975. return VertexBuffer._MatricesIndicesExtraKind;
  28976. },
  28977. enumerable: true,
  28978. configurable: true
  28979. });
  28980. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  28981. get: function () {
  28982. return VertexBuffer._MatricesWeightsExtraKind;
  28983. },
  28984. enumerable: true,
  28985. configurable: true
  28986. });
  28987. /**
  28988. * Deduces the stride given a kind.
  28989. * @param kind The kind string to deduce
  28990. * @returns The deduced stride
  28991. */
  28992. VertexBuffer.DeduceStride = function (kind) {
  28993. switch (kind) {
  28994. case VertexBuffer.UVKind:
  28995. case VertexBuffer.UV2Kind:
  28996. case VertexBuffer.UV3Kind:
  28997. case VertexBuffer.UV4Kind:
  28998. case VertexBuffer.UV5Kind:
  28999. case VertexBuffer.UV6Kind:
  29000. return 2;
  29001. case VertexBuffer.NormalKind:
  29002. case VertexBuffer.PositionKind:
  29003. return 3;
  29004. case VertexBuffer.ColorKind:
  29005. case VertexBuffer.MatricesIndicesKind:
  29006. case VertexBuffer.MatricesIndicesExtraKind:
  29007. case VertexBuffer.MatricesWeightsKind:
  29008. case VertexBuffer.MatricesWeightsExtraKind:
  29009. case VertexBuffer.TangentKind:
  29010. return 4;
  29011. default:
  29012. throw new Error("Invalid kind '" + kind + "'");
  29013. }
  29014. };
  29015. /**
  29016. * Gets the byte length of the given type.
  29017. * @param type the type
  29018. * @returns the number of bytes
  29019. */
  29020. VertexBuffer.GetTypeByteLength = function (type) {
  29021. switch (type) {
  29022. case VertexBuffer.BYTE:
  29023. case VertexBuffer.UNSIGNED_BYTE:
  29024. return 1;
  29025. case VertexBuffer.SHORT:
  29026. case VertexBuffer.UNSIGNED_SHORT:
  29027. return 2;
  29028. case VertexBuffer.INT:
  29029. case VertexBuffer.FLOAT:
  29030. return 4;
  29031. default:
  29032. throw new Error("Invalid type '" + type + "'");
  29033. }
  29034. };
  29035. /**
  29036. * Enumerates each value of the given parameters as numbers.
  29037. * @param data the data to enumerate
  29038. * @param byteOffset the byte offset of the data
  29039. * @param byteStride the byte stride of the data
  29040. * @param componentCount the number of components per element
  29041. * @param componentType the type of the component
  29042. * @param count the total number of components
  29043. * @param normalized whether the data is normalized
  29044. * @param callback the callback function called for each value
  29045. */
  29046. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29047. if (data instanceof Array) {
  29048. var offset = byteOffset / 4;
  29049. var stride = byteStride / 4;
  29050. for (var index = 0; index < count; index += componentCount) {
  29051. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29052. callback(data[offset + componentIndex], index + componentIndex);
  29053. }
  29054. offset += stride;
  29055. }
  29056. }
  29057. else {
  29058. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29059. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29060. for (var index = 0; index < count; index += componentCount) {
  29061. var componentByteOffset = byteOffset;
  29062. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29063. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29064. callback(value, index + componentIndex);
  29065. componentByteOffset += componentByteLength;
  29066. }
  29067. byteOffset += byteStride;
  29068. }
  29069. }
  29070. };
  29071. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29072. switch (type) {
  29073. case VertexBuffer.BYTE: {
  29074. var value = dataView.getInt8(byteOffset);
  29075. if (normalized) {
  29076. value = Math.max(value / 127, -1);
  29077. }
  29078. return value;
  29079. }
  29080. case VertexBuffer.UNSIGNED_BYTE: {
  29081. var value = dataView.getUint8(byteOffset);
  29082. if (normalized) {
  29083. value = value / 255;
  29084. }
  29085. return value;
  29086. }
  29087. case VertexBuffer.SHORT: {
  29088. var value = dataView.getInt16(byteOffset, true);
  29089. if (normalized) {
  29090. value = Math.max(value / 16383, -1);
  29091. }
  29092. return value;
  29093. }
  29094. case VertexBuffer.UNSIGNED_SHORT: {
  29095. var value = dataView.getUint16(byteOffset, true);
  29096. if (normalized) {
  29097. value = value / 65535;
  29098. }
  29099. return value;
  29100. }
  29101. case VertexBuffer.FLOAT: {
  29102. return dataView.getFloat32(byteOffset, true);
  29103. }
  29104. default: {
  29105. throw new Error("Invalid component type " + type);
  29106. }
  29107. }
  29108. };
  29109. /**
  29110. * The byte type.
  29111. */
  29112. VertexBuffer.BYTE = 5120;
  29113. /**
  29114. * The unsigned byte type.
  29115. */
  29116. VertexBuffer.UNSIGNED_BYTE = 5121;
  29117. /**
  29118. * The short type.
  29119. */
  29120. VertexBuffer.SHORT = 5122;
  29121. /**
  29122. * The unsigned short type.
  29123. */
  29124. VertexBuffer.UNSIGNED_SHORT = 5123;
  29125. /**
  29126. * The integer type.
  29127. */
  29128. VertexBuffer.INT = 5124;
  29129. /**
  29130. * The unsigned integer type.
  29131. */
  29132. VertexBuffer.UNSIGNED_INT = 5125;
  29133. /**
  29134. * The float type.
  29135. */
  29136. VertexBuffer.FLOAT = 5126;
  29137. // Enums
  29138. VertexBuffer._PositionKind = "position";
  29139. VertexBuffer._NormalKind = "normal";
  29140. VertexBuffer._TangentKind = "tangent";
  29141. VertexBuffer._UVKind = "uv";
  29142. VertexBuffer._UV2Kind = "uv2";
  29143. VertexBuffer._UV3Kind = "uv3";
  29144. VertexBuffer._UV4Kind = "uv4";
  29145. VertexBuffer._UV5Kind = "uv5";
  29146. VertexBuffer._UV6Kind = "uv6";
  29147. VertexBuffer._ColorKind = "color";
  29148. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29149. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29150. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29151. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29152. return VertexBuffer;
  29153. }());
  29154. BABYLON.VertexBuffer = VertexBuffer;
  29155. })(BABYLON || (BABYLON = {}));
  29156. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29157. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29158. var BABYLON;
  29159. (function (BABYLON) {
  29160. /**
  29161. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29162. */
  29163. var DummyInternalTextureTracker = /** @class */ (function () {
  29164. function DummyInternalTextureTracker() {
  29165. /**
  29166. * Gets or set the previous tracker in the list
  29167. */
  29168. this.previous = null;
  29169. /**
  29170. * Gets or set the next tracker in the list
  29171. */
  29172. this.next = null;
  29173. }
  29174. return DummyInternalTextureTracker;
  29175. }());
  29176. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29177. })(BABYLON || (BABYLON = {}));
  29178. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29179. var BABYLON;
  29180. (function (BABYLON) {
  29181. /**
  29182. * Class used to store data associated with WebGL texture data for the engine
  29183. * This class should not be used directly
  29184. */
  29185. var InternalTexture = /** @class */ (function () {
  29186. /**
  29187. * Creates a new InternalTexture
  29188. * @param engine defines the engine to use
  29189. * @param dataSource defines the type of data that will be used
  29190. */
  29191. function InternalTexture(engine, dataSource) {
  29192. /**
  29193. * Observable called when the texture is loaded
  29194. */
  29195. this.onLoadedObservable = new BABYLON.Observable();
  29196. /**
  29197. * Gets or set the previous tracker in the list
  29198. */
  29199. this.previous = null;
  29200. /**
  29201. * Gets or set the next tracker in the list
  29202. */
  29203. this.next = null;
  29204. // Private
  29205. /** @hidden */
  29206. this._initialSlot = -1;
  29207. /** @hidden */
  29208. this._designatedSlot = -1;
  29209. /** @hidden */
  29210. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29211. /** @hidden */
  29212. this._comparisonFunction = 0;
  29213. /** @hidden */
  29214. this._sphericalPolynomial = null;
  29215. /** @hidden */
  29216. this._lodGenerationScale = 0;
  29217. /** @hidden */
  29218. this._lodGenerationOffset = 0;
  29219. /** @hidden */
  29220. this._isRGBD = false;
  29221. /** @hidden */
  29222. this._references = 1;
  29223. this._engine = engine;
  29224. this._dataSource = dataSource;
  29225. this._webGLTexture = engine._createTexture();
  29226. }
  29227. /**
  29228. * Gets the Engine the texture belongs to.
  29229. * @returns The babylon engine
  29230. */
  29231. InternalTexture.prototype.getEngine = function () {
  29232. return this._engine;
  29233. };
  29234. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29235. /**
  29236. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29237. */
  29238. get: function () {
  29239. return this._dataSource;
  29240. },
  29241. enumerable: true,
  29242. configurable: true
  29243. });
  29244. /**
  29245. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29246. */
  29247. InternalTexture.prototype.incrementReferences = function () {
  29248. this._references++;
  29249. };
  29250. /**
  29251. * Change the size of the texture (not the size of the content)
  29252. * @param width defines the new width
  29253. * @param height defines the new height
  29254. * @param depth defines the new depth (1 by default)
  29255. */
  29256. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29257. if (depth === void 0) { depth = 1; }
  29258. this.width = width;
  29259. this.height = height;
  29260. this.depth = depth;
  29261. this.baseWidth = width;
  29262. this.baseHeight = height;
  29263. this.baseDepth = depth;
  29264. this._size = width * height * depth;
  29265. };
  29266. /** @hidden */
  29267. InternalTexture.prototype._rebuild = function () {
  29268. var _this = this;
  29269. var proxy;
  29270. this.isReady = false;
  29271. this._cachedCoordinatesMode = null;
  29272. this._cachedWrapU = null;
  29273. this._cachedWrapV = null;
  29274. this._cachedAnisotropicFilteringLevel = null;
  29275. switch (this._dataSource) {
  29276. case InternalTexture.DATASOURCE_TEMP:
  29277. return;
  29278. case InternalTexture.DATASOURCE_URL:
  29279. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29280. _this.isReady = true;
  29281. }, null, this._buffer, undefined, this.format);
  29282. proxy._swapAndDie(this);
  29283. return;
  29284. case InternalTexture.DATASOURCE_RAW:
  29285. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29286. proxy._swapAndDie(this);
  29287. this.isReady = true;
  29288. return;
  29289. case InternalTexture.DATASOURCE_RAW3D:
  29290. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29291. proxy._swapAndDie(this);
  29292. this.isReady = true;
  29293. return;
  29294. case InternalTexture.DATASOURCE_DYNAMIC:
  29295. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29296. proxy._swapAndDie(this);
  29297. // The engine will make sure to update content so no need to flag it as isReady = true
  29298. return;
  29299. case InternalTexture.DATASOURCE_RENDERTARGET:
  29300. var options = new BABYLON.RenderTargetCreationOptions();
  29301. options.generateDepthBuffer = this._generateDepthBuffer;
  29302. options.generateMipMaps = this.generateMipMaps;
  29303. options.generateStencilBuffer = this._generateStencilBuffer;
  29304. options.samplingMode = this.samplingMode;
  29305. options.type = this.type;
  29306. if (this.isCube) {
  29307. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29308. }
  29309. else {
  29310. var size = {
  29311. width: this.width,
  29312. height: this.height
  29313. };
  29314. proxy = this._engine.createRenderTargetTexture(size, options);
  29315. }
  29316. proxy._swapAndDie(this);
  29317. this.isReady = true;
  29318. return;
  29319. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29320. var depthTextureOptions = {
  29321. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29322. comparisonFunction: this._comparisonFunction,
  29323. generateStencil: this._generateStencilBuffer,
  29324. isCube: this.isCube
  29325. };
  29326. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29327. proxy._swapAndDie(this);
  29328. this.isReady = true;
  29329. return;
  29330. case InternalTexture.DATASOURCE_CUBE:
  29331. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29332. _this.isReady = true;
  29333. }, null, this.format, this._extension);
  29334. proxy._swapAndDie(this);
  29335. return;
  29336. case InternalTexture.DATASOURCE_CUBERAW:
  29337. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29338. proxy._swapAndDie(this);
  29339. this.isReady = true;
  29340. return;
  29341. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29342. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29343. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29344. _this.isReady = true;
  29345. });
  29346. proxy._swapAndDie(this);
  29347. return;
  29348. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29349. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29350. if (proxy) {
  29351. proxy._swapAndDie(_this);
  29352. }
  29353. _this.isReady = true;
  29354. }, null, this.format, this._extension);
  29355. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29356. return;
  29357. }
  29358. };
  29359. /** @hidden */
  29360. InternalTexture.prototype._swapAndDie = function (target) {
  29361. target._webGLTexture = this._webGLTexture;
  29362. if (this._framebuffer) {
  29363. target._framebuffer = this._framebuffer;
  29364. }
  29365. if (this._depthStencilBuffer) {
  29366. target._depthStencilBuffer = this._depthStencilBuffer;
  29367. }
  29368. if (this._lodTextureHigh) {
  29369. if (target._lodTextureHigh) {
  29370. target._lodTextureHigh.dispose();
  29371. }
  29372. target._lodTextureHigh = this._lodTextureHigh;
  29373. }
  29374. if (this._lodTextureMid) {
  29375. if (target._lodTextureMid) {
  29376. target._lodTextureMid.dispose();
  29377. }
  29378. target._lodTextureMid = this._lodTextureMid;
  29379. }
  29380. if (this._lodTextureLow) {
  29381. if (target._lodTextureLow) {
  29382. target._lodTextureLow.dispose();
  29383. }
  29384. target._lodTextureLow = this._lodTextureLow;
  29385. }
  29386. var cache = this._engine.getLoadedTexturesCache();
  29387. var index = cache.indexOf(this);
  29388. if (index !== -1) {
  29389. cache.splice(index, 1);
  29390. }
  29391. };
  29392. /**
  29393. * Dispose the current allocated resources
  29394. */
  29395. InternalTexture.prototype.dispose = function () {
  29396. if (!this._webGLTexture) {
  29397. return;
  29398. }
  29399. this._references--;
  29400. if (this._references === 0) {
  29401. this._engine._releaseTexture(this);
  29402. this._webGLTexture = null;
  29403. this.previous = null;
  29404. this.next = null;
  29405. }
  29406. };
  29407. /**
  29408. * The source of the texture data is unknown
  29409. */
  29410. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29411. /**
  29412. * Texture data comes from an URL
  29413. */
  29414. InternalTexture.DATASOURCE_URL = 1;
  29415. /**
  29416. * Texture data is only used for temporary storage
  29417. */
  29418. InternalTexture.DATASOURCE_TEMP = 2;
  29419. /**
  29420. * Texture data comes from raw data (ArrayBuffer)
  29421. */
  29422. InternalTexture.DATASOURCE_RAW = 3;
  29423. /**
  29424. * Texture content is dynamic (video or dynamic texture)
  29425. */
  29426. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29427. /**
  29428. * Texture content is generated by rendering to it
  29429. */
  29430. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29431. /**
  29432. * Texture content is part of a multi render target process
  29433. */
  29434. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29435. /**
  29436. * Texture data comes from a cube data file
  29437. */
  29438. InternalTexture.DATASOURCE_CUBE = 7;
  29439. /**
  29440. * Texture data comes from a raw cube data
  29441. */
  29442. InternalTexture.DATASOURCE_CUBERAW = 8;
  29443. /**
  29444. * Texture data come from a prefiltered cube data file
  29445. */
  29446. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29447. /**
  29448. * Texture content is raw 3D data
  29449. */
  29450. InternalTexture.DATASOURCE_RAW3D = 10;
  29451. /**
  29452. * Texture content is a depth texture
  29453. */
  29454. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29455. /**
  29456. * Texture data comes from a raw cube data encoded with RGBD
  29457. */
  29458. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29459. return InternalTexture;
  29460. }());
  29461. BABYLON.InternalTexture = InternalTexture;
  29462. })(BABYLON || (BABYLON = {}));
  29463. //# sourceMappingURL=babylon.internalTexture.js.map
  29464. var BABYLON;
  29465. (function (BABYLON) {
  29466. var BaseTexture = /** @class */ (function () {
  29467. function BaseTexture(scene) {
  29468. this._hasAlpha = false;
  29469. this.getAlphaFromRGB = false;
  29470. this.level = 1;
  29471. this.coordinatesIndex = 0;
  29472. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29473. /**
  29474. * | Value | Type | Description |
  29475. * | ----- | ------------------ | ----------- |
  29476. * | 0 | CLAMP_ADDRESSMODE | |
  29477. * | 1 | WRAP_ADDRESSMODE | |
  29478. * | 2 | MIRROR_ADDRESSMODE | |
  29479. */
  29480. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29481. /**
  29482. * | Value | Type | Description |
  29483. * | ----- | ------------------ | ----------- |
  29484. * | 0 | CLAMP_ADDRESSMODE | |
  29485. * | 1 | WRAP_ADDRESSMODE | |
  29486. * | 2 | MIRROR_ADDRESSMODE | |
  29487. */
  29488. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29489. /**
  29490. * | Value | Type | Description |
  29491. * | ----- | ------------------ | ----------- |
  29492. * | 0 | CLAMP_ADDRESSMODE | |
  29493. * | 1 | WRAP_ADDRESSMODE | |
  29494. * | 2 | MIRROR_ADDRESSMODE | |
  29495. */
  29496. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29497. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29498. this.isCube = false;
  29499. this.is3D = false;
  29500. this.gammaSpace = true;
  29501. this.invertZ = false;
  29502. this.lodLevelInAlpha = false;
  29503. this.isRenderTarget = false;
  29504. this.animations = new Array();
  29505. /**
  29506. * An event triggered when the texture is disposed.
  29507. */
  29508. this.onDisposeObservable = new BABYLON.Observable();
  29509. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29510. this._cachedSize = BABYLON.Size.Zero();
  29511. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29512. if (this._scene) {
  29513. this._scene.textures.push(this);
  29514. }
  29515. this._uid = null;
  29516. }
  29517. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29518. get: function () {
  29519. return this._hasAlpha;
  29520. },
  29521. set: function (value) {
  29522. if (this._hasAlpha === value) {
  29523. return;
  29524. }
  29525. this._hasAlpha = value;
  29526. if (this._scene) {
  29527. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29528. }
  29529. },
  29530. enumerable: true,
  29531. configurable: true
  29532. });
  29533. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29534. get: function () {
  29535. return this._coordinatesMode;
  29536. },
  29537. /**
  29538. * How a texture is mapped.
  29539. *
  29540. * | Value | Type | Description |
  29541. * | ----- | ----------------------------------- | ----------- |
  29542. * | 0 | EXPLICIT_MODE | |
  29543. * | 1 | SPHERICAL_MODE | |
  29544. * | 2 | PLANAR_MODE | |
  29545. * | 3 | CUBIC_MODE | |
  29546. * | 4 | PROJECTION_MODE | |
  29547. * | 5 | SKYBOX_MODE | |
  29548. * | 6 | INVCUBIC_MODE | |
  29549. * | 7 | EQUIRECTANGULAR_MODE | |
  29550. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29551. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29552. */
  29553. set: function (value) {
  29554. if (this._coordinatesMode === value) {
  29555. return;
  29556. }
  29557. this._coordinatesMode = value;
  29558. if (this._scene) {
  29559. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29560. }
  29561. },
  29562. enumerable: true,
  29563. configurable: true
  29564. });
  29565. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  29566. /**
  29567. * Gets whether or not the texture contains RGBD data.
  29568. */
  29569. get: function () {
  29570. return this._texture != null && this._texture._isRGBD;
  29571. },
  29572. enumerable: true,
  29573. configurable: true
  29574. });
  29575. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  29576. get: function () {
  29577. if (this._texture)
  29578. return this._texture._lodGenerationOffset;
  29579. return 0.0;
  29580. },
  29581. set: function (value) {
  29582. if (this._texture)
  29583. this._texture._lodGenerationOffset = value;
  29584. },
  29585. enumerable: true,
  29586. configurable: true
  29587. });
  29588. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  29589. get: function () {
  29590. if (this._texture)
  29591. return this._texture._lodGenerationScale;
  29592. return 0.0;
  29593. },
  29594. set: function (value) {
  29595. if (this._texture)
  29596. this._texture._lodGenerationScale = value;
  29597. },
  29598. enumerable: true,
  29599. configurable: true
  29600. });
  29601. Object.defineProperty(BaseTexture.prototype, "uid", {
  29602. get: function () {
  29603. if (!this._uid) {
  29604. this._uid = BABYLON.Tools.RandomId();
  29605. }
  29606. return this._uid;
  29607. },
  29608. enumerable: true,
  29609. configurable: true
  29610. });
  29611. BaseTexture.prototype.toString = function () {
  29612. return this.name;
  29613. };
  29614. BaseTexture.prototype.getClassName = function () {
  29615. return "BaseTexture";
  29616. };
  29617. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29618. set: function (callback) {
  29619. if (this._onDisposeObserver) {
  29620. this.onDisposeObservable.remove(this._onDisposeObserver);
  29621. }
  29622. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29623. },
  29624. enumerable: true,
  29625. configurable: true
  29626. });
  29627. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29628. get: function () {
  29629. return true;
  29630. },
  29631. enumerable: true,
  29632. configurable: true
  29633. });
  29634. BaseTexture.prototype.getScene = function () {
  29635. return this._scene;
  29636. };
  29637. BaseTexture.prototype.getTextureMatrix = function () {
  29638. return BABYLON.Matrix.IdentityReadOnly;
  29639. };
  29640. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29641. return BABYLON.Matrix.IdentityReadOnly;
  29642. };
  29643. BaseTexture.prototype.getInternalTexture = function () {
  29644. return this._texture;
  29645. };
  29646. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29647. return !this.isBlocking || this.isReady();
  29648. };
  29649. BaseTexture.prototype.isReady = function () {
  29650. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29651. this.delayLoad();
  29652. return false;
  29653. }
  29654. if (this._texture) {
  29655. return this._texture.isReady;
  29656. }
  29657. return false;
  29658. };
  29659. BaseTexture.prototype.getSize = function () {
  29660. if (this._texture) {
  29661. if (this._texture.width) {
  29662. this._cachedSize.width = this._texture.width;
  29663. this._cachedSize.height = this._texture.height;
  29664. return this._cachedSize;
  29665. }
  29666. if (this._texture._size) {
  29667. this._cachedSize.width = this._texture._size;
  29668. this._cachedSize.height = this._texture._size;
  29669. return this._cachedSize;
  29670. }
  29671. }
  29672. return this._cachedSize;
  29673. };
  29674. BaseTexture.prototype.getBaseSize = function () {
  29675. if (!this.isReady() || !this._texture)
  29676. return BABYLON.Size.Zero();
  29677. if (this._texture._size) {
  29678. return new BABYLON.Size(this._texture._size, this._texture._size);
  29679. }
  29680. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29681. };
  29682. BaseTexture.prototype.scale = function (ratio) {
  29683. };
  29684. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29685. get: function () {
  29686. return false;
  29687. },
  29688. enumerable: true,
  29689. configurable: true
  29690. });
  29691. /** @hidden */
  29692. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29693. if (!this._scene) {
  29694. return null;
  29695. }
  29696. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29697. for (var index = 0; index < texturesCache.length; index++) {
  29698. var texturesCacheEntry = texturesCache[index];
  29699. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29700. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29701. texturesCacheEntry.incrementReferences();
  29702. return texturesCacheEntry;
  29703. }
  29704. }
  29705. }
  29706. return null;
  29707. };
  29708. /** @hidden */
  29709. BaseTexture.prototype._rebuild = function () {
  29710. };
  29711. BaseTexture.prototype.delayLoad = function () {
  29712. };
  29713. BaseTexture.prototype.clone = function () {
  29714. return null;
  29715. };
  29716. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29717. get: function () {
  29718. if (!this._texture) {
  29719. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29720. }
  29721. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29722. },
  29723. enumerable: true,
  29724. configurable: true
  29725. });
  29726. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29727. get: function () {
  29728. if (!this._texture) {
  29729. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29730. }
  29731. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29732. },
  29733. enumerable: true,
  29734. configurable: true
  29735. });
  29736. /**
  29737. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  29738. * This will returns an RGBA array buffer containing either in values (0-255) or
  29739. * float values (0-1) depending of the underlying buffer type.
  29740. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  29741. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  29742. * @param buffer defines a user defined buffer to fill with data (can be null)
  29743. * @returns The Array buffer containing the pixels data.
  29744. */
  29745. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  29746. if (faceIndex === void 0) { faceIndex = 0; }
  29747. if (level === void 0) { level = 0; }
  29748. if (buffer === void 0) { buffer = null; }
  29749. if (!this._texture) {
  29750. return null;
  29751. }
  29752. var size = this.getSize();
  29753. var width = size.width;
  29754. var height = size.height;
  29755. var scene = this.getScene();
  29756. if (!scene) {
  29757. return null;
  29758. }
  29759. var engine = scene.getEngine();
  29760. if (level != 0) {
  29761. width = width / Math.pow(2, level);
  29762. height = height / Math.pow(2, level);
  29763. width = Math.round(width);
  29764. height = Math.round(height);
  29765. }
  29766. if (this._texture.isCube) {
  29767. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  29768. }
  29769. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  29770. };
  29771. BaseTexture.prototype.releaseInternalTexture = function () {
  29772. if (this._texture) {
  29773. this._texture.dispose();
  29774. this._texture = null;
  29775. }
  29776. };
  29777. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29778. get: function () {
  29779. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  29780. return null;
  29781. }
  29782. if (!this._texture._sphericalPolynomial) {
  29783. this._texture._sphericalPolynomial =
  29784. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  29785. }
  29786. return this._texture._sphericalPolynomial;
  29787. },
  29788. set: function (value) {
  29789. if (this._texture) {
  29790. this._texture._sphericalPolynomial = value;
  29791. }
  29792. },
  29793. enumerable: true,
  29794. configurable: true
  29795. });
  29796. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  29797. get: function () {
  29798. if (this._texture) {
  29799. return this._texture._lodTextureHigh;
  29800. }
  29801. return null;
  29802. },
  29803. enumerable: true,
  29804. configurable: true
  29805. });
  29806. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  29807. get: function () {
  29808. if (this._texture) {
  29809. return this._texture._lodTextureMid;
  29810. }
  29811. return null;
  29812. },
  29813. enumerable: true,
  29814. configurable: true
  29815. });
  29816. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  29817. get: function () {
  29818. if (this._texture) {
  29819. return this._texture._lodTextureLow;
  29820. }
  29821. return null;
  29822. },
  29823. enumerable: true,
  29824. configurable: true
  29825. });
  29826. BaseTexture.prototype.dispose = function () {
  29827. if (!this._scene) {
  29828. return;
  29829. }
  29830. // Animations
  29831. this._scene.stopAnimation(this);
  29832. // Remove from scene
  29833. this._scene._removePendingData(this);
  29834. var index = this._scene.textures.indexOf(this);
  29835. if (index >= 0) {
  29836. this._scene.textures.splice(index, 1);
  29837. }
  29838. if (this._texture === undefined) {
  29839. return;
  29840. }
  29841. // Release
  29842. this.releaseInternalTexture();
  29843. // Callback
  29844. this.onDisposeObservable.notifyObservers(this);
  29845. this.onDisposeObservable.clear();
  29846. };
  29847. BaseTexture.prototype.serialize = function () {
  29848. if (!this.name) {
  29849. return null;
  29850. }
  29851. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29852. // Animations
  29853. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29854. return serializationObject;
  29855. };
  29856. BaseTexture.WhenAllReady = function (textures, callback) {
  29857. var numRemaining = textures.length;
  29858. if (numRemaining === 0) {
  29859. callback();
  29860. return;
  29861. }
  29862. var _loop_1 = function () {
  29863. texture = textures[i];
  29864. if (texture.isReady()) {
  29865. if (--numRemaining === 0) {
  29866. callback();
  29867. }
  29868. }
  29869. else {
  29870. onLoadObservable = texture.onLoadObservable;
  29871. var onLoadCallback_1 = function () {
  29872. onLoadObservable.removeCallback(onLoadCallback_1);
  29873. if (--numRemaining === 0) {
  29874. callback();
  29875. }
  29876. };
  29877. onLoadObservable.add(onLoadCallback_1);
  29878. }
  29879. };
  29880. var texture, onLoadObservable;
  29881. for (var i = 0; i < textures.length; i++) {
  29882. _loop_1();
  29883. }
  29884. };
  29885. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  29886. __decorate([
  29887. BABYLON.serialize()
  29888. ], BaseTexture.prototype, "name", void 0);
  29889. __decorate([
  29890. BABYLON.serialize("hasAlpha")
  29891. ], BaseTexture.prototype, "_hasAlpha", void 0);
  29892. __decorate([
  29893. BABYLON.serialize()
  29894. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  29895. __decorate([
  29896. BABYLON.serialize()
  29897. ], BaseTexture.prototype, "level", void 0);
  29898. __decorate([
  29899. BABYLON.serialize()
  29900. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  29901. __decorate([
  29902. BABYLON.serialize("coordinatesMode")
  29903. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  29904. __decorate([
  29905. BABYLON.serialize()
  29906. ], BaseTexture.prototype, "wrapU", void 0);
  29907. __decorate([
  29908. BABYLON.serialize()
  29909. ], BaseTexture.prototype, "wrapV", void 0);
  29910. __decorate([
  29911. BABYLON.serialize()
  29912. ], BaseTexture.prototype, "wrapR", void 0);
  29913. __decorate([
  29914. BABYLON.serialize()
  29915. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  29916. __decorate([
  29917. BABYLON.serialize()
  29918. ], BaseTexture.prototype, "isCube", void 0);
  29919. __decorate([
  29920. BABYLON.serialize()
  29921. ], BaseTexture.prototype, "is3D", void 0);
  29922. __decorate([
  29923. BABYLON.serialize()
  29924. ], BaseTexture.prototype, "gammaSpace", void 0);
  29925. __decorate([
  29926. BABYLON.serialize()
  29927. ], BaseTexture.prototype, "invertZ", void 0);
  29928. __decorate([
  29929. BABYLON.serialize()
  29930. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  29931. __decorate([
  29932. BABYLON.serialize()
  29933. ], BaseTexture.prototype, "lodGenerationOffset", null);
  29934. __decorate([
  29935. BABYLON.serialize()
  29936. ], BaseTexture.prototype, "lodGenerationScale", null);
  29937. __decorate([
  29938. BABYLON.serialize()
  29939. ], BaseTexture.prototype, "isRenderTarget", void 0);
  29940. return BaseTexture;
  29941. }());
  29942. BABYLON.BaseTexture = BaseTexture;
  29943. })(BABYLON || (BABYLON = {}));
  29944. //# sourceMappingURL=babylon.baseTexture.js.map
  29945. var BABYLON;
  29946. (function (BABYLON) {
  29947. var Texture = /** @class */ (function (_super) {
  29948. __extends(Texture, _super);
  29949. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  29950. if (noMipmap === void 0) { noMipmap = false; }
  29951. if (invertY === void 0) { invertY = true; }
  29952. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  29953. if (onLoad === void 0) { onLoad = null; }
  29954. if (onError === void 0) { onError = null; }
  29955. if (buffer === void 0) { buffer = null; }
  29956. if (deleteBuffer === void 0) { deleteBuffer = false; }
  29957. var _this = _super.call(this, scene) || this;
  29958. _this.uOffset = 0;
  29959. _this.vOffset = 0;
  29960. _this.uScale = 1.0;
  29961. _this.vScale = 1.0;
  29962. _this.uAng = 0;
  29963. _this.vAng = 0;
  29964. _this.wAng = 0;
  29965. /**
  29966. * Defines the center of rotation (U)
  29967. */
  29968. _this.uRotationCenter = 0.5;
  29969. /**
  29970. * Defines the center of rotation (V)
  29971. */
  29972. _this.vRotationCenter = 0.5;
  29973. /**
  29974. * Defines the center of rotation (W)
  29975. */
  29976. _this.wRotationCenter = 0.5;
  29977. _this._isBlocking = true;
  29978. _this.name = url || "";
  29979. _this.url = url;
  29980. _this._noMipmap = noMipmap;
  29981. _this._invertY = invertY;
  29982. _this._samplingMode = samplingMode;
  29983. _this._buffer = buffer;
  29984. _this._deleteBuffer = deleteBuffer;
  29985. if (format) {
  29986. _this._format = format;
  29987. }
  29988. scene = _this.getScene();
  29989. if (!scene) {
  29990. return _this;
  29991. }
  29992. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  29993. var load = function () {
  29994. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  29995. _this.onLoadObservable.notifyObservers(_this);
  29996. }
  29997. if (onLoad) {
  29998. onLoad();
  29999. }
  30000. if (!_this.isBlocking && scene) {
  30001. scene.resetCachedMaterial();
  30002. }
  30003. };
  30004. if (!_this.url) {
  30005. _this._delayedOnLoad = load;
  30006. _this._delayedOnError = onError;
  30007. return _this;
  30008. }
  30009. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30010. if (!_this._texture) {
  30011. if (!scene.useDelayedTextureLoading) {
  30012. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30013. if (deleteBuffer) {
  30014. delete _this._buffer;
  30015. }
  30016. }
  30017. else {
  30018. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30019. _this._delayedOnLoad = load;
  30020. _this._delayedOnError = onError;
  30021. }
  30022. }
  30023. else {
  30024. if (_this._texture.isReady) {
  30025. BABYLON.Tools.SetImmediate(function () { return load(); });
  30026. }
  30027. else {
  30028. _this._texture.onLoadedObservable.add(load);
  30029. }
  30030. }
  30031. return _this;
  30032. }
  30033. Object.defineProperty(Texture.prototype, "noMipmap", {
  30034. get: function () {
  30035. return this._noMipmap;
  30036. },
  30037. enumerable: true,
  30038. configurable: true
  30039. });
  30040. Object.defineProperty(Texture.prototype, "isBlocking", {
  30041. get: function () {
  30042. return this._isBlocking;
  30043. },
  30044. set: function (value) {
  30045. this._isBlocking = value;
  30046. },
  30047. enumerable: true,
  30048. configurable: true
  30049. });
  30050. Object.defineProperty(Texture.prototype, "samplingMode", {
  30051. get: function () {
  30052. return this._samplingMode;
  30053. },
  30054. enumerable: true,
  30055. configurable: true
  30056. });
  30057. /**
  30058. * Update the url (and optional buffer) of this texture if url was null during construction.
  30059. * @param url the url of the texture
  30060. * @param buffer the buffer of the texture (defaults to null)
  30061. */
  30062. Texture.prototype.updateURL = function (url, buffer) {
  30063. if (buffer === void 0) { buffer = null; }
  30064. if (this.url) {
  30065. throw new Error("URL is already set");
  30066. }
  30067. this.url = url;
  30068. this._buffer = buffer;
  30069. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30070. this.delayLoad();
  30071. };
  30072. Texture.prototype.delayLoad = function () {
  30073. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30074. return;
  30075. }
  30076. var scene = this.getScene();
  30077. if (!scene) {
  30078. return;
  30079. }
  30080. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30081. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30082. if (!this._texture) {
  30083. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30084. if (this._deleteBuffer) {
  30085. delete this._buffer;
  30086. }
  30087. }
  30088. else {
  30089. if (this._delayedOnLoad) {
  30090. if (this._texture.isReady) {
  30091. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30092. }
  30093. else {
  30094. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30095. }
  30096. }
  30097. }
  30098. this._delayedOnLoad = null;
  30099. this._delayedOnError = null;
  30100. };
  30101. /**
  30102. * Default is Trilinear mode.
  30103. *
  30104. * | Value | Type | Description |
  30105. * | ----- | ------------------ | ----------- |
  30106. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30107. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30108. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30109. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30110. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30111. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30112. * | 7 | NEAREST_LINEAR | |
  30113. * | 8 | NEAREST_NEAREST | |
  30114. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30115. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30116. * | 11 | LINEAR_LINEAR | |
  30117. * | 12 | LINEAR_NEAREST | |
  30118. *
  30119. * > _mag_: magnification filter (close to the viewer)
  30120. * > _min_: minification filter (far from the viewer)
  30121. * > _mip_: filter used between mip map levels
  30122. *
  30123. */
  30124. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30125. if (!this._texture) {
  30126. return;
  30127. }
  30128. var scene = this.getScene();
  30129. if (!scene) {
  30130. return;
  30131. }
  30132. this._samplingMode = samplingMode;
  30133. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30134. };
  30135. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30136. x *= this.uScale;
  30137. y *= this.vScale;
  30138. x -= this.uRotationCenter * this.uScale;
  30139. y -= this.vRotationCenter * this.vScale;
  30140. z -= this.wRotationCenter;
  30141. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30142. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30143. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30144. t.z += this.wRotationCenter;
  30145. };
  30146. Texture.prototype.getTextureMatrix = function () {
  30147. var _this = this;
  30148. if (this.uOffset === this._cachedUOffset &&
  30149. this.vOffset === this._cachedVOffset &&
  30150. this.uScale === this._cachedUScale &&
  30151. this.vScale === this._cachedVScale &&
  30152. this.uAng === this._cachedUAng &&
  30153. this.vAng === this._cachedVAng &&
  30154. this.wAng === this._cachedWAng) {
  30155. return this._cachedTextureMatrix;
  30156. }
  30157. this._cachedUOffset = this.uOffset;
  30158. this._cachedVOffset = this.vOffset;
  30159. this._cachedUScale = this.uScale;
  30160. this._cachedVScale = this.vScale;
  30161. this._cachedUAng = this.uAng;
  30162. this._cachedVAng = this.vAng;
  30163. this._cachedWAng = this.wAng;
  30164. if (!this._cachedTextureMatrix) {
  30165. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30166. this._rowGenerationMatrix = new BABYLON.Matrix();
  30167. this._t0 = BABYLON.Vector3.Zero();
  30168. this._t1 = BABYLON.Vector3.Zero();
  30169. this._t2 = BABYLON.Vector3.Zero();
  30170. }
  30171. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30172. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30173. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30174. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30175. this._t1.subtractInPlace(this._t0);
  30176. this._t2.subtractInPlace(this._t0);
  30177. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30178. this._cachedTextureMatrix.m[0] = this._t1.x;
  30179. this._cachedTextureMatrix.m[1] = this._t1.y;
  30180. this._cachedTextureMatrix.m[2] = this._t1.z;
  30181. this._cachedTextureMatrix.m[4] = this._t2.x;
  30182. this._cachedTextureMatrix.m[5] = this._t2.y;
  30183. this._cachedTextureMatrix.m[6] = this._t2.z;
  30184. this._cachedTextureMatrix.m[8] = this._t0.x;
  30185. this._cachedTextureMatrix.m[9] = this._t0.y;
  30186. this._cachedTextureMatrix.m[10] = this._t0.z;
  30187. var scene = this.getScene();
  30188. if (!scene) {
  30189. return this._cachedTextureMatrix;
  30190. }
  30191. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30192. return mat.hasTexture(_this);
  30193. });
  30194. return this._cachedTextureMatrix;
  30195. };
  30196. Texture.prototype.getReflectionTextureMatrix = function () {
  30197. var _this = this;
  30198. var scene = this.getScene();
  30199. if (!scene) {
  30200. return this._cachedTextureMatrix;
  30201. }
  30202. if (this.uOffset === this._cachedUOffset &&
  30203. this.vOffset === this._cachedVOffset &&
  30204. this.uScale === this._cachedUScale &&
  30205. this.vScale === this._cachedVScale &&
  30206. this.coordinatesMode === this._cachedCoordinatesMode) {
  30207. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30208. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30209. return this._cachedTextureMatrix;
  30210. }
  30211. }
  30212. else {
  30213. return this._cachedTextureMatrix;
  30214. }
  30215. }
  30216. if (!this._cachedTextureMatrix) {
  30217. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30218. }
  30219. if (!this._projectionModeMatrix) {
  30220. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30221. }
  30222. this._cachedUOffset = this.uOffset;
  30223. this._cachedVOffset = this.vOffset;
  30224. this._cachedUScale = this.uScale;
  30225. this._cachedVScale = this.vScale;
  30226. this._cachedCoordinatesMode = this.coordinatesMode;
  30227. switch (this.coordinatesMode) {
  30228. case Texture.PLANAR_MODE:
  30229. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30230. this._cachedTextureMatrix[0] = this.uScale;
  30231. this._cachedTextureMatrix[5] = this.vScale;
  30232. this._cachedTextureMatrix[12] = this.uOffset;
  30233. this._cachedTextureMatrix[13] = this.vOffset;
  30234. break;
  30235. case Texture.PROJECTION_MODE:
  30236. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30237. this._projectionModeMatrix.m[0] = 0.5;
  30238. this._projectionModeMatrix.m[5] = -0.5;
  30239. this._projectionModeMatrix.m[10] = 0.0;
  30240. this._projectionModeMatrix.m[12] = 0.5;
  30241. this._projectionModeMatrix.m[13] = 0.5;
  30242. this._projectionModeMatrix.m[14] = 1.0;
  30243. this._projectionModeMatrix.m[15] = 1.0;
  30244. var projectionMatrix = scene.getProjectionMatrix();
  30245. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30246. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30247. break;
  30248. default:
  30249. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30250. break;
  30251. }
  30252. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30253. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30254. });
  30255. return this._cachedTextureMatrix;
  30256. };
  30257. Texture.prototype.clone = function () {
  30258. var _this = this;
  30259. return BABYLON.SerializationHelper.Clone(function () {
  30260. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30261. }, this);
  30262. };
  30263. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30264. get: function () {
  30265. if (!this._onLoadObservable) {
  30266. this._onLoadObservable = new BABYLON.Observable();
  30267. }
  30268. return this._onLoadObservable;
  30269. },
  30270. enumerable: true,
  30271. configurable: true
  30272. });
  30273. Texture.prototype.serialize = function () {
  30274. var serializationObject = _super.prototype.serialize.call(this);
  30275. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30276. serializationObject.base64String = this._buffer;
  30277. serializationObject.name = serializationObject.name.replace("data:", "");
  30278. }
  30279. serializationObject.invertY = this._invertY;
  30280. serializationObject.samplingMode = this.samplingMode;
  30281. return serializationObject;
  30282. };
  30283. Texture.prototype.getClassName = function () {
  30284. return "Texture";
  30285. };
  30286. Texture.prototype.dispose = function () {
  30287. _super.prototype.dispose.call(this);
  30288. if (this._onLoadObservable) {
  30289. this._onLoadObservable.clear();
  30290. this._onLoadObservable = null;
  30291. }
  30292. this._delayedOnLoad = null;
  30293. this._delayedOnError = null;
  30294. };
  30295. // Statics
  30296. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30297. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30298. if (onLoad === void 0) { onLoad = null; }
  30299. if (onError === void 0) { onError = null; }
  30300. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30301. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30302. };
  30303. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30304. if (parsedTexture.customType) {
  30305. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30306. // Update Sampling Mode
  30307. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30308. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30309. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30310. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30311. }
  30312. }
  30313. return parsedCustomTexture;
  30314. }
  30315. if (parsedTexture.isCube) {
  30316. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30317. }
  30318. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30319. return null;
  30320. }
  30321. var texture = BABYLON.SerializationHelper.Parse(function () {
  30322. var generateMipMaps = true;
  30323. if (parsedTexture.noMipmap) {
  30324. generateMipMaps = false;
  30325. }
  30326. if (parsedTexture.mirrorPlane) {
  30327. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30328. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30329. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30330. return mirrorTexture;
  30331. }
  30332. else if (parsedTexture.isRenderTarget) {
  30333. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30334. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30335. return renderTargetTexture;
  30336. }
  30337. else {
  30338. var texture;
  30339. if (parsedTexture.base64String) {
  30340. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30341. }
  30342. else {
  30343. var url = rootUrl + parsedTexture.name;
  30344. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30345. url = parsedTexture.url;
  30346. }
  30347. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30348. }
  30349. return texture;
  30350. }
  30351. }, parsedTexture, scene);
  30352. // Update Sampling Mode
  30353. if (parsedTexture.samplingMode) {
  30354. var sampling = parsedTexture.samplingMode;
  30355. if (texture._samplingMode !== sampling) {
  30356. texture.updateSamplingMode(sampling);
  30357. }
  30358. }
  30359. // Animations
  30360. if (parsedTexture.animations) {
  30361. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30362. var parsedAnimation = parsedTexture.animations[animationIndex];
  30363. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30364. }
  30365. }
  30366. return texture;
  30367. };
  30368. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30369. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30370. if (noMipmap === void 0) { noMipmap = false; }
  30371. if (invertY === void 0) { invertY = true; }
  30372. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30373. if (onLoad === void 0) { onLoad = null; }
  30374. if (onError === void 0) { onError = null; }
  30375. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30376. if (name.substr(0, 5) !== "data:") {
  30377. name = "data:" + name;
  30378. }
  30379. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30380. };
  30381. // Constants
  30382. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30383. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30384. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30385. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30386. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30387. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30388. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30389. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30390. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30391. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30392. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30393. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30394. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30395. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30396. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30397. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30398. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30399. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30400. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30401. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30402. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30403. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30404. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30405. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30406. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30407. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30408. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30409. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30410. /**
  30411. * 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
  30412. */
  30413. Texture.UseSerializedUrlIfAny = false;
  30414. __decorate([
  30415. BABYLON.serialize()
  30416. ], Texture.prototype, "url", void 0);
  30417. __decorate([
  30418. BABYLON.serialize()
  30419. ], Texture.prototype, "uOffset", void 0);
  30420. __decorate([
  30421. BABYLON.serialize()
  30422. ], Texture.prototype, "vOffset", void 0);
  30423. __decorate([
  30424. BABYLON.serialize()
  30425. ], Texture.prototype, "uScale", void 0);
  30426. __decorate([
  30427. BABYLON.serialize()
  30428. ], Texture.prototype, "vScale", void 0);
  30429. __decorate([
  30430. BABYLON.serialize()
  30431. ], Texture.prototype, "uAng", void 0);
  30432. __decorate([
  30433. BABYLON.serialize()
  30434. ], Texture.prototype, "vAng", void 0);
  30435. __decorate([
  30436. BABYLON.serialize()
  30437. ], Texture.prototype, "wAng", void 0);
  30438. __decorate([
  30439. BABYLON.serialize()
  30440. ], Texture.prototype, "uRotationCenter", void 0);
  30441. __decorate([
  30442. BABYLON.serialize()
  30443. ], Texture.prototype, "vRotationCenter", void 0);
  30444. __decorate([
  30445. BABYLON.serialize()
  30446. ], Texture.prototype, "wRotationCenter", void 0);
  30447. __decorate([
  30448. BABYLON.serialize()
  30449. ], Texture.prototype, "isBlocking", null);
  30450. return Texture;
  30451. }(BABYLON.BaseTexture));
  30452. BABYLON.Texture = Texture;
  30453. })(BABYLON || (BABYLON = {}));
  30454. //# sourceMappingURL=babylon.texture.js.map
  30455. var BABYLON;
  30456. (function (BABYLON) {
  30457. /**
  30458. * @hidden
  30459. **/
  30460. var _InstancesBatch = /** @class */ (function () {
  30461. function _InstancesBatch() {
  30462. this.mustReturn = false;
  30463. this.visibleInstances = new Array();
  30464. this.renderSelf = new Array();
  30465. }
  30466. return _InstancesBatch;
  30467. }());
  30468. BABYLON._InstancesBatch = _InstancesBatch;
  30469. var Mesh = /** @class */ (function (_super) {
  30470. __extends(Mesh, _super);
  30471. /**
  30472. * @constructor
  30473. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30474. * @param {Scene} scene The scene to add this mesh to.
  30475. * @param {Node} parent The parent of this mesh, if it has one
  30476. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30477. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30478. * When false, achieved by calling a clone(), also passing False.
  30479. * This will make creation of children, recursive.
  30480. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30481. */
  30482. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30483. if (scene === void 0) { scene = null; }
  30484. if (parent === void 0) { parent = null; }
  30485. if (source === void 0) { source = null; }
  30486. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30487. var _this = _super.call(this, name, scene) || this;
  30488. // Members
  30489. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30490. _this.instances = new Array();
  30491. _this._LODLevels = new Array();
  30492. /** @hidden */
  30493. _this._visibleInstances = {};
  30494. _this._renderIdForInstances = new Array();
  30495. _this._batchCache = new _InstancesBatch();
  30496. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30497. // Use by builder only to know what orientation were the mesh build in.
  30498. /** @hidden */
  30499. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30500. _this.overrideMaterialSideOrientation = null;
  30501. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30502. // Will be used to save a source mesh reference, If any
  30503. _this._source = null;
  30504. scene = _this.getScene();
  30505. if (source) {
  30506. // Geometry
  30507. if (source._geometry) {
  30508. source._geometry.applyToMesh(_this);
  30509. }
  30510. // Deep copy
  30511. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30512. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  30513. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  30514. ], ["_poseMatrix"]);
  30515. // Source mesh
  30516. _this._source = source;
  30517. // Construction Params
  30518. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  30519. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  30520. var myAnyThis = _this;
  30521. var myAnySource = source;
  30522. myAnyThis._closePath = myAnySource._closePath;
  30523. myAnyThis._idx = myAnySource._idx;
  30524. myAnyThis.dashSize = myAnySource.dashSize;
  30525. myAnyThis.gapSize = myAnySource.gapSize;
  30526. myAnyThis.path3D = myAnySource.path3D;
  30527. myAnyThis.pathArray = myAnySource.pathArray;
  30528. myAnyThis.arc = myAnySource.arc;
  30529. myAnyThis.radius = myAnySource.radius;
  30530. // Animation ranges
  30531. if (_this._source._ranges) {
  30532. var ranges = _this._source._ranges;
  30533. for (var name in ranges) {
  30534. if (!ranges.hasOwnProperty(name)) {
  30535. continue;
  30536. }
  30537. if (!ranges[name]) {
  30538. continue;
  30539. }
  30540. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  30541. }
  30542. }
  30543. // Metadata
  30544. if (source.metadata && source.metadata.clone) {
  30545. _this.metadata = source.metadata.clone();
  30546. }
  30547. else {
  30548. _this.metadata = source.metadata;
  30549. }
  30550. // Tags
  30551. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30552. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30553. }
  30554. // Parent
  30555. _this.parent = source.parent;
  30556. // Pivot
  30557. _this.setPivotMatrix(source.getPivotMatrix());
  30558. _this.id = name + "." + source.id;
  30559. // Material
  30560. _this.material = source.material;
  30561. var index;
  30562. if (!doNotCloneChildren) {
  30563. // Children
  30564. var directDescendants = source.getDescendants(true);
  30565. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30566. var child = directDescendants[index_1];
  30567. if (child.clone) {
  30568. child.clone(name + "." + child.name, _this);
  30569. }
  30570. }
  30571. }
  30572. // Physics clone
  30573. var physicsEngine = _this.getScene().getPhysicsEngine();
  30574. if (clonePhysicsImpostor && physicsEngine) {
  30575. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30576. if (impostor) {
  30577. _this.physicsImpostor = impostor.clone(_this);
  30578. }
  30579. }
  30580. // Particles
  30581. for (index = 0; index < scene.particleSystems.length; index++) {
  30582. var system = scene.particleSystems[index];
  30583. if (system.emitter === source) {
  30584. system.clone(system.name, _this);
  30585. }
  30586. }
  30587. _this.refreshBoundingInfo();
  30588. _this.computeWorldMatrix(true);
  30589. }
  30590. // Parent
  30591. if (parent !== null) {
  30592. _this.parent = parent;
  30593. }
  30594. return _this;
  30595. }
  30596. Object.defineProperty(Mesh, "FRONTSIDE", {
  30597. /**
  30598. * Mesh side orientation : usually the external or front surface
  30599. */
  30600. get: function () {
  30601. return Mesh._FRONTSIDE;
  30602. },
  30603. enumerable: true,
  30604. configurable: true
  30605. });
  30606. Object.defineProperty(Mesh, "BACKSIDE", {
  30607. /**
  30608. * Mesh side orientation : usually the internal or back surface
  30609. */
  30610. get: function () {
  30611. return Mesh._BACKSIDE;
  30612. },
  30613. enumerable: true,
  30614. configurable: true
  30615. });
  30616. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30617. /**
  30618. * Mesh side orientation : both internal and external or front and back surfaces
  30619. */
  30620. get: function () {
  30621. return Mesh._DOUBLESIDE;
  30622. },
  30623. enumerable: true,
  30624. configurable: true
  30625. });
  30626. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30627. /**
  30628. * Mesh side orientation : by default, `FRONTSIDE`
  30629. */
  30630. get: function () {
  30631. return Mesh._DEFAULTSIDE;
  30632. },
  30633. enumerable: true,
  30634. configurable: true
  30635. });
  30636. Object.defineProperty(Mesh, "NO_CAP", {
  30637. /**
  30638. * Mesh cap setting : no cap
  30639. */
  30640. get: function () {
  30641. return Mesh._NO_CAP;
  30642. },
  30643. enumerable: true,
  30644. configurable: true
  30645. });
  30646. Object.defineProperty(Mesh, "CAP_START", {
  30647. /**
  30648. * Mesh cap setting : one cap at the beginning of the mesh
  30649. */
  30650. get: function () {
  30651. return Mesh._CAP_START;
  30652. },
  30653. enumerable: true,
  30654. configurable: true
  30655. });
  30656. Object.defineProperty(Mesh, "CAP_END", {
  30657. /**
  30658. * Mesh cap setting : one cap at the end of the mesh
  30659. */
  30660. get: function () {
  30661. return Mesh._CAP_END;
  30662. },
  30663. enumerable: true,
  30664. configurable: true
  30665. });
  30666. Object.defineProperty(Mesh, "CAP_ALL", {
  30667. /**
  30668. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30669. */
  30670. get: function () {
  30671. return Mesh._CAP_ALL;
  30672. },
  30673. enumerable: true,
  30674. configurable: true
  30675. });
  30676. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  30677. /**
  30678. * An event triggered before rendering the mesh
  30679. */
  30680. get: function () {
  30681. if (!this._onBeforeRenderObservable) {
  30682. this._onBeforeRenderObservable = new BABYLON.Observable();
  30683. }
  30684. return this._onBeforeRenderObservable;
  30685. },
  30686. enumerable: true,
  30687. configurable: true
  30688. });
  30689. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  30690. /**
  30691. * An event triggered after rendering the mesh
  30692. */
  30693. get: function () {
  30694. if (!this._onAfterRenderObservable) {
  30695. this._onAfterRenderObservable = new BABYLON.Observable();
  30696. }
  30697. return this._onAfterRenderObservable;
  30698. },
  30699. enumerable: true,
  30700. configurable: true
  30701. });
  30702. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  30703. /**
  30704. * An event triggered before drawing the mesh
  30705. */
  30706. get: function () {
  30707. if (!this._onBeforeDrawObservable) {
  30708. this._onBeforeDrawObservable = new BABYLON.Observable();
  30709. }
  30710. return this._onBeforeDrawObservable;
  30711. },
  30712. enumerable: true,
  30713. configurable: true
  30714. });
  30715. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30716. set: function (callback) {
  30717. if (this._onBeforeDrawObserver) {
  30718. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30719. }
  30720. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30721. },
  30722. enumerable: true,
  30723. configurable: true
  30724. });
  30725. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30726. get: function () {
  30727. return this._morphTargetManager;
  30728. },
  30729. set: function (value) {
  30730. if (this._morphTargetManager === value) {
  30731. return;
  30732. }
  30733. this._morphTargetManager = value;
  30734. this._syncGeometryWithMorphTargetManager();
  30735. },
  30736. enumerable: true,
  30737. configurable: true
  30738. });
  30739. Object.defineProperty(Mesh.prototype, "source", {
  30740. get: function () {
  30741. return this._source;
  30742. },
  30743. enumerable: true,
  30744. configurable: true
  30745. });
  30746. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30747. get: function () {
  30748. return this._unIndexed;
  30749. },
  30750. set: function (value) {
  30751. if (this._unIndexed !== value) {
  30752. this._unIndexed = value;
  30753. this._markSubMeshesAsAttributesDirty();
  30754. }
  30755. },
  30756. enumerable: true,
  30757. configurable: true
  30758. });
  30759. // Methods
  30760. /**
  30761. * Returns the string "Mesh".
  30762. */
  30763. Mesh.prototype.getClassName = function () {
  30764. return "Mesh";
  30765. };
  30766. /**
  30767. * Returns a string.
  30768. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30769. */
  30770. Mesh.prototype.toString = function (fullDetails) {
  30771. var ret = _super.prototype.toString.call(this, fullDetails);
  30772. ret += ", n vertices: " + this.getTotalVertices();
  30773. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30774. if (this.animations) {
  30775. for (var i = 0; i < this.animations.length; i++) {
  30776. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30777. }
  30778. }
  30779. if (fullDetails) {
  30780. if (this._geometry) {
  30781. var ib = this.getIndices();
  30782. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30783. if (vb && ib) {
  30784. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30785. }
  30786. }
  30787. else {
  30788. ret += ", flat shading: UNKNOWN";
  30789. }
  30790. }
  30791. return ret;
  30792. };
  30793. /** @hidden */
  30794. Mesh.prototype._unBindEffect = function () {
  30795. _super.prototype._unBindEffect.call(this);
  30796. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  30797. var instance = _a[_i];
  30798. instance._unBindEffect();
  30799. }
  30800. };
  30801. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30802. /**
  30803. * True if the mesh has some Levels Of Details (LOD).
  30804. * Returns a boolean.
  30805. */
  30806. get: function () {
  30807. return this._LODLevels.length > 0;
  30808. },
  30809. enumerable: true,
  30810. configurable: true
  30811. });
  30812. /**
  30813. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30814. * @returns an array of {BABYLON.MeshLODLevel}
  30815. */
  30816. Mesh.prototype.getLODLevels = function () {
  30817. return this._LODLevels;
  30818. };
  30819. Mesh.prototype._sortLODLevels = function () {
  30820. this._LODLevels.sort(function (a, b) {
  30821. if (a.distance < b.distance) {
  30822. return 1;
  30823. }
  30824. if (a.distance > b.distance) {
  30825. return -1;
  30826. }
  30827. return 0;
  30828. });
  30829. };
  30830. /**
  30831. * Add a mesh as LOD level triggered at the given distance.
  30832. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30833. * @param distance The distance from the center of the object to show this level
  30834. * @param mesh The mesh to be added as LOD level (can be null)
  30835. * @return This mesh (for chaining)
  30836. */
  30837. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30838. if (mesh && mesh._masterMesh) {
  30839. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30840. return this;
  30841. }
  30842. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30843. this._LODLevels.push(level);
  30844. if (mesh) {
  30845. mesh._masterMesh = this;
  30846. }
  30847. this._sortLODLevels();
  30848. return this;
  30849. };
  30850. /**
  30851. * Returns the LOD level mesh at the passed distance or null if not found.
  30852. * It is related to the method `addLODLevel(distance, mesh)`.
  30853. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30854. * Returns an object Mesh or `null`.
  30855. */
  30856. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30857. for (var index = 0; index < this._LODLevels.length; index++) {
  30858. var level = this._LODLevels[index];
  30859. if (level.distance === distance) {
  30860. return level.mesh;
  30861. }
  30862. }
  30863. return null;
  30864. };
  30865. /**
  30866. * Remove a mesh from the LOD array
  30867. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30868. * @param {Mesh} mesh The mesh to be removed.
  30869. * @return {Mesh} This mesh (for chaining)
  30870. */
  30871. Mesh.prototype.removeLODLevel = function (mesh) {
  30872. for (var index = 0; index < this._LODLevels.length; index++) {
  30873. if (this._LODLevels[index].mesh === mesh) {
  30874. this._LODLevels.splice(index, 1);
  30875. if (mesh) {
  30876. mesh._masterMesh = null;
  30877. }
  30878. }
  30879. }
  30880. this._sortLODLevels();
  30881. return this;
  30882. };
  30883. /**
  30884. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30885. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  30886. */
  30887. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30888. if (!this._LODLevels || this._LODLevels.length === 0) {
  30889. return this;
  30890. }
  30891. var bSphere;
  30892. if (boundingSphere) {
  30893. bSphere = boundingSphere;
  30894. }
  30895. else {
  30896. var boundingInfo = this.getBoundingInfo();
  30897. bSphere = boundingInfo.boundingSphere;
  30898. }
  30899. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  30900. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  30901. if (this.onLODLevelSelection) {
  30902. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  30903. }
  30904. return this;
  30905. }
  30906. for (var index = 0; index < this._LODLevels.length; index++) {
  30907. var level = this._LODLevels[index];
  30908. if (level.distance < distanceToCamera) {
  30909. if (level.mesh) {
  30910. level.mesh._preActivate();
  30911. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  30912. }
  30913. if (this.onLODLevelSelection) {
  30914. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  30915. }
  30916. return level.mesh;
  30917. }
  30918. }
  30919. if (this.onLODLevelSelection) {
  30920. this.onLODLevelSelection(distanceToCamera, this, this);
  30921. }
  30922. return this;
  30923. };
  30924. Object.defineProperty(Mesh.prototype, "geometry", {
  30925. /**
  30926. * Returns the mesh internal Geometry object.
  30927. */
  30928. get: function () {
  30929. return this._geometry;
  30930. },
  30931. enumerable: true,
  30932. configurable: true
  30933. });
  30934. /**
  30935. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  30936. */
  30937. Mesh.prototype.getTotalVertices = function () {
  30938. if (this._geometry === null || this._geometry === undefined) {
  30939. return 0;
  30940. }
  30941. return this._geometry.getTotalVertices();
  30942. };
  30943. /**
  30944. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  30945. * 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.
  30946. * You can force the copy with forceCopy === true
  30947. * Returns null if the mesh has no geometry or no vertex buffer.
  30948. * Possible `kind` values :
  30949. * - BABYLON.VertexBuffer.PositionKind
  30950. * - BABYLON.VertexBuffer.UVKind
  30951. * - BABYLON.VertexBuffer.UV2Kind
  30952. * - BABYLON.VertexBuffer.UV3Kind
  30953. * - BABYLON.VertexBuffer.UV4Kind
  30954. * - BABYLON.VertexBuffer.UV5Kind
  30955. * - BABYLON.VertexBuffer.UV6Kind
  30956. * - BABYLON.VertexBuffer.ColorKind
  30957. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30958. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30959. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30960. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30961. */
  30962. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30963. if (!this._geometry) {
  30964. return null;
  30965. }
  30966. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  30967. };
  30968. /**
  30969. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  30970. * Returns `null` if the mesh has no geometry.
  30971. * Possible `kind` values :
  30972. * - BABYLON.VertexBuffer.PositionKind
  30973. * - BABYLON.VertexBuffer.UVKind
  30974. * - BABYLON.VertexBuffer.UV2Kind
  30975. * - BABYLON.VertexBuffer.UV3Kind
  30976. * - BABYLON.VertexBuffer.UV4Kind
  30977. * - BABYLON.VertexBuffer.UV5Kind
  30978. * - BABYLON.VertexBuffer.UV6Kind
  30979. * - BABYLON.VertexBuffer.ColorKind
  30980. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30981. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30982. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30983. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30984. */
  30985. Mesh.prototype.getVertexBuffer = function (kind) {
  30986. if (!this._geometry) {
  30987. return null;
  30988. }
  30989. return this._geometry.getVertexBuffer(kind);
  30990. };
  30991. Mesh.prototype.isVerticesDataPresent = function (kind) {
  30992. if (!this._geometry) {
  30993. if (this._delayInfo) {
  30994. return this._delayInfo.indexOf(kind) !== -1;
  30995. }
  30996. return false;
  30997. }
  30998. return this._geometry.isVerticesDataPresent(kind);
  30999. };
  31000. /**
  31001. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31002. * Possible `kind` values :
  31003. * - BABYLON.VertexBuffer.PositionKind
  31004. * - BABYLON.VertexBuffer.UVKind
  31005. * - BABYLON.VertexBuffer.UV2Kind
  31006. * - BABYLON.VertexBuffer.UV3Kind
  31007. * - BABYLON.VertexBuffer.UV4Kind
  31008. * - BABYLON.VertexBuffer.UV5Kind
  31009. * - BABYLON.VertexBuffer.UV6Kind
  31010. * - BABYLON.VertexBuffer.ColorKind
  31011. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31012. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31013. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31014. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31015. */
  31016. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31017. if (!this._geometry) {
  31018. if (this._delayInfo) {
  31019. return this._delayInfo.indexOf(kind) !== -1;
  31020. }
  31021. return false;
  31022. }
  31023. return this._geometry.isVertexBufferUpdatable(kind);
  31024. };
  31025. /**
  31026. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31027. * Possible `kind` values :
  31028. * - BABYLON.VertexBuffer.PositionKind
  31029. * - BABYLON.VertexBuffer.UVKind
  31030. * - BABYLON.VertexBuffer.UV2Kind
  31031. * - BABYLON.VertexBuffer.UV3Kind
  31032. * - BABYLON.VertexBuffer.UV4Kind
  31033. * - BABYLON.VertexBuffer.UV5Kind
  31034. * - BABYLON.VertexBuffer.UV6Kind
  31035. * - BABYLON.VertexBuffer.ColorKind
  31036. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31037. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31038. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31039. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31040. */
  31041. Mesh.prototype.getVerticesDataKinds = function () {
  31042. if (!this._geometry) {
  31043. var result = new Array();
  31044. if (this._delayInfo) {
  31045. this._delayInfo.forEach(function (kind, index, array) {
  31046. result.push(kind);
  31047. });
  31048. }
  31049. return result;
  31050. }
  31051. return this._geometry.getVerticesDataKinds();
  31052. };
  31053. /**
  31054. * Returns a positive integer : the total number of indices in this mesh geometry.
  31055. * Returns zero if the mesh has no geometry.
  31056. */
  31057. Mesh.prototype.getTotalIndices = function () {
  31058. if (!this._geometry) {
  31059. return 0;
  31060. }
  31061. return this._geometry.getTotalIndices();
  31062. };
  31063. /**
  31064. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31065. * @param copyWhenShared If 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.
  31066. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31067. * @returns the indices array or an empty array if the mesh has no geometry
  31068. */
  31069. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31070. if (!this._geometry) {
  31071. return [];
  31072. }
  31073. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31074. };
  31075. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31076. get: function () {
  31077. return this._masterMesh !== null && this._masterMesh !== undefined;
  31078. },
  31079. enumerable: true,
  31080. configurable: true
  31081. });
  31082. /**
  31083. * Determine if the current mesh is ready to be rendered
  31084. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31085. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31086. * @returns true if all associated assets are ready (material, textures, shaders)
  31087. */
  31088. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31089. if (completeCheck === void 0) { completeCheck = false; }
  31090. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31091. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31092. return false;
  31093. }
  31094. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31095. return false;
  31096. }
  31097. if (!this.subMeshes || this.subMeshes.length === 0) {
  31098. return true;
  31099. }
  31100. if (!completeCheck) {
  31101. return true;
  31102. }
  31103. var engine = this.getEngine();
  31104. var scene = this.getScene();
  31105. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31106. this.computeWorldMatrix();
  31107. var mat = this.material || scene.defaultMaterial;
  31108. if (mat) {
  31109. if (mat.storeEffectOnSubMeshes) {
  31110. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31111. var subMesh = _a[_i];
  31112. var effectiveMaterial = subMesh.getMaterial();
  31113. if (effectiveMaterial) {
  31114. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31115. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31116. return false;
  31117. }
  31118. }
  31119. else {
  31120. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31121. return false;
  31122. }
  31123. }
  31124. }
  31125. }
  31126. }
  31127. else {
  31128. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31129. return false;
  31130. }
  31131. }
  31132. }
  31133. // Shadows
  31134. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31135. var light = _c[_b];
  31136. var generator = light.getShadowGenerator();
  31137. if (generator) {
  31138. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31139. var subMesh = _e[_d];
  31140. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31141. return false;
  31142. }
  31143. }
  31144. }
  31145. }
  31146. // LOD
  31147. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31148. var lod = _g[_f];
  31149. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31150. return false;
  31151. }
  31152. }
  31153. return true;
  31154. };
  31155. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31156. /**
  31157. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31158. * This property is pertinent only for updatable parametric shapes.
  31159. */
  31160. get: function () {
  31161. return this._areNormalsFrozen;
  31162. },
  31163. enumerable: true,
  31164. configurable: true
  31165. });
  31166. /**
  31167. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31168. * It has no effect at all on other shapes.
  31169. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31170. * Returns the Mesh.
  31171. */
  31172. Mesh.prototype.freezeNormals = function () {
  31173. this._areNormalsFrozen = true;
  31174. return this;
  31175. };
  31176. /**
  31177. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31178. * It has no effect at all on other shapes.
  31179. * It reactivates the mesh normals computation if it was previously frozen.
  31180. * Returns the Mesh.
  31181. */
  31182. Mesh.prototype.unfreezeNormals = function () {
  31183. this._areNormalsFrozen = false;
  31184. return this;
  31185. };
  31186. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31187. /**
  31188. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31189. */
  31190. set: function (count) {
  31191. this._overridenInstanceCount = count;
  31192. },
  31193. enumerable: true,
  31194. configurable: true
  31195. });
  31196. // Methods
  31197. /** @hidden */
  31198. Mesh.prototype._preActivate = function () {
  31199. var sceneRenderId = this.getScene().getRenderId();
  31200. if (this._preActivateId === sceneRenderId) {
  31201. return this;
  31202. }
  31203. this._preActivateId = sceneRenderId;
  31204. this._visibleInstances = null;
  31205. return this;
  31206. };
  31207. /** @hidden */
  31208. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31209. if (this._visibleInstances) {
  31210. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31211. }
  31212. return this;
  31213. };
  31214. /** @hidden */
  31215. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31216. if (!this._visibleInstances) {
  31217. this._visibleInstances = {};
  31218. this._visibleInstances.defaultRenderId = renderId;
  31219. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31220. }
  31221. if (!this._visibleInstances[renderId]) {
  31222. this._visibleInstances[renderId] = new Array();
  31223. }
  31224. this._visibleInstances[renderId].push(instance);
  31225. return this;
  31226. };
  31227. /**
  31228. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31229. * This means the mesh underlying bounding box and sphere are recomputed.
  31230. * Returns the Mesh.
  31231. */
  31232. Mesh.prototype.refreshBoundingInfo = function () {
  31233. return this._refreshBoundingInfo(false);
  31234. };
  31235. /** @hidden */
  31236. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31237. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31238. return this;
  31239. }
  31240. var data = this._getPositionData(applySkeleton);
  31241. if (data) {
  31242. var bias = this.geometry ? this.geometry.boundingBias : null;
  31243. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31244. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31245. }
  31246. if (this.subMeshes) {
  31247. for (var index = 0; index < this.subMeshes.length; index++) {
  31248. this.subMeshes[index].refreshBoundingInfo();
  31249. }
  31250. }
  31251. this._updateBoundingInfo();
  31252. return this;
  31253. };
  31254. Mesh.prototype._getPositionData = function (applySkeleton) {
  31255. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31256. if (data && applySkeleton && this.skeleton) {
  31257. data = BABYLON.Tools.Slice(data);
  31258. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31259. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31260. if (matricesWeightsData && matricesIndicesData) {
  31261. var needExtras = this.numBoneInfluencers > 4;
  31262. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31263. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31264. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31265. var tempVector = BABYLON.Tmp.Vector3[0];
  31266. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31267. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31268. var matWeightIdx = 0;
  31269. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31270. finalMatrix.reset();
  31271. var inf;
  31272. var weight;
  31273. for (inf = 0; inf < 4; inf++) {
  31274. weight = matricesWeightsData[matWeightIdx + inf];
  31275. if (weight > 0) {
  31276. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31277. finalMatrix.addToSelf(tempMatrix);
  31278. }
  31279. }
  31280. if (needExtras) {
  31281. for (inf = 0; inf < 4; inf++) {
  31282. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31283. if (weight > 0) {
  31284. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31285. finalMatrix.addToSelf(tempMatrix);
  31286. }
  31287. }
  31288. }
  31289. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31290. tempVector.toArray(data, index);
  31291. }
  31292. }
  31293. }
  31294. return data;
  31295. };
  31296. /** @hidden */
  31297. Mesh.prototype._createGlobalSubMesh = function (force) {
  31298. var totalVertices = this.getTotalVertices();
  31299. if (!totalVertices || !this.getIndices()) {
  31300. return null;
  31301. }
  31302. // Check if we need to recreate the submeshes
  31303. if (this.subMeshes && this.subMeshes.length > 0) {
  31304. var ib = this.getIndices();
  31305. if (!ib) {
  31306. return null;
  31307. }
  31308. var totalIndices = ib.length;
  31309. var needToRecreate = false;
  31310. if (force) {
  31311. needToRecreate = true;
  31312. }
  31313. else {
  31314. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31315. var submesh = _a[_i];
  31316. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31317. needToRecreate = true;
  31318. break;
  31319. }
  31320. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31321. needToRecreate = true;
  31322. break;
  31323. }
  31324. }
  31325. }
  31326. if (!needToRecreate) {
  31327. return this.subMeshes[0];
  31328. }
  31329. }
  31330. this.releaseSubMeshes();
  31331. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31332. };
  31333. Mesh.prototype.subdivide = function (count) {
  31334. if (count < 1) {
  31335. return;
  31336. }
  31337. var totalIndices = this.getTotalIndices();
  31338. var subdivisionSize = (totalIndices / count) | 0;
  31339. var offset = 0;
  31340. // Ensure that subdivisionSize is a multiple of 3
  31341. while (subdivisionSize % 3 !== 0) {
  31342. subdivisionSize++;
  31343. }
  31344. this.releaseSubMeshes();
  31345. for (var index = 0; index < count; index++) {
  31346. if (offset >= totalIndices) {
  31347. break;
  31348. }
  31349. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31350. offset += subdivisionSize;
  31351. }
  31352. this.synchronizeInstances();
  31353. };
  31354. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31355. if (updatable === void 0) { updatable = false; }
  31356. if (!this._geometry) {
  31357. var vertexData = new BABYLON.VertexData();
  31358. vertexData.set(data, kind);
  31359. var scene = this.getScene();
  31360. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31361. }
  31362. else {
  31363. this._geometry.setVerticesData(kind, data, updatable, stride);
  31364. }
  31365. return this;
  31366. };
  31367. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31368. if (updatable === void 0) { updatable = true; }
  31369. var vb = this.getVertexBuffer(kind);
  31370. if (!vb || vb.isUpdatable() === updatable) {
  31371. return;
  31372. }
  31373. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31374. };
  31375. /**
  31376. * Sets the mesh VertexBuffer.
  31377. * Returns the Mesh.
  31378. */
  31379. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31380. if (!this._geometry) {
  31381. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31382. }
  31383. this._geometry.setVerticesBuffer(buffer);
  31384. return this;
  31385. };
  31386. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31387. if (!this._geometry) {
  31388. return this;
  31389. }
  31390. if (!makeItUnique) {
  31391. this._geometry.updateVerticesData(kind, data, updateExtends);
  31392. }
  31393. else {
  31394. this.makeGeometryUnique();
  31395. this.updateVerticesData(kind, data, updateExtends, false);
  31396. }
  31397. return this;
  31398. };
  31399. /**
  31400. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31401. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31402. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31403. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31404. * Returns the Mesh.
  31405. */
  31406. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31407. if (computeNormals === void 0) { computeNormals = true; }
  31408. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31409. if (!positions) {
  31410. return this;
  31411. }
  31412. positionFunction(positions);
  31413. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31414. if (computeNormals) {
  31415. var indices = this.getIndices();
  31416. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31417. if (!normals) {
  31418. return this;
  31419. }
  31420. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31421. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31422. }
  31423. return this;
  31424. };
  31425. /**
  31426. * Creates a un-shared specific occurence of the geometry for the mesh.
  31427. * Returns the Mesh.
  31428. */
  31429. Mesh.prototype.makeGeometryUnique = function () {
  31430. if (!this._geometry) {
  31431. return this;
  31432. }
  31433. var oldGeometry = this._geometry;
  31434. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31435. oldGeometry.releaseForMesh(this, true);
  31436. geometry.applyToMesh(this);
  31437. return this;
  31438. };
  31439. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31440. if (totalVertices === void 0) { totalVertices = null; }
  31441. if (updatable === void 0) { updatable = false; }
  31442. if (!this._geometry) {
  31443. var vertexData = new BABYLON.VertexData();
  31444. vertexData.indices = indices;
  31445. var scene = this.getScene();
  31446. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31447. }
  31448. else {
  31449. this._geometry.setIndices(indices, totalVertices, updatable);
  31450. }
  31451. return this;
  31452. };
  31453. /**
  31454. * Update the current index buffer
  31455. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31456. * Returns the Mesh.
  31457. */
  31458. Mesh.prototype.updateIndices = function (indices, offset) {
  31459. if (!this._geometry) {
  31460. return this;
  31461. }
  31462. this._geometry.updateIndices(indices, offset);
  31463. return this;
  31464. };
  31465. /**
  31466. * Invert the geometry to move from a right handed system to a left handed one.
  31467. * Returns the Mesh.
  31468. */
  31469. Mesh.prototype.toLeftHanded = function () {
  31470. if (!this._geometry) {
  31471. return this;
  31472. }
  31473. this._geometry.toLeftHanded();
  31474. return this;
  31475. };
  31476. /** @hidden */
  31477. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31478. if (!this._geometry) {
  31479. return this;
  31480. }
  31481. var engine = this.getScene().getEngine();
  31482. // Wireframe
  31483. var indexToBind;
  31484. if (this._unIndexed) {
  31485. indexToBind = null;
  31486. }
  31487. else {
  31488. switch (fillMode) {
  31489. case BABYLON.Material.PointFillMode:
  31490. indexToBind = null;
  31491. break;
  31492. case BABYLON.Material.WireFrameFillMode:
  31493. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31494. break;
  31495. default:
  31496. case BABYLON.Material.TriangleFillMode:
  31497. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31498. break;
  31499. }
  31500. }
  31501. // VBOs
  31502. this._geometry._bind(effect, indexToBind);
  31503. return this;
  31504. };
  31505. /** @hidden */
  31506. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31507. if (alternate === void 0) { alternate = false; }
  31508. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31509. return this;
  31510. }
  31511. if (this._onBeforeDrawObservable) {
  31512. this._onBeforeDrawObservable.notifyObservers(this);
  31513. }
  31514. var scene = this.getScene();
  31515. var engine = scene.getEngine();
  31516. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31517. // or triangles as points
  31518. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31519. }
  31520. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31521. // Triangles as wireframe
  31522. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31523. }
  31524. else {
  31525. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31526. }
  31527. if (scene._isAlternateRenderingEnabled && !alternate) {
  31528. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31529. if (!effect || !scene.activeCamera) {
  31530. return this;
  31531. }
  31532. scene._switchToAlternateCameraConfiguration(true);
  31533. this._effectiveMaterial.bindView(effect);
  31534. this._effectiveMaterial.bindViewProjection(effect);
  31535. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31536. this._draw(subMesh, fillMode, instancesCount, true);
  31537. engine.setViewport(scene.activeCamera.viewport);
  31538. scene._switchToAlternateCameraConfiguration(false);
  31539. this._effectiveMaterial.bindView(effect);
  31540. this._effectiveMaterial.bindViewProjection(effect);
  31541. }
  31542. return this;
  31543. };
  31544. /**
  31545. * Registers for this mesh a javascript function called just before the rendering process.
  31546. * This function is passed the current mesh.
  31547. * Return the Mesh.
  31548. */
  31549. Mesh.prototype.registerBeforeRender = function (func) {
  31550. this.onBeforeRenderObservable.add(func);
  31551. return this;
  31552. };
  31553. /**
  31554. * Disposes a previously registered javascript function called before the rendering.
  31555. * This function is passed the current mesh.
  31556. * Returns the Mesh.
  31557. */
  31558. Mesh.prototype.unregisterBeforeRender = function (func) {
  31559. this.onBeforeRenderObservable.removeCallback(func);
  31560. return this;
  31561. };
  31562. /**
  31563. * Registers for this mesh a javascript function called just after the rendering is complete.
  31564. * This function is passed the current mesh.
  31565. * Returns the Mesh.
  31566. */
  31567. Mesh.prototype.registerAfterRender = function (func) {
  31568. this.onAfterRenderObservable.add(func);
  31569. return this;
  31570. };
  31571. /**
  31572. * Disposes a previously registered javascript function called after the rendering.
  31573. * This function is passed the current mesh.
  31574. * Return the Mesh.
  31575. */
  31576. Mesh.prototype.unregisterAfterRender = function (func) {
  31577. this.onAfterRenderObservable.removeCallback(func);
  31578. return this;
  31579. };
  31580. /** @hidden */
  31581. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31582. var scene = this.getScene();
  31583. this._batchCache.mustReturn = false;
  31584. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31585. this._batchCache.visibleInstances[subMeshId] = null;
  31586. if (this._visibleInstances) {
  31587. var currentRenderId = scene.getRenderId();
  31588. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31589. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31590. var selfRenderId = this._renderId;
  31591. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31592. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31593. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31594. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31595. }
  31596. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31597. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31598. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31599. this._batchCache.mustReturn = true;
  31600. return this._batchCache;
  31601. }
  31602. if (currentRenderId !== selfRenderId) {
  31603. this._batchCache.renderSelf[subMeshId] = false;
  31604. }
  31605. }
  31606. this._renderIdForInstances[subMeshId] = currentRenderId;
  31607. }
  31608. return this._batchCache;
  31609. };
  31610. /** @hidden */
  31611. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31612. var visibleInstances = batch.visibleInstances[subMesh._id];
  31613. if (!visibleInstances) {
  31614. return this;
  31615. }
  31616. var matricesCount = visibleInstances.length + 1;
  31617. var bufferSize = matricesCount * 16 * 4;
  31618. var currentInstancesBufferSize = this._instancesBufferSize;
  31619. var instancesBuffer = this._instancesBuffer;
  31620. while (this._instancesBufferSize < bufferSize) {
  31621. this._instancesBufferSize *= 2;
  31622. }
  31623. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31624. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31625. }
  31626. var offset = 0;
  31627. var instancesCount = 0;
  31628. var world = this.getWorldMatrix();
  31629. if (batch.renderSelf[subMesh._id]) {
  31630. world.copyToArray(this._instancesData, offset);
  31631. offset += 16;
  31632. instancesCount++;
  31633. }
  31634. if (visibleInstances) {
  31635. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31636. var instance = visibleInstances[instanceIndex];
  31637. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31638. offset += 16;
  31639. instancesCount++;
  31640. }
  31641. }
  31642. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31643. if (instancesBuffer) {
  31644. instancesBuffer.dispose();
  31645. }
  31646. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31647. this._instancesBuffer = instancesBuffer;
  31648. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31649. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31650. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31651. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31652. }
  31653. else {
  31654. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31655. }
  31656. this._bind(subMesh, effect, fillMode);
  31657. this._draw(subMesh, fillMode, instancesCount);
  31658. engine.unbindInstanceAttributes();
  31659. return this;
  31660. };
  31661. /** @hidden */
  31662. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31663. var scene = this.getScene();
  31664. var engine = scene.getEngine();
  31665. if (hardwareInstancedRendering) {
  31666. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31667. }
  31668. else {
  31669. if (batch.renderSelf[subMesh._id]) {
  31670. // Draw
  31671. if (onBeforeDraw) {
  31672. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31673. }
  31674. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31675. }
  31676. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31677. if (visibleInstancesForSubMesh) {
  31678. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31679. var instance = visibleInstancesForSubMesh[instanceIndex];
  31680. // World
  31681. var world = instance.getWorldMatrix();
  31682. if (onBeforeDraw) {
  31683. onBeforeDraw(true, world, effectiveMaterial);
  31684. }
  31685. // Draw
  31686. this._draw(subMesh, fillMode);
  31687. }
  31688. }
  31689. }
  31690. return this;
  31691. };
  31692. /**
  31693. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  31694. * @param subMesh defines the subMesh to render
  31695. * @param enableAlphaMode defines if alpha mode can be changed
  31696. * @returns the current mesh
  31697. */
  31698. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31699. this._checkOcclusionQuery();
  31700. if (this._isOccluded) {
  31701. return this;
  31702. }
  31703. var scene = this.getScene();
  31704. // Managing instances
  31705. var batch = this._getInstancesRenderList(subMesh._id);
  31706. if (batch.mustReturn) {
  31707. return this;
  31708. }
  31709. // Checking geometry state
  31710. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31711. return this;
  31712. }
  31713. if (this._onBeforeRenderObservable) {
  31714. this._onBeforeRenderObservable.notifyObservers(this);
  31715. }
  31716. var engine = scene.getEngine();
  31717. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31718. // Material
  31719. var material = subMesh.getMaterial();
  31720. if (!material) {
  31721. return this;
  31722. }
  31723. this._effectiveMaterial = material;
  31724. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31725. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31726. return this;
  31727. }
  31728. }
  31729. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31730. return this;
  31731. }
  31732. // Alpha mode
  31733. if (enableAlphaMode) {
  31734. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31735. }
  31736. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  31737. var step = _a[_i];
  31738. step.action(this, subMesh, batch);
  31739. }
  31740. var effect;
  31741. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31742. effect = subMesh.effect;
  31743. }
  31744. else {
  31745. effect = this._effectiveMaterial.getEffect();
  31746. }
  31747. if (!effect) {
  31748. return this;
  31749. }
  31750. var sideOrientation = this.overrideMaterialSideOrientation;
  31751. if (sideOrientation == null) {
  31752. sideOrientation = this._effectiveMaterial.sideOrientation;
  31753. if (this._getWorldMatrixDeterminant() < 0) {
  31754. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31755. }
  31756. }
  31757. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31758. if (this._effectiveMaterial.forceDepthWrite) {
  31759. engine.setDepthWrite(true);
  31760. }
  31761. // Bind
  31762. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31763. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  31764. this._bind(subMesh, effect, fillMode);
  31765. }
  31766. var world = this.getWorldMatrix();
  31767. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31768. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31769. }
  31770. else {
  31771. this._effectiveMaterial.bind(world, this);
  31772. }
  31773. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31774. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31775. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31776. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31777. }
  31778. // Draw
  31779. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31780. // Unbind
  31781. this._effectiveMaterial.unbind();
  31782. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  31783. var step = _c[_b];
  31784. step.action(this, subMesh, batch);
  31785. }
  31786. if (this._onAfterRenderObservable) {
  31787. this._onAfterRenderObservable.notifyObservers(this);
  31788. }
  31789. return this;
  31790. };
  31791. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31792. if (isInstance && effectiveMaterial) {
  31793. effectiveMaterial.bindOnlyWorldMatrix(world);
  31794. }
  31795. };
  31796. /**
  31797. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  31798. */
  31799. Mesh.prototype.getEmittedParticleSystems = function () {
  31800. var results = new Array();
  31801. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31802. var particleSystem = this.getScene().particleSystems[index];
  31803. if (particleSystem.emitter === this) {
  31804. results.push(particleSystem);
  31805. }
  31806. }
  31807. return results;
  31808. };
  31809. /**
  31810. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  31811. */
  31812. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31813. var results = new Array();
  31814. var descendants = this.getDescendants();
  31815. descendants.push(this);
  31816. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31817. var particleSystem = this.getScene().particleSystems[index];
  31818. var emitter = particleSystem.emitter;
  31819. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31820. results.push(particleSystem);
  31821. }
  31822. }
  31823. return results;
  31824. };
  31825. /**
  31826. * Normalize matrix weights so that all vertices have a total weight set to 1
  31827. */
  31828. Mesh.prototype.cleanMatrixWeights = function () {
  31829. var epsilon = 1e-3;
  31830. var noInfluenceBoneIndex = 0.0;
  31831. if (this.skeleton) {
  31832. noInfluenceBoneIndex = this.skeleton.bones.length;
  31833. }
  31834. else {
  31835. return;
  31836. }
  31837. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31838. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31839. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31840. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31841. var influencers = this.numBoneInfluencers;
  31842. var size = matricesWeights.length;
  31843. for (var i = 0; i < size; i += 4) {
  31844. var weight = 0.0;
  31845. var firstZeroWeight = -1;
  31846. for (var j = 0; j < 4; j++) {
  31847. var w = matricesWeights[i + j];
  31848. weight += w;
  31849. if (w < epsilon && firstZeroWeight < 0) {
  31850. firstZeroWeight = j;
  31851. }
  31852. }
  31853. if (matricesWeightsExtra) {
  31854. for (var j = 0; j < 4; j++) {
  31855. var w = matricesWeightsExtra[i + j];
  31856. weight += w;
  31857. if (w < epsilon && firstZeroWeight < 0) {
  31858. firstZeroWeight = j + 4;
  31859. }
  31860. }
  31861. }
  31862. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31863. firstZeroWeight = influencers - 1;
  31864. }
  31865. if (weight > epsilon) {
  31866. var mweight = 1.0 / weight;
  31867. for (var j = 0; j < 4; j++) {
  31868. matricesWeights[i + j] *= mweight;
  31869. }
  31870. if (matricesWeightsExtra) {
  31871. for (var j = 0; j < 4; j++) {
  31872. matricesWeightsExtra[i + j] *= mweight;
  31873. }
  31874. }
  31875. }
  31876. else {
  31877. if (firstZeroWeight >= 4) {
  31878. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31879. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31880. }
  31881. else {
  31882. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31883. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31884. }
  31885. }
  31886. }
  31887. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31888. if (matricesIndicesExtra) {
  31889. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31890. }
  31891. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  31892. if (matricesWeightsExtra) {
  31893. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  31894. }
  31895. };
  31896. /** @hidden */
  31897. Mesh.prototype._checkDelayState = function () {
  31898. var scene = this.getScene();
  31899. if (this._geometry) {
  31900. this._geometry.load(scene);
  31901. }
  31902. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31903. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31904. this._queueLoad(scene);
  31905. }
  31906. return this;
  31907. };
  31908. Mesh.prototype._queueLoad = function (scene) {
  31909. var _this = this;
  31910. scene._addPendingData(this);
  31911. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31912. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31913. if (data instanceof ArrayBuffer) {
  31914. _this._delayLoadingFunction(data, _this);
  31915. }
  31916. else {
  31917. _this._delayLoadingFunction(JSON.parse(data), _this);
  31918. }
  31919. _this.instances.forEach(function (instance) {
  31920. instance._syncSubMeshes();
  31921. });
  31922. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31923. scene._removePendingData(_this);
  31924. }, function () { }, scene.database, getBinaryData);
  31925. return this;
  31926. };
  31927. /**
  31928. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  31929. * A mesh is in the frustum if its bounding box intersects the frustum
  31930. * @param frustumPlanes defines the frustum to test
  31931. * @returns true if the mesh is in the frustum planes
  31932. */
  31933. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31934. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31935. return false;
  31936. }
  31937. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31938. return false;
  31939. }
  31940. this._checkDelayState();
  31941. return true;
  31942. };
  31943. /**
  31944. * Sets the mesh material by the material or multiMaterial `id` property.
  31945. * The material `id` is a string identifying the material or the multiMaterial.
  31946. * This method returns the Mesh.
  31947. */
  31948. Mesh.prototype.setMaterialByID = function (id) {
  31949. var materials = this.getScene().materials;
  31950. var index;
  31951. for (index = materials.length - 1; index > -1; index--) {
  31952. if (materials[index].id === id) {
  31953. this.material = materials[index];
  31954. return this;
  31955. }
  31956. }
  31957. // Multi
  31958. var multiMaterials = this.getScene().multiMaterials;
  31959. for (index = multiMaterials.length - 1; index > -1; index--) {
  31960. if (multiMaterials[index].id === id) {
  31961. this.material = multiMaterials[index];
  31962. return this;
  31963. }
  31964. }
  31965. return this;
  31966. };
  31967. /**
  31968. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  31969. */
  31970. Mesh.prototype.getAnimatables = function () {
  31971. var results = new Array();
  31972. if (this.material) {
  31973. results.push(this.material);
  31974. }
  31975. if (this.skeleton) {
  31976. results.push(this.skeleton);
  31977. }
  31978. return results;
  31979. };
  31980. /**
  31981. * Modifies the mesh geometry according to the passed transformation matrix.
  31982. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  31983. * The mesh normals are modified using the same transformation.
  31984. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  31985. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31986. * Returns the Mesh.
  31987. */
  31988. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  31989. // Position
  31990. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31991. return this;
  31992. }
  31993. var submeshes = this.subMeshes.splice(0);
  31994. this._resetPointsArrayCache();
  31995. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31996. var temp = new Array();
  31997. var index;
  31998. for (index = 0; index < data.length; index += 3) {
  31999. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32000. }
  32001. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32002. // Normals
  32003. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32004. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32005. temp = [];
  32006. for (index = 0; index < data.length; index += 3) {
  32007. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32008. }
  32009. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32010. }
  32011. // flip faces?
  32012. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32013. this.flipFaces();
  32014. }
  32015. // Restore submeshes
  32016. this.releaseSubMeshes();
  32017. this.subMeshes = submeshes;
  32018. return this;
  32019. };
  32020. /**
  32021. * Modifies the mesh geometry according to its own current World Matrix.
  32022. * The mesh World Matrix is then reset.
  32023. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32024. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32025. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32026. * Returns the Mesh.
  32027. */
  32028. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32029. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32030. this.scaling.copyFromFloats(1, 1, 1);
  32031. this.position.copyFromFloats(0, 0, 0);
  32032. this.rotation.copyFromFloats(0, 0, 0);
  32033. //only if quaternion is already set
  32034. if (this.rotationQuaternion) {
  32035. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32036. }
  32037. this._worldMatrix = BABYLON.Matrix.Identity();
  32038. return this;
  32039. };
  32040. Object.defineProperty(Mesh.prototype, "_positions", {
  32041. // Cache
  32042. get: function () {
  32043. if (this._geometry) {
  32044. return this._geometry._positions;
  32045. }
  32046. return null;
  32047. },
  32048. enumerable: true,
  32049. configurable: true
  32050. });
  32051. /** @hidden */
  32052. Mesh.prototype._resetPointsArrayCache = function () {
  32053. if (this._geometry) {
  32054. this._geometry._resetPointsArrayCache();
  32055. }
  32056. return this;
  32057. };
  32058. /** @hidden */
  32059. Mesh.prototype._generatePointsArray = function () {
  32060. if (this._geometry) {
  32061. return this._geometry._generatePointsArray();
  32062. }
  32063. return false;
  32064. };
  32065. /**
  32066. * Returns a new Mesh object generated from the current mesh properties.
  32067. * This method must not get confused with createInstance().
  32068. * The parameter `name` is a string, the name given to the new mesh.
  32069. * The optional parameter `newParent` can be any Node object (default `null`).
  32070. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32071. * 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.
  32072. */
  32073. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32074. if (name === void 0) { name = ""; }
  32075. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32076. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32077. };
  32078. /**
  32079. * Releases resources associated with this mesh.
  32080. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32081. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32082. */
  32083. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32084. var _this = this;
  32085. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32086. this.morphTargetManager = null;
  32087. if (this._geometry) {
  32088. this._geometry.releaseForMesh(this, true);
  32089. }
  32090. if (this._onBeforeDrawObservable) {
  32091. this._onBeforeDrawObservable.clear();
  32092. }
  32093. if (this._onBeforeRenderObservable) {
  32094. this._onBeforeRenderObservable.clear();
  32095. }
  32096. if (this._onAfterRenderObservable) {
  32097. this._onAfterRenderObservable.clear();
  32098. }
  32099. // Sources
  32100. var meshes = this.getScene().meshes;
  32101. meshes.forEach(function (abstractMesh) {
  32102. var mesh = abstractMesh;
  32103. if (mesh._source && mesh._source === _this) {
  32104. mesh._source = null;
  32105. }
  32106. });
  32107. this._source = null;
  32108. // Instances
  32109. if (this._instancesBuffer) {
  32110. this._instancesBuffer.dispose();
  32111. this._instancesBuffer = null;
  32112. }
  32113. while (this.instances.length) {
  32114. this.instances[0].dispose();
  32115. }
  32116. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32117. };
  32118. /**
  32119. * Modifies the mesh geometry according to a displacement map.
  32120. * 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.
  32121. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32122. * This method returns nothing.
  32123. * @param url is a string, the URL from the image file is to be downloaded.
  32124. * @param minHeight is the lower limit of the displacement.
  32125. * @param maxHeight is the upper limit of the displacement.
  32126. * @param 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.
  32127. * @param uvOffset is an optional vector2 used to offset UV.
  32128. * @param uvScale is an optional vector2 used to scale UV.
  32129. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32130. * @returns the Mesh.
  32131. */
  32132. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32133. var _this = this;
  32134. if (forceUpdate === void 0) { forceUpdate = false; }
  32135. var scene = this.getScene();
  32136. var onload = function (img) {
  32137. // Getting height map data
  32138. var canvas = document.createElement("canvas");
  32139. var context = canvas.getContext("2d");
  32140. var heightMapWidth = img.width;
  32141. var heightMapHeight = img.height;
  32142. canvas.width = heightMapWidth;
  32143. canvas.height = heightMapHeight;
  32144. context.drawImage(img, 0, 0);
  32145. // Create VertexData from map data
  32146. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32147. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32148. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32149. //execute success callback, if set
  32150. if (onSuccess) {
  32151. onSuccess(_this);
  32152. }
  32153. };
  32154. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32155. return this;
  32156. };
  32157. /**
  32158. * Modifies the mesh geometry according to a displacementMap buffer.
  32159. * 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.
  32160. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32161. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32162. * @param heightMapWidth is the width of the buffer image.
  32163. * @param heightMapHeight is the height of the buffer image.
  32164. * @param minHeight is the lower limit of the displacement.
  32165. * @param maxHeight is the upper limit of the displacement.
  32166. * @param 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.
  32167. * @param uvOffset is an optional vector2 used to offset UV.
  32168. * @param uvScale is an optional vector2 used to scale UV.
  32169. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32170. * @returns the Mesh.
  32171. */
  32172. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32173. if (forceUpdate === void 0) { forceUpdate = false; }
  32174. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32175. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32176. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32177. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32178. return this;
  32179. }
  32180. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32181. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32182. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32183. var position = BABYLON.Vector3.Zero();
  32184. var normal = BABYLON.Vector3.Zero();
  32185. var uv = BABYLON.Vector2.Zero();
  32186. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32187. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32188. for (var index = 0; index < positions.length; index += 3) {
  32189. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32190. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32191. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32192. // Compute height
  32193. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32194. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32195. var pos = (u + v * heightMapWidth) * 4;
  32196. var r = buffer[pos] / 255.0;
  32197. var g = buffer[pos + 1] / 255.0;
  32198. var b = buffer[pos + 2] / 255.0;
  32199. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32200. normal.normalize();
  32201. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32202. position = position.add(normal);
  32203. position.toArray(positions, index);
  32204. }
  32205. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32206. if (forceUpdate) {
  32207. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32208. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32209. }
  32210. else {
  32211. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32212. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32213. }
  32214. return this;
  32215. };
  32216. /**
  32217. * Modify the mesh to get a flat shading rendering.
  32218. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32219. * This method returns the Mesh.
  32220. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32221. */
  32222. Mesh.prototype.convertToFlatShadedMesh = function () {
  32223. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32224. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32225. var kinds = this.getVerticesDataKinds();
  32226. var vbs = {};
  32227. var data = {};
  32228. var newdata = {};
  32229. var updatableNormals = false;
  32230. var kindIndex;
  32231. var kind;
  32232. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32233. kind = kinds[kindIndex];
  32234. var vertexBuffer = this.getVertexBuffer(kind);
  32235. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32236. updatableNormals = vertexBuffer.isUpdatable();
  32237. kinds.splice(kindIndex, 1);
  32238. kindIndex--;
  32239. continue;
  32240. }
  32241. vbs[kind] = vertexBuffer;
  32242. data[kind] = vbs[kind].getData();
  32243. newdata[kind] = [];
  32244. }
  32245. // Save previous submeshes
  32246. var previousSubmeshes = this.subMeshes.slice(0);
  32247. var indices = this.getIndices();
  32248. var totalIndices = this.getTotalIndices();
  32249. // Generating unique vertices per face
  32250. var index;
  32251. for (index = 0; index < totalIndices; index++) {
  32252. var vertexIndex = indices[index];
  32253. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32254. kind = kinds[kindIndex];
  32255. var stride = vbs[kind].getStrideSize();
  32256. for (var offset = 0; offset < stride; offset++) {
  32257. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32258. }
  32259. }
  32260. }
  32261. // Updating faces & normal
  32262. var normals = [];
  32263. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32264. for (index = 0; index < totalIndices; index += 3) {
  32265. indices[index] = index;
  32266. indices[index + 1] = index + 1;
  32267. indices[index + 2] = index + 2;
  32268. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32269. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32270. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32271. var p1p2 = p1.subtract(p2);
  32272. var p3p2 = p3.subtract(p2);
  32273. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32274. // Store same normals for every vertex
  32275. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32276. normals.push(normal.x);
  32277. normals.push(normal.y);
  32278. normals.push(normal.z);
  32279. }
  32280. }
  32281. this.setIndices(indices);
  32282. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32283. // Updating vertex buffers
  32284. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32285. kind = kinds[kindIndex];
  32286. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32287. }
  32288. // Updating submeshes
  32289. this.releaseSubMeshes();
  32290. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32291. var previousOne = previousSubmeshes[submeshIndex];
  32292. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32293. }
  32294. this.synchronizeInstances();
  32295. return this;
  32296. };
  32297. /**
  32298. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32299. * In other words, more vertices, no more indices and a single bigger VBO.
  32300. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32301. * Returns the Mesh.
  32302. */
  32303. Mesh.prototype.convertToUnIndexedMesh = function () {
  32304. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32305. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32306. var kinds = this.getVerticesDataKinds();
  32307. var vbs = {};
  32308. var data = {};
  32309. var newdata = {};
  32310. var kindIndex;
  32311. var kind;
  32312. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32313. kind = kinds[kindIndex];
  32314. var vertexBuffer = this.getVertexBuffer(kind);
  32315. vbs[kind] = vertexBuffer;
  32316. data[kind] = vbs[kind].getData();
  32317. newdata[kind] = [];
  32318. }
  32319. // Save previous submeshes
  32320. var previousSubmeshes = this.subMeshes.slice(0);
  32321. var indices = this.getIndices();
  32322. var totalIndices = this.getTotalIndices();
  32323. // Generating unique vertices per face
  32324. var index;
  32325. for (index = 0; index < totalIndices; index++) {
  32326. var vertexIndex = indices[index];
  32327. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32328. kind = kinds[kindIndex];
  32329. var stride = vbs[kind].getStrideSize();
  32330. for (var offset = 0; offset < stride; offset++) {
  32331. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32332. }
  32333. }
  32334. }
  32335. // Updating indices
  32336. for (index = 0; index < totalIndices; index += 3) {
  32337. indices[index] = index;
  32338. indices[index + 1] = index + 1;
  32339. indices[index + 2] = index + 2;
  32340. }
  32341. this.setIndices(indices);
  32342. // Updating vertex buffers
  32343. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32344. kind = kinds[kindIndex];
  32345. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32346. }
  32347. // Updating submeshes
  32348. this.releaseSubMeshes();
  32349. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32350. var previousOne = previousSubmeshes[submeshIndex];
  32351. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32352. }
  32353. this._unIndexed = true;
  32354. this.synchronizeInstances();
  32355. return this;
  32356. };
  32357. /**
  32358. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32359. * This method returns the Mesh.
  32360. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32361. */
  32362. Mesh.prototype.flipFaces = function (flipNormals) {
  32363. if (flipNormals === void 0) { flipNormals = false; }
  32364. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32365. var i;
  32366. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32367. for (i = 0; i < vertex_data.normals.length; i++) {
  32368. vertex_data.normals[i] *= -1;
  32369. }
  32370. }
  32371. if (vertex_data.indices) {
  32372. var temp;
  32373. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32374. // reassign indices
  32375. temp = vertex_data.indices[i + 1];
  32376. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32377. vertex_data.indices[i + 2] = temp;
  32378. }
  32379. }
  32380. vertex_data.applyToMesh(this);
  32381. return this;
  32382. };
  32383. // Instances
  32384. /**
  32385. * Creates a new InstancedMesh object from the mesh model.
  32386. * An instance shares the same properties and the same material than its model.
  32387. * Please make sure to call mesh.makeGeometryUnique() if you are calling createInstance on a previously cloned mesh.
  32388. * Only these properties of each instance can then be set individually :
  32389. * - position
  32390. * - rotation
  32391. * - rotationQuaternion
  32392. * - setPivotMatrix
  32393. * - scaling
  32394. *
  32395. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32396. * Warning : this method is not supported for Line mesh and LineSystem
  32397. */
  32398. Mesh.prototype.createInstance = function (name) {
  32399. return new BABYLON.InstancedMesh(name, this);
  32400. };
  32401. /**
  32402. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32403. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32404. * This method returns the Mesh.
  32405. */
  32406. Mesh.prototype.synchronizeInstances = function () {
  32407. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32408. var instance = this.instances[instanceIndex];
  32409. instance._syncSubMeshes();
  32410. }
  32411. return this;
  32412. };
  32413. /**
  32414. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32415. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32416. * This should be used together with the simplification to avoid disappearing triangles.
  32417. * Returns the Mesh.
  32418. * @param successCallback an optional success callback to be called after the optimization finished.
  32419. */
  32420. Mesh.prototype.optimizeIndices = function (successCallback) {
  32421. var _this = this;
  32422. var indices = this.getIndices();
  32423. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32424. if (!positions || !indices) {
  32425. return this;
  32426. }
  32427. var vectorPositions = new Array();
  32428. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32429. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32430. }
  32431. var dupes = new Array();
  32432. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32433. var realPos = vectorPositions.length - 1 - iteration;
  32434. var testedPosition = vectorPositions[realPos];
  32435. for (var j = 0; j < realPos; ++j) {
  32436. var againstPosition = vectorPositions[j];
  32437. if (testedPosition.equals(againstPosition)) {
  32438. dupes[realPos] = j;
  32439. break;
  32440. }
  32441. }
  32442. }, function () {
  32443. for (var i = 0; i < indices.length; ++i) {
  32444. indices[i] = dupes[indices[i]] || indices[i];
  32445. }
  32446. //indices are now reordered
  32447. var originalSubMeshes = _this.subMeshes.slice(0);
  32448. _this.setIndices(indices);
  32449. _this.subMeshes = originalSubMeshes;
  32450. if (successCallback) {
  32451. successCallback(_this);
  32452. }
  32453. });
  32454. return this;
  32455. };
  32456. Mesh.prototype.serialize = function (serializationObject) {
  32457. serializationObject.name = this.name;
  32458. serializationObject.id = this.id;
  32459. serializationObject.type = this.getClassName();
  32460. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32461. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32462. }
  32463. serializationObject.position = this.position.asArray();
  32464. if (this.rotationQuaternion) {
  32465. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32466. }
  32467. else if (this.rotation) {
  32468. serializationObject.rotation = this.rotation.asArray();
  32469. }
  32470. serializationObject.scaling = this.scaling.asArray();
  32471. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32472. serializationObject.isEnabled = this.isEnabled(false);
  32473. serializationObject.isVisible = this.isVisible;
  32474. serializationObject.infiniteDistance = this.infiniteDistance;
  32475. serializationObject.pickable = this.isPickable;
  32476. serializationObject.receiveShadows = this.receiveShadows;
  32477. serializationObject.billboardMode = this.billboardMode;
  32478. serializationObject.visibility = this.visibility;
  32479. serializationObject.checkCollisions = this.checkCollisions;
  32480. serializationObject.isBlocker = this.isBlocker;
  32481. // Parent
  32482. if (this.parent) {
  32483. serializationObject.parentId = this.parent.id;
  32484. }
  32485. // Geometry
  32486. serializationObject.isUnIndexed = this.isUnIndexed;
  32487. var geometry = this._geometry;
  32488. if (geometry) {
  32489. var geometryId = geometry.id;
  32490. serializationObject.geometryId = geometryId;
  32491. // SubMeshes
  32492. serializationObject.subMeshes = [];
  32493. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32494. var subMesh = this.subMeshes[subIndex];
  32495. serializationObject.subMeshes.push({
  32496. materialIndex: subMesh.materialIndex,
  32497. verticesStart: subMesh.verticesStart,
  32498. verticesCount: subMesh.verticesCount,
  32499. indexStart: subMesh.indexStart,
  32500. indexCount: subMesh.indexCount
  32501. });
  32502. }
  32503. }
  32504. // Material
  32505. if (this.material) {
  32506. serializationObject.materialId = this.material.id;
  32507. }
  32508. else {
  32509. this.material = null;
  32510. }
  32511. // Morph targets
  32512. if (this.morphTargetManager) {
  32513. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32514. }
  32515. // Skeleton
  32516. if (this.skeleton) {
  32517. serializationObject.skeletonId = this.skeleton.id;
  32518. }
  32519. // Physics
  32520. //TODO implement correct serialization for physics impostors.
  32521. var impostor = this.getPhysicsImpostor();
  32522. if (impostor) {
  32523. serializationObject.physicsMass = impostor.getParam("mass");
  32524. serializationObject.physicsFriction = impostor.getParam("friction");
  32525. serializationObject.physicsRestitution = impostor.getParam("mass");
  32526. serializationObject.physicsImpostor = impostor.type;
  32527. }
  32528. // Metadata
  32529. if (this.metadata) {
  32530. serializationObject.metadata = this.metadata;
  32531. }
  32532. // Instances
  32533. serializationObject.instances = [];
  32534. for (var index = 0; index < this.instances.length; index++) {
  32535. var instance = this.instances[index];
  32536. if (instance.doNotSerialize) {
  32537. continue;
  32538. }
  32539. var serializationInstance = {
  32540. name: instance.name,
  32541. id: instance.id,
  32542. position: instance.position.asArray(),
  32543. scaling: instance.scaling.asArray()
  32544. };
  32545. if (instance.parent) {
  32546. serializationInstance.parentId = instance.parent.id;
  32547. }
  32548. if (instance.rotationQuaternion) {
  32549. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32550. }
  32551. else if (instance.rotation) {
  32552. serializationInstance.rotation = instance.rotation.asArray();
  32553. }
  32554. serializationObject.instances.push(serializationInstance);
  32555. // Animations
  32556. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32557. serializationInstance.ranges = instance.serializeAnimationRanges();
  32558. }
  32559. //
  32560. // Animations
  32561. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32562. serializationObject.ranges = this.serializeAnimationRanges();
  32563. // Layer mask
  32564. serializationObject.layerMask = this.layerMask;
  32565. // Alpha
  32566. serializationObject.alphaIndex = this.alphaIndex;
  32567. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32568. // Overlay
  32569. serializationObject.overlayAlpha = this.overlayAlpha;
  32570. serializationObject.overlayColor = this.overlayColor.asArray();
  32571. serializationObject.renderOverlay = this.renderOverlay;
  32572. // Fog
  32573. serializationObject.applyFog = this.applyFog;
  32574. // Action Manager
  32575. if (this.actionManager) {
  32576. serializationObject.actions = this.actionManager.serialize(this.name);
  32577. }
  32578. };
  32579. /** @hidden */
  32580. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32581. if (!this.geometry) {
  32582. return;
  32583. }
  32584. this._markSubMeshesAsAttributesDirty();
  32585. var morphTargetManager = this._morphTargetManager;
  32586. if (morphTargetManager && morphTargetManager.vertexCount) {
  32587. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32588. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32589. this.morphTargetManager = null;
  32590. return;
  32591. }
  32592. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32593. var morphTarget = morphTargetManager.getActiveTarget(index);
  32594. var positions = morphTarget.getPositions();
  32595. if (!positions) {
  32596. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32597. return;
  32598. }
  32599. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32600. var normals = morphTarget.getNormals();
  32601. if (normals) {
  32602. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32603. }
  32604. var tangents = morphTarget.getTangents();
  32605. if (tangents) {
  32606. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32607. }
  32608. }
  32609. }
  32610. else {
  32611. var index = 0;
  32612. // Positions
  32613. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32614. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32615. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32616. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32617. }
  32618. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32619. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32620. }
  32621. index++;
  32622. }
  32623. }
  32624. };
  32625. // Statics
  32626. /**
  32627. * Returns a new Mesh object parsed from the source provided.
  32628. * The parameter `parsedMesh` is the source.
  32629. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32630. */
  32631. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32632. var mesh;
  32633. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32634. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32635. }
  32636. else {
  32637. mesh = new Mesh(parsedMesh.name, scene);
  32638. }
  32639. mesh.id = parsedMesh.id;
  32640. if (BABYLON.Tags) {
  32641. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32642. }
  32643. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32644. if (parsedMesh.metadata !== undefined) {
  32645. mesh.metadata = parsedMesh.metadata;
  32646. }
  32647. if (parsedMesh.rotationQuaternion) {
  32648. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32649. }
  32650. else if (parsedMesh.rotation) {
  32651. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32652. }
  32653. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32654. if (parsedMesh.localMatrix) {
  32655. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32656. }
  32657. else if (parsedMesh.pivotMatrix) {
  32658. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32659. }
  32660. mesh.setEnabled(parsedMesh.isEnabled);
  32661. mesh.isVisible = parsedMesh.isVisible;
  32662. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32663. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32664. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32665. if (parsedMesh.applyFog !== undefined) {
  32666. mesh.applyFog = parsedMesh.applyFog;
  32667. }
  32668. if (parsedMesh.pickable !== undefined) {
  32669. mesh.isPickable = parsedMesh.pickable;
  32670. }
  32671. if (parsedMesh.alphaIndex !== undefined) {
  32672. mesh.alphaIndex = parsedMesh.alphaIndex;
  32673. }
  32674. mesh.receiveShadows = parsedMesh.receiveShadows;
  32675. mesh.billboardMode = parsedMesh.billboardMode;
  32676. if (parsedMesh.visibility !== undefined) {
  32677. mesh.visibility = parsedMesh.visibility;
  32678. }
  32679. mesh.checkCollisions = parsedMesh.checkCollisions;
  32680. if (parsedMesh.isBlocker !== undefined) {
  32681. mesh.isBlocker = parsedMesh.isBlocker;
  32682. }
  32683. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32684. // freezeWorldMatrix
  32685. if (parsedMesh.freezeWorldMatrix) {
  32686. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32687. }
  32688. // Parent
  32689. if (parsedMesh.parentId) {
  32690. mesh._waitingParentId = parsedMesh.parentId;
  32691. }
  32692. // Actions
  32693. if (parsedMesh.actions !== undefined) {
  32694. mesh._waitingActions = parsedMesh.actions;
  32695. }
  32696. // Overlay
  32697. if (parsedMesh.overlayAlpha !== undefined) {
  32698. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32699. }
  32700. if (parsedMesh.overlayColor !== undefined) {
  32701. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32702. }
  32703. if (parsedMesh.renderOverlay !== undefined) {
  32704. mesh.renderOverlay = parsedMesh.renderOverlay;
  32705. }
  32706. // Geometry
  32707. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32708. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32709. if (parsedMesh.delayLoadingFile) {
  32710. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32711. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32712. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32713. if (parsedMesh._binaryInfo) {
  32714. mesh._binaryInfo = parsedMesh._binaryInfo;
  32715. }
  32716. mesh._delayInfo = [];
  32717. if (parsedMesh.hasUVs) {
  32718. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32719. }
  32720. if (parsedMesh.hasUVs2) {
  32721. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32722. }
  32723. if (parsedMesh.hasUVs3) {
  32724. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32725. }
  32726. if (parsedMesh.hasUVs4) {
  32727. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32728. }
  32729. if (parsedMesh.hasUVs5) {
  32730. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32731. }
  32732. if (parsedMesh.hasUVs6) {
  32733. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32734. }
  32735. if (parsedMesh.hasColors) {
  32736. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32737. }
  32738. if (parsedMesh.hasMatricesIndices) {
  32739. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32740. }
  32741. if (parsedMesh.hasMatricesWeights) {
  32742. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32743. }
  32744. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32745. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32746. mesh._checkDelayState();
  32747. }
  32748. }
  32749. else {
  32750. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32751. }
  32752. // Material
  32753. if (parsedMesh.materialId) {
  32754. mesh.setMaterialByID(parsedMesh.materialId);
  32755. }
  32756. else {
  32757. mesh.material = null;
  32758. }
  32759. // Morph targets
  32760. if (parsedMesh.morphTargetManagerId > -1) {
  32761. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32762. }
  32763. // Skeleton
  32764. if (parsedMesh.skeletonId > -1) {
  32765. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32766. if (parsedMesh.numBoneInfluencers) {
  32767. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32768. }
  32769. }
  32770. // Animations
  32771. if (parsedMesh.animations) {
  32772. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32773. var parsedAnimation = parsedMesh.animations[animationIndex];
  32774. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32775. }
  32776. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32777. }
  32778. if (parsedMesh.autoAnimate) {
  32779. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32780. }
  32781. // Layer Mask
  32782. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32783. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32784. }
  32785. else {
  32786. mesh.layerMask = 0x0FFFFFFF;
  32787. }
  32788. // Physics
  32789. if (parsedMesh.physicsImpostor) {
  32790. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32791. mass: parsedMesh.physicsMass,
  32792. friction: parsedMesh.physicsFriction,
  32793. restitution: parsedMesh.physicsRestitution
  32794. }, scene);
  32795. }
  32796. // Instances
  32797. if (parsedMesh.instances) {
  32798. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32799. var parsedInstance = parsedMesh.instances[index];
  32800. var instance = mesh.createInstance(parsedInstance.name);
  32801. if (parsedInstance.id) {
  32802. instance.id = parsedInstance.id;
  32803. }
  32804. if (BABYLON.Tags) {
  32805. if (parsedInstance.tags) {
  32806. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32807. }
  32808. else {
  32809. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  32810. }
  32811. }
  32812. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32813. if (parsedInstance.parentId) {
  32814. instance._waitingParentId = parsedInstance.parentId;
  32815. }
  32816. if (parsedInstance.rotationQuaternion) {
  32817. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32818. }
  32819. else if (parsedInstance.rotation) {
  32820. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32821. }
  32822. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32823. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  32824. instance.checkCollisions = parsedInstance.checkCollisions;
  32825. }
  32826. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  32827. instance.isPickable = parsedInstance.pickable;
  32828. }
  32829. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  32830. instance.showBoundingBox = parsedInstance.showBoundingBox;
  32831. }
  32832. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  32833. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  32834. }
  32835. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  32836. instance.alphaIndex = parsedInstance.alphaIndex;
  32837. }
  32838. // Physics
  32839. if (parsedInstance.physicsImpostor) {
  32840. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  32841. mass: parsedInstance.physicsMass,
  32842. friction: parsedInstance.physicsFriction,
  32843. restitution: parsedInstance.physicsRestitution
  32844. }, scene);
  32845. }
  32846. // Animation
  32847. if (parsedInstance.animations) {
  32848. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  32849. parsedAnimation = parsedInstance.animations[animationIndex];
  32850. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32851. }
  32852. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  32853. if (parsedInstance.autoAnimate) {
  32854. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  32855. }
  32856. }
  32857. }
  32858. }
  32859. return mesh;
  32860. };
  32861. /**
  32862. * Creates a ribbon mesh.
  32863. * Please consider using the same method from the MeshBuilder class instead.
  32864. * The ribbon is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  32865. *
  32866. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32867. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32868. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32869. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32870. * 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.
  32871. * 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.
  32872. * 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
  32873. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32874. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32875. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32876. */
  32877. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32878. if (closeArray === void 0) { closeArray = false; }
  32879. if (updatable === void 0) { updatable = false; }
  32880. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32881. pathArray: pathArray,
  32882. closeArray: closeArray,
  32883. closePath: closePath,
  32884. offset: offset,
  32885. updatable: updatable,
  32886. sideOrientation: sideOrientation,
  32887. instance: instance
  32888. }, scene);
  32889. };
  32890. /**
  32891. * Creates a plane polygonal mesh. By default, this is a disc.
  32892. * Please consider using the same method from the MeshBuilder class instead.
  32893. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32894. * 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.
  32895. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32896. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32897. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32898. */
  32899. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32900. if (scene === void 0) { scene = null; }
  32901. var options = {
  32902. radius: radius,
  32903. tessellation: tessellation,
  32904. sideOrientation: sideOrientation,
  32905. updatable: updatable
  32906. };
  32907. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32908. };
  32909. /**
  32910. * Creates a box mesh.
  32911. * Please consider using the same method from the MeshBuilder class instead.
  32912. * The parameter `size` sets the size (float) of each box side (default 1).
  32913. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32914. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32915. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32916. */
  32917. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32918. if (scene === void 0) { scene = null; }
  32919. var options = {
  32920. size: size,
  32921. sideOrientation: sideOrientation,
  32922. updatable: updatable
  32923. };
  32924. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32925. };
  32926. /**
  32927. * Creates a sphere mesh.
  32928. * Please consider using the same method from the MeshBuilder class instead.
  32929. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32930. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32931. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32932. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32933. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32934. */
  32935. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32936. var options = {
  32937. segments: segments,
  32938. diameterX: diameter,
  32939. diameterY: diameter,
  32940. diameterZ: diameter,
  32941. sideOrientation: sideOrientation,
  32942. updatable: updatable
  32943. };
  32944. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  32945. };
  32946. /**
  32947. * Creates a cylinder or a cone mesh.
  32948. * Please consider using the same method from the MeshBuilder class instead.
  32949. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  32950. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  32951. * 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.
  32952. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  32953. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  32954. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32955. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32956. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32957. */
  32958. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  32959. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  32960. if (scene !== undefined) {
  32961. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  32962. updatable = scene;
  32963. }
  32964. scene = subdivisions;
  32965. subdivisions = 1;
  32966. }
  32967. var options = {
  32968. height: height,
  32969. diameterTop: diameterTop,
  32970. diameterBottom: diameterBottom,
  32971. tessellation: tessellation,
  32972. subdivisions: subdivisions,
  32973. sideOrientation: sideOrientation,
  32974. updatable: updatable
  32975. };
  32976. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  32977. };
  32978. // Torus (Code from SharpDX.org)
  32979. /**
  32980. * Creates a torus mesh.
  32981. * Please consider using the same method from the MeshBuilder class instead.
  32982. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  32983. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  32984. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  32985. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32986. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32987. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32988. */
  32989. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  32990. var options = {
  32991. diameter: diameter,
  32992. thickness: thickness,
  32993. tessellation: tessellation,
  32994. sideOrientation: sideOrientation,
  32995. updatable: updatable
  32996. };
  32997. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  32998. };
  32999. /**
  33000. * Creates a torus knot mesh.
  33001. * Please consider using the same method from the MeshBuilder class instead.
  33002. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33003. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33004. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33005. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33006. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33007. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33008. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33009. */
  33010. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33011. var options = {
  33012. radius: radius,
  33013. tube: tube,
  33014. radialSegments: radialSegments,
  33015. tubularSegments: tubularSegments,
  33016. p: p,
  33017. q: q,
  33018. sideOrientation: sideOrientation,
  33019. updatable: updatable
  33020. };
  33021. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33022. };
  33023. /**
  33024. * Creates a line mesh.
  33025. * Please consider using the same method from the MeshBuilder class instead.
  33026. * 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.
  33027. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33028. * The parameter `points` is an array successive Vector3.
  33029. * 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
  33030. * When updating an instance, remember that only point positions can change, not the number of points.
  33031. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33032. */
  33033. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33034. if (scene === void 0) { scene = null; }
  33035. if (updatable === void 0) { updatable = false; }
  33036. if (instance === void 0) { instance = null; }
  33037. var options = {
  33038. points: points,
  33039. updatable: updatable,
  33040. instance: instance
  33041. };
  33042. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33043. };
  33044. /**
  33045. * Creates a dashed line mesh.
  33046. * Please consider using the same method from the MeshBuilder class instead.
  33047. * 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.
  33048. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33049. * The parameter `points` is an array successive Vector3.
  33050. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33051. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33052. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33053. * 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
  33054. * When updating an instance, remember that only point positions can change, not the number of points.
  33055. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33056. */
  33057. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33058. if (scene === void 0) { scene = null; }
  33059. var options = {
  33060. points: points,
  33061. dashSize: dashSize,
  33062. gapSize: gapSize,
  33063. dashNb: dashNb,
  33064. updatable: updatable,
  33065. instance: instance
  33066. };
  33067. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33068. };
  33069. /**
  33070. * Creates a polygon mesh.
  33071. * Please consider using the same method from the MeshBuilder class instead.
  33072. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33073. * 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.
  33074. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33075. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33076. * Remember you can only change the shape positions, not their number when updating a polygon.
  33077. */
  33078. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33079. var options = {
  33080. shape: shape,
  33081. holes: holes,
  33082. updatable: updatable,
  33083. sideOrientation: sideOrientation
  33084. };
  33085. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33086. };
  33087. /**
  33088. * Creates an extruded polygon mesh, with depth in the Y direction.
  33089. * Please consider using the same method from the MeshBuilder class instead.
  33090. */
  33091. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33092. var options = {
  33093. shape: shape,
  33094. holes: holes,
  33095. depth: depth,
  33096. updatable: updatable,
  33097. sideOrientation: sideOrientation
  33098. };
  33099. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33100. };
  33101. /**
  33102. * Creates an extruded shape mesh.
  33103. * The extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33104. * Please consider using the same method from the MeshBuilder class instead.
  33105. *
  33106. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33107. * 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
  33108. * extruded along the Z axis.
  33109. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33110. * 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.
  33111. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33112. * 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
  33113. * 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
  33114. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33115. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33116. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33117. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33118. */
  33119. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33120. if (scene === void 0) { scene = null; }
  33121. var options = {
  33122. shape: shape,
  33123. path: path,
  33124. scale: scale,
  33125. rotation: rotation,
  33126. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33127. sideOrientation: sideOrientation,
  33128. instance: instance,
  33129. updatable: updatable
  33130. };
  33131. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33132. };
  33133. /**
  33134. * Creates an custom extruded shape mesh.
  33135. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33136. * Please consider using the same method from the MeshBuilder class instead.
  33137. *
  33138. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33139. * 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
  33140. * extruded along the Z axis.
  33141. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33142. * 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
  33143. * and the distance of this point from the begining of the path :
  33144. * ```javascript
  33145. * var rotationFunction = function(i, distance) {
  33146. * // do things
  33147. * return rotationValue; }
  33148. * ```
  33149. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33150. * 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
  33151. * and the distance of this point from the begining of the path :
  33152. * ```javascript
  33153. * var scaleFunction = function(i, distance) {
  33154. * // do things
  33155. * return scaleValue;}
  33156. * ```
  33157. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33158. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33159. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33160. * 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
  33161. * 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
  33162. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33163. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33164. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33165. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33166. */
  33167. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33168. var options = {
  33169. shape: shape,
  33170. path: path,
  33171. scaleFunction: scaleFunction,
  33172. rotationFunction: rotationFunction,
  33173. ribbonCloseArray: ribbonCloseArray,
  33174. ribbonClosePath: ribbonClosePath,
  33175. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33176. sideOrientation: sideOrientation,
  33177. instance: instance,
  33178. updatable: updatable
  33179. };
  33180. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33181. };
  33182. /**
  33183. * Creates lathe mesh.
  33184. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33185. * Please consider using the same method from the MeshBuilder class instead.
  33186. * 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
  33187. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33188. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33189. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33190. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33191. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33192. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33193. */
  33194. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33195. var options = {
  33196. shape: shape,
  33197. radius: radius,
  33198. tessellation: tessellation,
  33199. sideOrientation: sideOrientation,
  33200. updatable: updatable
  33201. };
  33202. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33203. };
  33204. /**
  33205. * Creates a plane mesh.
  33206. * Please consider using the same method from the MeshBuilder class instead.
  33207. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33208. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33209. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33210. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33211. */
  33212. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33213. var options = {
  33214. size: size,
  33215. width: size,
  33216. height: size,
  33217. sideOrientation: sideOrientation,
  33218. updatable: updatable
  33219. };
  33220. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33221. };
  33222. /**
  33223. * Creates a ground mesh.
  33224. * Please consider using the same method from the MeshBuilder class instead.
  33225. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33226. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33227. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33228. */
  33229. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33230. var options = {
  33231. width: width,
  33232. height: height,
  33233. subdivisions: subdivisions,
  33234. updatable: updatable
  33235. };
  33236. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33237. };
  33238. /**
  33239. * Creates a tiled ground mesh.
  33240. * Please consider using the same method from the MeshBuilder class instead.
  33241. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33242. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33243. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33244. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33245. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33246. * numbers of subdivisions on the ground width and height of each tile.
  33247. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33248. */
  33249. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33250. var options = {
  33251. xmin: xmin,
  33252. zmin: zmin,
  33253. xmax: xmax,
  33254. zmax: zmax,
  33255. subdivisions: subdivisions,
  33256. precision: precision,
  33257. updatable: updatable
  33258. };
  33259. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33260. };
  33261. /**
  33262. * Creates a ground mesh from a height map.
  33263. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33264. * Please consider using the same method from the MeshBuilder class instead.
  33265. * @param url sets the URL of the height map image resource.
  33266. * @param width (positive float, default 10) set the ground width size.
  33267. * @param height (positive float, default 10) set the ground height size.
  33268. * @param subdivisions (positive integer, default 1) sets the number of subdivision per side.
  33269. * @param minHeight (float, default 0) is the minimum altitude on the ground.
  33270. * @param maxHeight (float, default 1) is the maximum altitude on the ground.
  33271. * @param onReady is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  33272. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible).
  33273. * This function is passed the newly built mesh :
  33274. * ```javascript
  33275. * function(mesh) { // do things
  33276. * return; }
  33277. * ```
  33278. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33279. */
  33280. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  33281. var options = {
  33282. width: width,
  33283. height: height,
  33284. subdivisions: subdivisions,
  33285. minHeight: minHeight,
  33286. maxHeight: maxHeight,
  33287. updatable: updatable,
  33288. onReady: onReady,
  33289. alphaFilter: alphaFilter
  33290. };
  33291. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33292. };
  33293. /**
  33294. * Creates a tube mesh.
  33295. * The tube is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33296. * Please consider using the same method from the MeshBuilder class instead.
  33297. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33298. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33299. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33300. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33301. * 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.
  33302. * It must return a radius value (positive float) :
  33303. * ```javascript
  33304. * var radiusFunction = function(i, distance) {
  33305. * // do things
  33306. * return radius; }
  33307. * ```
  33308. * 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
  33309. * 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
  33310. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33311. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33312. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33313. */
  33314. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33315. var options = {
  33316. path: path,
  33317. radius: radius,
  33318. tessellation: tessellation,
  33319. radiusFunction: radiusFunction,
  33320. arc: 1,
  33321. cap: cap,
  33322. updatable: updatable,
  33323. sideOrientation: sideOrientation,
  33324. instance: instance
  33325. };
  33326. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33327. };
  33328. /**
  33329. * Creates a polyhedron mesh.
  33330. * Please consider using the same method from the MeshBuilder class instead.
  33331. * 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
  33332. * to choose the wanted type.
  33333. * The parameter `size` (positive float, default 1) sets the polygon size.
  33334. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33335. * 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`.
  33336. * 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
  33337. * 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)`).
  33338. * 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
  33339. * 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.
  33340. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33341. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33342. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33343. */
  33344. Mesh.CreatePolyhedron = function (name, options, scene) {
  33345. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33346. };
  33347. /**
  33348. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33349. * Please consider using the same method from the MeshBuilder class instead.
  33350. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33351. * 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`).
  33352. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33353. * 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.
  33354. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33355. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33356. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33357. */
  33358. Mesh.CreateIcoSphere = function (name, options, scene) {
  33359. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33360. };
  33361. /**
  33362. * Creates a decal mesh.
  33363. * Please consider using the same method from the MeshBuilder class instead.
  33364. * 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.
  33365. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33366. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33367. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33368. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33369. */
  33370. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33371. var options = {
  33372. position: position,
  33373. normal: normal,
  33374. size: size,
  33375. angle: angle
  33376. };
  33377. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33378. };
  33379. // Skeletons
  33380. /**
  33381. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33382. */
  33383. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33384. if (!this._sourcePositions) {
  33385. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33386. if (!source) {
  33387. return this._sourcePositions;
  33388. }
  33389. this._sourcePositions = new Float32Array(source);
  33390. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33391. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33392. }
  33393. }
  33394. return this._sourcePositions;
  33395. };
  33396. /**
  33397. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33398. */
  33399. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33400. if (!this._sourceNormals) {
  33401. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33402. if (!source) {
  33403. return this._sourceNormals;
  33404. }
  33405. this._sourceNormals = new Float32Array(source);
  33406. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33407. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33408. }
  33409. }
  33410. return this._sourceNormals;
  33411. };
  33412. /**
  33413. * Updates the vertex buffer by applying transformation from the bones.
  33414. * Returns the Mesh.
  33415. *
  33416. * @param {skeleton} skeleton to apply
  33417. */
  33418. Mesh.prototype.applySkeleton = function (skeleton) {
  33419. if (!this.geometry) {
  33420. return this;
  33421. }
  33422. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  33423. return this;
  33424. }
  33425. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  33426. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33427. return this;
  33428. }
  33429. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33430. return this;
  33431. }
  33432. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33433. return this;
  33434. }
  33435. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33436. return this;
  33437. }
  33438. if (!this._sourcePositions) {
  33439. var submeshes = this.subMeshes.slice();
  33440. this.setPositionsForCPUSkinning();
  33441. this.subMeshes = submeshes;
  33442. }
  33443. if (!this._sourceNormals) {
  33444. this.setNormalsForCPUSkinning();
  33445. }
  33446. // positionsData checks for not being Float32Array will only pass at most once
  33447. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33448. if (!positionsData) {
  33449. return this;
  33450. }
  33451. if (!(positionsData instanceof Float32Array)) {
  33452. positionsData = new Float32Array(positionsData);
  33453. }
  33454. // normalsData checks for not being Float32Array will only pass at most once
  33455. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33456. if (!normalsData) {
  33457. return this;
  33458. }
  33459. if (!(normalsData instanceof Float32Array)) {
  33460. normalsData = new Float32Array(normalsData);
  33461. }
  33462. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33463. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33464. if (!matricesWeightsData || !matricesIndicesData) {
  33465. return this;
  33466. }
  33467. var needExtras = this.numBoneInfluencers > 4;
  33468. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33469. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33470. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33471. var tempVector3 = BABYLON.Vector3.Zero();
  33472. var finalMatrix = new BABYLON.Matrix();
  33473. var tempMatrix = new BABYLON.Matrix();
  33474. var matWeightIdx = 0;
  33475. var inf;
  33476. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33477. var weight;
  33478. for (inf = 0; inf < 4; inf++) {
  33479. weight = matricesWeightsData[matWeightIdx + inf];
  33480. if (weight > 0) {
  33481. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33482. finalMatrix.addToSelf(tempMatrix);
  33483. }
  33484. }
  33485. if (needExtras) {
  33486. for (inf = 0; inf < 4; inf++) {
  33487. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33488. if (weight > 0) {
  33489. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33490. finalMatrix.addToSelf(tempMatrix);
  33491. }
  33492. }
  33493. }
  33494. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33495. tempVector3.toArray(positionsData, index);
  33496. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33497. tempVector3.toArray(normalsData, index);
  33498. finalMatrix.reset();
  33499. }
  33500. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33501. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33502. return this;
  33503. };
  33504. // Tools
  33505. /**
  33506. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33507. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33508. */
  33509. Mesh.MinMax = function (meshes) {
  33510. var minVector = null;
  33511. var maxVector = null;
  33512. meshes.forEach(function (mesh, index, array) {
  33513. var boundingInfo = mesh.getBoundingInfo();
  33514. var boundingBox = boundingInfo.boundingBox;
  33515. if (!minVector || !maxVector) {
  33516. minVector = boundingBox.minimumWorld;
  33517. maxVector = boundingBox.maximumWorld;
  33518. }
  33519. else {
  33520. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33521. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33522. }
  33523. });
  33524. if (!minVector || !maxVector) {
  33525. return {
  33526. min: BABYLON.Vector3.Zero(),
  33527. max: BABYLON.Vector3.Zero()
  33528. };
  33529. }
  33530. return {
  33531. min: minVector,
  33532. max: maxVector
  33533. };
  33534. };
  33535. /**
  33536. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33537. */
  33538. Mesh.Center = function (meshesOrMinMaxVector) {
  33539. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33540. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33541. };
  33542. /**
  33543. * Merge the array of meshes into a single mesh for performance reasons.
  33544. * @param meshes - The vertices source. They should all be of the same material. Entries can empty
  33545. * @param disposeSource - When true (default), dispose of the vertices from the source meshes
  33546. * @param allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33547. * @param meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33548. * @param subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33549. */
  33550. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33551. if (disposeSource === void 0) { disposeSource = true; }
  33552. var index;
  33553. if (!allow32BitsIndices) {
  33554. var totalVertices = 0;
  33555. // Counting vertices
  33556. for (index = 0; index < meshes.length; index++) {
  33557. if (meshes[index]) {
  33558. totalVertices += meshes[index].getTotalVertices();
  33559. if (totalVertices > 65536) {
  33560. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33561. return null;
  33562. }
  33563. }
  33564. }
  33565. }
  33566. // Merge
  33567. var vertexData = null;
  33568. var otherVertexData;
  33569. var indiceArray = new Array();
  33570. var source = null;
  33571. for (index = 0; index < meshes.length; index++) {
  33572. if (meshes[index]) {
  33573. var wm = meshes[index].computeWorldMatrix(true);
  33574. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33575. otherVertexData.transform(wm);
  33576. if (vertexData) {
  33577. vertexData.merge(otherVertexData, allow32BitsIndices);
  33578. }
  33579. else {
  33580. vertexData = otherVertexData;
  33581. source = meshes[index];
  33582. }
  33583. if (subdivideWithSubMeshes) {
  33584. indiceArray.push(meshes[index].getTotalIndices());
  33585. }
  33586. }
  33587. }
  33588. source = source;
  33589. if (!meshSubclass) {
  33590. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33591. }
  33592. vertexData.applyToMesh(meshSubclass);
  33593. // Setting properties
  33594. meshSubclass.material = source.material;
  33595. meshSubclass.checkCollisions = source.checkCollisions;
  33596. // Cleaning
  33597. if (disposeSource) {
  33598. for (index = 0; index < meshes.length; index++) {
  33599. if (meshes[index]) {
  33600. meshes[index].dispose();
  33601. }
  33602. }
  33603. }
  33604. // Subdivide
  33605. if (subdivideWithSubMeshes) {
  33606. //-- removal of global submesh
  33607. meshSubclass.releaseSubMeshes();
  33608. index = 0;
  33609. var offset = 0;
  33610. //-- apply subdivision according to index table
  33611. while (index < indiceArray.length) {
  33612. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33613. offset += indiceArray[index];
  33614. index++;
  33615. }
  33616. }
  33617. return meshSubclass;
  33618. };
  33619. // Consts
  33620. Mesh._FRONTSIDE = 0;
  33621. Mesh._BACKSIDE = 1;
  33622. Mesh._DOUBLESIDE = 2;
  33623. Mesh._DEFAULTSIDE = 0;
  33624. Mesh._NO_CAP = 0;
  33625. Mesh._CAP_START = 1;
  33626. Mesh._CAP_END = 2;
  33627. Mesh._CAP_ALL = 3;
  33628. return Mesh;
  33629. }(BABYLON.AbstractMesh));
  33630. BABYLON.Mesh = Mesh;
  33631. })(BABYLON || (BABYLON = {}));
  33632. //# sourceMappingURL=babylon.mesh.js.map
  33633. var BABYLON;
  33634. (function (BABYLON) {
  33635. var BaseSubMesh = /** @class */ (function () {
  33636. function BaseSubMesh() {
  33637. }
  33638. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33639. get: function () {
  33640. return this._materialEffect;
  33641. },
  33642. enumerable: true,
  33643. configurable: true
  33644. });
  33645. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33646. if (defines === void 0) { defines = null; }
  33647. if (this._materialEffect === effect) {
  33648. if (!effect) {
  33649. this._materialDefines = null;
  33650. }
  33651. return;
  33652. }
  33653. this._materialDefines = defines;
  33654. this._materialEffect = effect;
  33655. };
  33656. return BaseSubMesh;
  33657. }());
  33658. BABYLON.BaseSubMesh = BaseSubMesh;
  33659. var SubMesh = /** @class */ (function (_super) {
  33660. __extends(SubMesh, _super);
  33661. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33662. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33663. var _this = _super.call(this) || this;
  33664. _this.materialIndex = materialIndex;
  33665. _this.verticesStart = verticesStart;
  33666. _this.verticesCount = verticesCount;
  33667. _this.indexStart = indexStart;
  33668. _this.indexCount = indexCount;
  33669. /** @hidden */
  33670. _this._renderId = 0;
  33671. _this._mesh = mesh;
  33672. _this._renderingMesh = renderingMesh || mesh;
  33673. mesh.subMeshes.push(_this);
  33674. _this._trianglePlanes = [];
  33675. _this._id = mesh.subMeshes.length - 1;
  33676. if (createBoundingBox) {
  33677. _this.refreshBoundingInfo();
  33678. mesh.computeWorldMatrix(true);
  33679. }
  33680. return _this;
  33681. }
  33682. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33683. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33684. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33685. };
  33686. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33687. get: function () {
  33688. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  33689. },
  33690. enumerable: true,
  33691. configurable: true
  33692. });
  33693. /**
  33694. * Returns the submesh BoudingInfo object.
  33695. */
  33696. SubMesh.prototype.getBoundingInfo = function () {
  33697. if (this.IsGlobal) {
  33698. return this._mesh.getBoundingInfo();
  33699. }
  33700. return this._boundingInfo;
  33701. };
  33702. /**
  33703. * Sets the submesh BoundingInfo.
  33704. * Return the SubMesh.
  33705. */
  33706. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33707. this._boundingInfo = boundingInfo;
  33708. return this;
  33709. };
  33710. /**
  33711. * Returns the mesh of the current submesh.
  33712. */
  33713. SubMesh.prototype.getMesh = function () {
  33714. return this._mesh;
  33715. };
  33716. /**
  33717. * Returns the rendering mesh of the submesh.
  33718. */
  33719. SubMesh.prototype.getRenderingMesh = function () {
  33720. return this._renderingMesh;
  33721. };
  33722. /**
  33723. * Returns the submesh material.
  33724. */
  33725. SubMesh.prototype.getMaterial = function () {
  33726. var rootMaterial = this._renderingMesh.material;
  33727. if (rootMaterial === null || rootMaterial === undefined) {
  33728. return this._mesh.getScene().defaultMaterial;
  33729. }
  33730. else if (rootMaterial.getSubMaterial) {
  33731. var multiMaterial = rootMaterial;
  33732. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33733. if (this._currentMaterial !== effectiveMaterial) {
  33734. this._currentMaterial = effectiveMaterial;
  33735. this._materialDefines = null;
  33736. }
  33737. return effectiveMaterial;
  33738. }
  33739. return rootMaterial;
  33740. };
  33741. // Methods
  33742. /**
  33743. * Sets a new updated BoundingInfo object to the submesh.
  33744. * Returns the SubMesh.
  33745. */
  33746. SubMesh.prototype.refreshBoundingInfo = function () {
  33747. this._lastColliderWorldVertices = null;
  33748. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33749. return this;
  33750. }
  33751. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33752. if (!data) {
  33753. this._boundingInfo = this._mesh.getBoundingInfo();
  33754. return this;
  33755. }
  33756. var indices = this._renderingMesh.getIndices();
  33757. var extend;
  33758. //is this the only submesh?
  33759. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33760. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33761. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33762. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33763. }
  33764. else {
  33765. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33766. }
  33767. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33768. return this;
  33769. };
  33770. /** @hidden */
  33771. SubMesh.prototype._checkCollision = function (collider) {
  33772. var boundingInfo = this.getBoundingInfo();
  33773. return boundingInfo._checkCollision(collider);
  33774. };
  33775. /**
  33776. * Updates the submesh BoundingInfo.
  33777. * Returns the Submesh.
  33778. */
  33779. SubMesh.prototype.updateBoundingInfo = function (world) {
  33780. var boundingInfo = this.getBoundingInfo();
  33781. if (!boundingInfo) {
  33782. this.refreshBoundingInfo();
  33783. boundingInfo = this.getBoundingInfo();
  33784. }
  33785. boundingInfo.update(world);
  33786. return this;
  33787. };
  33788. /**
  33789. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33790. * Boolean returned.
  33791. */
  33792. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33793. var boundingInfo = this.getBoundingInfo();
  33794. if (!boundingInfo) {
  33795. return false;
  33796. }
  33797. return boundingInfo.isInFrustum(frustumPlanes);
  33798. };
  33799. /**
  33800. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33801. * Boolean returned.
  33802. */
  33803. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33804. var boundingInfo = this.getBoundingInfo();
  33805. if (!boundingInfo) {
  33806. return false;
  33807. }
  33808. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33809. };
  33810. /**
  33811. * Renders the submesh.
  33812. * Returns it.
  33813. */
  33814. SubMesh.prototype.render = function (enableAlphaMode) {
  33815. this._renderingMesh.render(this, enableAlphaMode);
  33816. return this;
  33817. };
  33818. /**
  33819. * Returns a new Index Buffer.
  33820. * Type returned : WebGLBuffer.
  33821. */
  33822. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33823. if (!this._linesIndexBuffer) {
  33824. var linesIndices = [];
  33825. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33826. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33827. }
  33828. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33829. this.linesIndexCount = linesIndices.length;
  33830. }
  33831. return this._linesIndexBuffer;
  33832. };
  33833. /**
  33834. * True is the passed Ray intersects the submesh bounding box.
  33835. * Boolean returned.
  33836. */
  33837. SubMesh.prototype.canIntersects = function (ray) {
  33838. var boundingInfo = this.getBoundingInfo();
  33839. if (!boundingInfo) {
  33840. return false;
  33841. }
  33842. return ray.intersectsBox(boundingInfo.boundingBox);
  33843. };
  33844. /**
  33845. * Returns an object IntersectionInfo.
  33846. */
  33847. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33848. var intersectInfo = null;
  33849. var material = this.getMaterial();
  33850. if (!material) {
  33851. return null;
  33852. }
  33853. switch (material.fillMode) {
  33854. case BABYLON.Material.PointListDrawMode:
  33855. case BABYLON.Material.LineListDrawMode:
  33856. case BABYLON.Material.LineLoopDrawMode:
  33857. case BABYLON.Material.LineStripDrawMode:
  33858. case BABYLON.Material.TriangleFanDrawMode:
  33859. case BABYLON.Material.TriangleStripDrawMode:
  33860. return null;
  33861. }
  33862. // LineMesh first as it's also a Mesh...
  33863. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33864. var lineMesh = this._mesh;
  33865. // Line test
  33866. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33867. var p0 = positions[indices[index]];
  33868. var p1 = positions[indices[index + 1]];
  33869. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33870. if (length < 0) {
  33871. continue;
  33872. }
  33873. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33874. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33875. if (fastCheck) {
  33876. break;
  33877. }
  33878. }
  33879. }
  33880. }
  33881. else {
  33882. // Triangles test
  33883. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33884. var p0 = positions[indices[index]];
  33885. var p1 = positions[indices[index + 1]];
  33886. var p2 = positions[indices[index + 2]];
  33887. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33888. if (currentIntersectInfo) {
  33889. if (currentIntersectInfo.distance < 0) {
  33890. continue;
  33891. }
  33892. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33893. intersectInfo = currentIntersectInfo;
  33894. intersectInfo.faceId = index / 3;
  33895. if (fastCheck) {
  33896. break;
  33897. }
  33898. }
  33899. }
  33900. }
  33901. }
  33902. return intersectInfo;
  33903. };
  33904. /** @hidden */
  33905. SubMesh.prototype._rebuild = function () {
  33906. if (this._linesIndexBuffer) {
  33907. this._linesIndexBuffer = null;
  33908. }
  33909. };
  33910. // Clone
  33911. /**
  33912. * Creates a new Submesh from the passed Mesh.
  33913. */
  33914. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33915. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33916. if (!this.IsGlobal) {
  33917. var boundingInfo = this.getBoundingInfo();
  33918. if (!boundingInfo) {
  33919. return result;
  33920. }
  33921. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33922. }
  33923. return result;
  33924. };
  33925. // Dispose
  33926. /**
  33927. * Disposes the Submesh.
  33928. * Returns nothing.
  33929. */
  33930. SubMesh.prototype.dispose = function () {
  33931. if (this._linesIndexBuffer) {
  33932. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33933. this._linesIndexBuffer = null;
  33934. }
  33935. // Remove from mesh
  33936. var index = this._mesh.subMeshes.indexOf(this);
  33937. this._mesh.subMeshes.splice(index, 1);
  33938. };
  33939. // Statics
  33940. /**
  33941. * Creates a new Submesh from the passed parameters :
  33942. * - materialIndex (integer) : the index of the main mesh material.
  33943. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  33944. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  33945. * - mesh (Mesh) : the main mesh to create the submesh from.
  33946. * - renderingMesh (optional Mesh) : rendering mesh.
  33947. */
  33948. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  33949. var minVertexIndex = Number.MAX_VALUE;
  33950. var maxVertexIndex = -Number.MAX_VALUE;
  33951. renderingMesh = (renderingMesh || mesh);
  33952. var indices = renderingMesh.getIndices();
  33953. for (var index = startIndex; index < startIndex + indexCount; index++) {
  33954. var vertexIndex = indices[index];
  33955. if (vertexIndex < minVertexIndex)
  33956. minVertexIndex = vertexIndex;
  33957. if (vertexIndex > maxVertexIndex)
  33958. maxVertexIndex = vertexIndex;
  33959. }
  33960. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  33961. };
  33962. return SubMesh;
  33963. }(BaseSubMesh));
  33964. BABYLON.SubMesh = SubMesh;
  33965. })(BABYLON || (BABYLON = {}));
  33966. //# sourceMappingURL=babylon.subMesh.js.map
  33967. var __assign = (this && this.__assign) || function () {
  33968. __assign = Object.assign || function(t) {
  33969. for (var s, i = 1, n = arguments.length; i < n; i++) {
  33970. s = arguments[i];
  33971. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  33972. t[p] = s[p];
  33973. }
  33974. return t;
  33975. };
  33976. return __assign.apply(this, arguments);
  33977. };
  33978. var BABYLON;
  33979. (function (BABYLON) {
  33980. /**
  33981. * Manages the defines for the Material
  33982. */
  33983. var MaterialDefines = /** @class */ (function () {
  33984. function MaterialDefines() {
  33985. this._isDirty = true;
  33986. /** @hidden */
  33987. this._areLightsDirty = true;
  33988. /** @hidden */
  33989. this._areAttributesDirty = true;
  33990. /** @hidden */
  33991. this._areTexturesDirty = true;
  33992. /** @hidden */
  33993. this._areFresnelDirty = true;
  33994. /** @hidden */
  33995. this._areMiscDirty = true;
  33996. /** @hidden */
  33997. this._areImageProcessingDirty = true;
  33998. /** @hidden */
  33999. this._normals = false;
  34000. /** @hidden */
  34001. this._uvs = false;
  34002. /** @hidden */
  34003. this._needNormals = false;
  34004. /** @hidden */
  34005. this._needUVs = false;
  34006. }
  34007. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34008. /**
  34009. * Specifies if the material needs to be re-calculated
  34010. */
  34011. get: function () {
  34012. return this._isDirty;
  34013. },
  34014. enumerable: true,
  34015. configurable: true
  34016. });
  34017. /**
  34018. * Marks the material to indicate that it has been re-calculated
  34019. */
  34020. MaterialDefines.prototype.markAsProcessed = function () {
  34021. this._isDirty = false;
  34022. this._areAttributesDirty = false;
  34023. this._areTexturesDirty = false;
  34024. this._areFresnelDirty = false;
  34025. this._areLightsDirty = false;
  34026. this._areMiscDirty = false;
  34027. this._areImageProcessingDirty = false;
  34028. };
  34029. /**
  34030. * Marks the material to indicate that it needs to be re-calculated
  34031. */
  34032. MaterialDefines.prototype.markAsUnprocessed = function () {
  34033. this._isDirty = true;
  34034. };
  34035. /**
  34036. * Marks the material to indicate all of its defines need to be re-calculated
  34037. */
  34038. MaterialDefines.prototype.markAllAsDirty = function () {
  34039. this._areTexturesDirty = true;
  34040. this._areAttributesDirty = true;
  34041. this._areLightsDirty = true;
  34042. this._areFresnelDirty = true;
  34043. this._areMiscDirty = true;
  34044. this._areImageProcessingDirty = true;
  34045. this._isDirty = true;
  34046. };
  34047. /**
  34048. * Marks the material to indicate that image processing needs to be re-calculated
  34049. */
  34050. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34051. this._areImageProcessingDirty = true;
  34052. this._isDirty = true;
  34053. };
  34054. /**
  34055. * Marks the material to indicate the lights need to be re-calculated
  34056. */
  34057. MaterialDefines.prototype.markAsLightDirty = function () {
  34058. this._areLightsDirty = true;
  34059. this._isDirty = true;
  34060. };
  34061. /**
  34062. * Marks the attribute state as changed
  34063. */
  34064. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34065. this._areAttributesDirty = true;
  34066. this._isDirty = true;
  34067. };
  34068. /**
  34069. * Marks the texture state as changed
  34070. */
  34071. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34072. this._areTexturesDirty = true;
  34073. this._isDirty = true;
  34074. };
  34075. /**
  34076. * Marks the fresnel state as changed
  34077. */
  34078. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34079. this._areFresnelDirty = true;
  34080. this._isDirty = true;
  34081. };
  34082. /**
  34083. * Marks the misc state as changed
  34084. */
  34085. MaterialDefines.prototype.markAsMiscDirty = function () {
  34086. this._areMiscDirty = true;
  34087. this._isDirty = true;
  34088. };
  34089. /**
  34090. * Rebuilds the material defines
  34091. */
  34092. MaterialDefines.prototype.rebuild = function () {
  34093. if (this._keys) {
  34094. delete this._keys;
  34095. }
  34096. this._keys = [];
  34097. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34098. var key = _a[_i];
  34099. if (key[0] === "_") {
  34100. continue;
  34101. }
  34102. this._keys.push(key);
  34103. }
  34104. };
  34105. /**
  34106. * Specifies if two material defines are equal
  34107. * @param other - A material define instance to compare to
  34108. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34109. */
  34110. MaterialDefines.prototype.isEqual = function (other) {
  34111. if (this._keys.length !== other._keys.length) {
  34112. return false;
  34113. }
  34114. for (var index = 0; index < this._keys.length; index++) {
  34115. var prop = this._keys[index];
  34116. if (this[prop] !== other[prop]) {
  34117. return false;
  34118. }
  34119. }
  34120. return true;
  34121. };
  34122. /**
  34123. * Clones this instance's defines to another instance
  34124. * @param other - material defines to clone values to
  34125. */
  34126. MaterialDefines.prototype.cloneTo = function (other) {
  34127. if (this._keys.length !== other._keys.length) {
  34128. other._keys = this._keys.slice(0);
  34129. }
  34130. for (var index = 0; index < this._keys.length; index++) {
  34131. var prop = this._keys[index];
  34132. other[prop] = this[prop];
  34133. }
  34134. };
  34135. /**
  34136. * Resets the material define values
  34137. */
  34138. MaterialDefines.prototype.reset = function () {
  34139. for (var index = 0; index < this._keys.length; index++) {
  34140. var prop = this._keys[index];
  34141. var type = typeof this[prop];
  34142. switch (type) {
  34143. case "number":
  34144. this[prop] = 0;
  34145. break;
  34146. case "string":
  34147. this[prop] = "";
  34148. break;
  34149. default:
  34150. this[prop] = false;
  34151. break;
  34152. }
  34153. }
  34154. };
  34155. /**
  34156. * Converts the material define values to a string
  34157. * @returns - String of material define information
  34158. */
  34159. MaterialDefines.prototype.toString = function () {
  34160. var result = "";
  34161. for (var index = 0; index < this._keys.length; index++) {
  34162. var prop = this._keys[index];
  34163. var value = this[prop];
  34164. var type = typeof value;
  34165. switch (type) {
  34166. case "number":
  34167. case "string":
  34168. result += "#define " + prop + " " + value + "\n";
  34169. break;
  34170. default:
  34171. if (value) {
  34172. result += "#define " + prop + "\n";
  34173. }
  34174. break;
  34175. }
  34176. }
  34177. return result;
  34178. };
  34179. return MaterialDefines;
  34180. }());
  34181. BABYLON.MaterialDefines = MaterialDefines;
  34182. /**
  34183. * Base class for the main features of a material in Babylon.js
  34184. */
  34185. var Material = /** @class */ (function () {
  34186. /**
  34187. * Creates a material instance
  34188. * @param name defines the name of the material
  34189. * @param scene defines the scene to reference
  34190. * @param doNotAdd specifies if the material should be added to the scene
  34191. */
  34192. function Material(name, scene, doNotAdd) {
  34193. /**
  34194. * Specifies if the ready state should be checked on each call
  34195. */
  34196. this.checkReadyOnEveryCall = false;
  34197. /**
  34198. * Specifies if the ready state should be checked once
  34199. */
  34200. this.checkReadyOnlyOnce = false;
  34201. /**
  34202. * The state of the material
  34203. */
  34204. this.state = "";
  34205. /**
  34206. * The alpha value of the material
  34207. */
  34208. this._alpha = 1.0;
  34209. /**
  34210. * Specifies if back face culling is enabled
  34211. */
  34212. this._backFaceCulling = true;
  34213. /**
  34214. * Gets a boolean indicating that current material needs to register RTT
  34215. */
  34216. this.hasRenderTargetTextures = false;
  34217. /**
  34218. * Specifies if the material should be serialized
  34219. */
  34220. this.doNotSerialize = false;
  34221. /**
  34222. * Specifies if the effect should be stored on sub meshes
  34223. */
  34224. this.storeEffectOnSubMeshes = false;
  34225. /**
  34226. * An event triggered when the material is disposed
  34227. */
  34228. this.onDisposeObservable = new BABYLON.Observable();
  34229. /**
  34230. * Stores the value of the alpha mode
  34231. */
  34232. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34233. /**
  34234. * Stores the state of the need depth pre-pass value
  34235. */
  34236. this._needDepthPrePass = false;
  34237. /**
  34238. * Specifies if depth writing should be disabled
  34239. */
  34240. this.disableDepthWrite = false;
  34241. /**
  34242. * Specifies if depth writing should be forced
  34243. */
  34244. this.forceDepthWrite = false;
  34245. /**
  34246. * Specifies if there should be a separate pass for culling
  34247. */
  34248. this.separateCullingPass = false;
  34249. /**
  34250. * Stores the state specifing if fog should be enabled
  34251. */
  34252. this._fogEnabled = true;
  34253. /**
  34254. * Stores the size of points
  34255. */
  34256. this.pointSize = 1.0;
  34257. /**
  34258. * Stores the z offset value
  34259. */
  34260. this.zOffset = 0;
  34261. /**
  34262. * @hidden
  34263. * Specifies if the material was previously ready
  34264. */
  34265. this._wasPreviouslyReady = false;
  34266. /**
  34267. * Stores the fill mode state
  34268. */
  34269. this._fillMode = Material.TriangleFillMode;
  34270. this.name = name;
  34271. this.id = name || BABYLON.Tools.RandomId();
  34272. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34273. this.uniqueId = this._scene.getUniqueId();
  34274. if (this._scene.useRightHandedSystem) {
  34275. this.sideOrientation = Material.ClockWiseSideOrientation;
  34276. }
  34277. else {
  34278. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34279. }
  34280. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34281. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34282. if (!doNotAdd) {
  34283. this._scene.materials.push(this);
  34284. }
  34285. }
  34286. Object.defineProperty(Material, "TriangleFillMode", {
  34287. /**
  34288. * Returns the triangle fill mode
  34289. */
  34290. get: function () {
  34291. return Material._TriangleFillMode;
  34292. },
  34293. enumerable: true,
  34294. configurable: true
  34295. });
  34296. Object.defineProperty(Material, "WireFrameFillMode", {
  34297. /**
  34298. * Returns the wireframe mode
  34299. */
  34300. get: function () {
  34301. return Material._WireFrameFillMode;
  34302. },
  34303. enumerable: true,
  34304. configurable: true
  34305. });
  34306. Object.defineProperty(Material, "PointFillMode", {
  34307. /**
  34308. * Returns the point fill mode
  34309. */
  34310. get: function () {
  34311. return Material._PointFillMode;
  34312. },
  34313. enumerable: true,
  34314. configurable: true
  34315. });
  34316. Object.defineProperty(Material, "PointListDrawMode", {
  34317. /**
  34318. * Returns the point list draw mode
  34319. */
  34320. get: function () {
  34321. return Material._PointListDrawMode;
  34322. },
  34323. enumerable: true,
  34324. configurable: true
  34325. });
  34326. Object.defineProperty(Material, "LineListDrawMode", {
  34327. /**
  34328. * Returns the line list draw mode
  34329. */
  34330. get: function () {
  34331. return Material._LineListDrawMode;
  34332. },
  34333. enumerable: true,
  34334. configurable: true
  34335. });
  34336. Object.defineProperty(Material, "LineLoopDrawMode", {
  34337. /**
  34338. * Returns the line loop draw mode
  34339. */
  34340. get: function () {
  34341. return Material._LineLoopDrawMode;
  34342. },
  34343. enumerable: true,
  34344. configurable: true
  34345. });
  34346. Object.defineProperty(Material, "LineStripDrawMode", {
  34347. /**
  34348. * Returns the line strip draw mode
  34349. */
  34350. get: function () {
  34351. return Material._LineStripDrawMode;
  34352. },
  34353. enumerable: true,
  34354. configurable: true
  34355. });
  34356. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34357. /**
  34358. * Returns the triangle strip draw mode
  34359. */
  34360. get: function () {
  34361. return Material._TriangleStripDrawMode;
  34362. },
  34363. enumerable: true,
  34364. configurable: true
  34365. });
  34366. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34367. /**
  34368. * Returns the triangle fan draw mode
  34369. */
  34370. get: function () {
  34371. return Material._TriangleFanDrawMode;
  34372. },
  34373. enumerable: true,
  34374. configurable: true
  34375. });
  34376. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34377. /**
  34378. * Returns the clock-wise side orientation
  34379. */
  34380. get: function () {
  34381. return Material._ClockWiseSideOrientation;
  34382. },
  34383. enumerable: true,
  34384. configurable: true
  34385. });
  34386. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34387. /**
  34388. * Returns the counter clock-wise side orientation
  34389. */
  34390. get: function () {
  34391. return Material._CounterClockWiseSideOrientation;
  34392. },
  34393. enumerable: true,
  34394. configurable: true
  34395. });
  34396. Object.defineProperty(Material, "TextureDirtyFlag", {
  34397. /**
  34398. * Returns the dirty texture flag value
  34399. */
  34400. get: function () {
  34401. return Material._TextureDirtyFlag;
  34402. },
  34403. enumerable: true,
  34404. configurable: true
  34405. });
  34406. Object.defineProperty(Material, "LightDirtyFlag", {
  34407. /**
  34408. * Returns the dirty light flag value
  34409. */
  34410. get: function () {
  34411. return Material._LightDirtyFlag;
  34412. },
  34413. enumerable: true,
  34414. configurable: true
  34415. });
  34416. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34417. /**
  34418. * Returns the dirty fresnel flag value
  34419. */
  34420. get: function () {
  34421. return Material._FresnelDirtyFlag;
  34422. },
  34423. enumerable: true,
  34424. configurable: true
  34425. });
  34426. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34427. /**
  34428. * Returns the dirty attributes flag value
  34429. */
  34430. get: function () {
  34431. return Material._AttributesDirtyFlag;
  34432. },
  34433. enumerable: true,
  34434. configurable: true
  34435. });
  34436. Object.defineProperty(Material, "MiscDirtyFlag", {
  34437. /**
  34438. * Returns the dirty misc flag value
  34439. */
  34440. get: function () {
  34441. return Material._MiscDirtyFlag;
  34442. },
  34443. enumerable: true,
  34444. configurable: true
  34445. });
  34446. Object.defineProperty(Material.prototype, "alpha", {
  34447. /**
  34448. * Gets the alpha value of the material
  34449. */
  34450. get: function () {
  34451. return this._alpha;
  34452. },
  34453. /**
  34454. * Sets the alpha value of the material
  34455. */
  34456. set: function (value) {
  34457. if (this._alpha === value) {
  34458. return;
  34459. }
  34460. this._alpha = value;
  34461. this.markAsDirty(Material.MiscDirtyFlag);
  34462. },
  34463. enumerable: true,
  34464. configurable: true
  34465. });
  34466. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34467. /**
  34468. * Gets the back-face culling state
  34469. */
  34470. get: function () {
  34471. return this._backFaceCulling;
  34472. },
  34473. /**
  34474. * Sets the back-face culling state
  34475. */
  34476. set: function (value) {
  34477. if (this._backFaceCulling === value) {
  34478. return;
  34479. }
  34480. this._backFaceCulling = value;
  34481. this.markAsDirty(Material.TextureDirtyFlag);
  34482. },
  34483. enumerable: true,
  34484. configurable: true
  34485. });
  34486. Object.defineProperty(Material.prototype, "onDispose", {
  34487. /**
  34488. * Called during a dispose event
  34489. */
  34490. set: function (callback) {
  34491. if (this._onDisposeObserver) {
  34492. this.onDisposeObservable.remove(this._onDisposeObserver);
  34493. }
  34494. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34495. },
  34496. enumerable: true,
  34497. configurable: true
  34498. });
  34499. Object.defineProperty(Material.prototype, "onBindObservable", {
  34500. /**
  34501. * An event triggered when the material is bound
  34502. */
  34503. get: function () {
  34504. if (!this._onBindObservable) {
  34505. this._onBindObservable = new BABYLON.Observable();
  34506. }
  34507. return this._onBindObservable;
  34508. },
  34509. enumerable: true,
  34510. configurable: true
  34511. });
  34512. Object.defineProperty(Material.prototype, "onBind", {
  34513. /**
  34514. * Called during a bind event
  34515. */
  34516. set: function (callback) {
  34517. if (this._onBindObserver) {
  34518. this.onBindObservable.remove(this._onBindObserver);
  34519. }
  34520. this._onBindObserver = this.onBindObservable.add(callback);
  34521. },
  34522. enumerable: true,
  34523. configurable: true
  34524. });
  34525. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34526. /**
  34527. * An event triggered when the material is unbound
  34528. */
  34529. get: function () {
  34530. if (!this._onUnBindObservable) {
  34531. this._onUnBindObservable = new BABYLON.Observable();
  34532. }
  34533. return this._onUnBindObservable;
  34534. },
  34535. enumerable: true,
  34536. configurable: true
  34537. });
  34538. Object.defineProperty(Material.prototype, "alphaMode", {
  34539. /**
  34540. * Gets the value of the alpha mode
  34541. */
  34542. get: function () {
  34543. return this._alphaMode;
  34544. },
  34545. /**
  34546. * Sets the value of the alpha mode.
  34547. *
  34548. * | Value | Type | Description |
  34549. * | --- | --- | --- |
  34550. * | 0 | ALPHA_DISABLE | |
  34551. * | 1 | ALPHA_ADD | |
  34552. * | 2 | ALPHA_COMBINE | |
  34553. * | 3 | ALPHA_SUBTRACT | |
  34554. * | 4 | ALPHA_MULTIPLY | |
  34555. * | 5 | ALPHA_MAXIMIZED | |
  34556. * | 6 | ALPHA_ONEONE | |
  34557. * | 7 | ALPHA_PREMULTIPLIED | |
  34558. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34559. * | 9 | ALPHA_INTERPOLATE | |
  34560. * | 10 | ALPHA_SCREENMODE | |
  34561. *
  34562. */
  34563. set: function (value) {
  34564. if (this._alphaMode === value) {
  34565. return;
  34566. }
  34567. this._alphaMode = value;
  34568. this.markAsDirty(Material.TextureDirtyFlag);
  34569. },
  34570. enumerable: true,
  34571. configurable: true
  34572. });
  34573. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34574. /**
  34575. * Gets the depth pre-pass value
  34576. */
  34577. get: function () {
  34578. return this._needDepthPrePass;
  34579. },
  34580. /**
  34581. * Sets the need depth pre-pass value
  34582. */
  34583. set: function (value) {
  34584. if (this._needDepthPrePass === value) {
  34585. return;
  34586. }
  34587. this._needDepthPrePass = value;
  34588. if (this._needDepthPrePass) {
  34589. this.checkReadyOnEveryCall = true;
  34590. }
  34591. },
  34592. enumerable: true,
  34593. configurable: true
  34594. });
  34595. Object.defineProperty(Material.prototype, "fogEnabled", {
  34596. /**
  34597. * Gets the value of the fog enabled state
  34598. */
  34599. get: function () {
  34600. return this._fogEnabled;
  34601. },
  34602. /**
  34603. * Sets the state for enabling fog
  34604. */
  34605. set: function (value) {
  34606. if (this._fogEnabled === value) {
  34607. return;
  34608. }
  34609. this._fogEnabled = value;
  34610. this.markAsDirty(Material.MiscDirtyFlag);
  34611. },
  34612. enumerable: true,
  34613. configurable: true
  34614. });
  34615. Object.defineProperty(Material.prototype, "wireframe", {
  34616. /**
  34617. * Gets a value specifying if wireframe mode is enabled
  34618. */
  34619. get: function () {
  34620. switch (this._fillMode) {
  34621. case Material.WireFrameFillMode:
  34622. case Material.LineListDrawMode:
  34623. case Material.LineLoopDrawMode:
  34624. case Material.LineStripDrawMode:
  34625. return true;
  34626. }
  34627. return this._scene.forceWireframe;
  34628. },
  34629. /**
  34630. * Sets the state of wireframe mode
  34631. */
  34632. set: function (value) {
  34633. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34634. },
  34635. enumerable: true,
  34636. configurable: true
  34637. });
  34638. Object.defineProperty(Material.prototype, "pointsCloud", {
  34639. /**
  34640. * Gets the value specifying if point clouds are enabled
  34641. */
  34642. get: function () {
  34643. switch (this._fillMode) {
  34644. case Material.PointFillMode:
  34645. case Material.PointListDrawMode:
  34646. return true;
  34647. }
  34648. return this._scene.forcePointsCloud;
  34649. },
  34650. /**
  34651. * Sets the state of point cloud mode
  34652. */
  34653. set: function (value) {
  34654. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34655. },
  34656. enumerable: true,
  34657. configurable: true
  34658. });
  34659. Object.defineProperty(Material.prototype, "fillMode", {
  34660. /**
  34661. * Gets the material fill mode
  34662. */
  34663. get: function () {
  34664. return this._fillMode;
  34665. },
  34666. /**
  34667. * Sets the material fill mode
  34668. */
  34669. set: function (value) {
  34670. if (this._fillMode === value) {
  34671. return;
  34672. }
  34673. this._fillMode = value;
  34674. this.markAsDirty(Material.MiscDirtyFlag);
  34675. },
  34676. enumerable: true,
  34677. configurable: true
  34678. });
  34679. /**
  34680. * Returns a string representation of the current material
  34681. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34682. * @returns a string with material information
  34683. */
  34684. Material.prototype.toString = function (fullDetails) {
  34685. var ret = "Name: " + this.name;
  34686. if (fullDetails) {
  34687. }
  34688. return ret;
  34689. };
  34690. /**
  34691. * Gets the class name of the material
  34692. * @returns a string with the class name of the material
  34693. */
  34694. Material.prototype.getClassName = function () {
  34695. return "Material";
  34696. };
  34697. Object.defineProperty(Material.prototype, "isFrozen", {
  34698. /**
  34699. * Specifies if updates for the material been locked
  34700. */
  34701. get: function () {
  34702. return this.checkReadyOnlyOnce;
  34703. },
  34704. enumerable: true,
  34705. configurable: true
  34706. });
  34707. /**
  34708. * Locks updates for the material
  34709. */
  34710. Material.prototype.freeze = function () {
  34711. this.checkReadyOnlyOnce = true;
  34712. };
  34713. /**
  34714. * Unlocks updates for the material
  34715. */
  34716. Material.prototype.unfreeze = function () {
  34717. this.checkReadyOnlyOnce = false;
  34718. };
  34719. /**
  34720. * Specifies if the material is ready to be used
  34721. * @param mesh defines the mesh to check
  34722. * @param useInstances specifies if instances should be used
  34723. * @returns a boolean indicating if the material is ready to be used
  34724. */
  34725. Material.prototype.isReady = function (mesh, useInstances) {
  34726. return true;
  34727. };
  34728. /**
  34729. * Specifies that the submesh is ready to be used
  34730. * @param mesh defines the mesh to check
  34731. * @param subMesh defines which submesh to check
  34732. * @param useInstances specifies that instances should be used
  34733. * @returns a boolean indicating that the submesh is ready or not
  34734. */
  34735. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34736. return false;
  34737. };
  34738. /**
  34739. * Returns the material effect
  34740. * @returns the effect associated with the material
  34741. */
  34742. Material.prototype.getEffect = function () {
  34743. return this._effect;
  34744. };
  34745. /**
  34746. * Returns the current scene
  34747. * @returns a Scene
  34748. */
  34749. Material.prototype.getScene = function () {
  34750. return this._scene;
  34751. };
  34752. /**
  34753. * Specifies if the material will require alpha blending
  34754. * @returns a boolean specifying if alpha blending is needed
  34755. */
  34756. Material.prototype.needAlphaBlending = function () {
  34757. return (this.alpha < 1.0);
  34758. };
  34759. /**
  34760. * Specifies if the mesh will require alpha blending
  34761. * @param mesh defines the mesh to check
  34762. * @returns a boolean specifying if alpha blending is needed for the mesh
  34763. */
  34764. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34765. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34766. };
  34767. /**
  34768. * Specifies if this material should be rendered in alpha test mode
  34769. * @returns a boolean specifying if an alpha test is needed.
  34770. */
  34771. Material.prototype.needAlphaTesting = function () {
  34772. return false;
  34773. };
  34774. /**
  34775. * Gets the texture used for the alpha test
  34776. * @returns the texture to use for alpha testing
  34777. */
  34778. Material.prototype.getAlphaTestTexture = function () {
  34779. return null;
  34780. };
  34781. /**
  34782. * Marks the material to indicate that it needs to be re-calculated
  34783. */
  34784. Material.prototype.markDirty = function () {
  34785. this._wasPreviouslyReady = false;
  34786. };
  34787. /** @hidden */
  34788. Material.prototype._preBind = function (effect, overrideOrientation) {
  34789. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34790. var engine = this._scene.getEngine();
  34791. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34792. var reverse = orientation === Material.ClockWiseSideOrientation;
  34793. engine.enableEffect(effect ? effect : this._effect);
  34794. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34795. return reverse;
  34796. };
  34797. /**
  34798. * Binds the material to the mesh
  34799. * @param world defines the world transformation matrix
  34800. * @param mesh defines the mesh to bind the material to
  34801. */
  34802. Material.prototype.bind = function (world, mesh) {
  34803. };
  34804. /**
  34805. * Binds the submesh to the material
  34806. * @param world defines the world transformation matrix
  34807. * @param mesh defines the mesh containing the submesh
  34808. * @param subMesh defines the submesh to bind the material to
  34809. */
  34810. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34811. };
  34812. /**
  34813. * Binds the world matrix to the material
  34814. * @param world defines the world transformation matrix
  34815. */
  34816. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34817. };
  34818. /**
  34819. * Binds the scene's uniform buffer to the effect.
  34820. * @param effect defines the effect to bind to the scene uniform buffer
  34821. * @param sceneUbo defines the uniform buffer storing scene data
  34822. */
  34823. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34824. sceneUbo.bindToEffect(effect, "Scene");
  34825. };
  34826. /**
  34827. * Binds the view matrix to the effect
  34828. * @param effect defines the effect to bind the view matrix to
  34829. */
  34830. Material.prototype.bindView = function (effect) {
  34831. if (!this._useUBO) {
  34832. effect.setMatrix("view", this.getScene().getViewMatrix());
  34833. }
  34834. else {
  34835. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34836. }
  34837. };
  34838. /**
  34839. * Binds the view projection matrix to the effect
  34840. * @param effect defines the effect to bind the view projection matrix to
  34841. */
  34842. Material.prototype.bindViewProjection = function (effect) {
  34843. if (!this._useUBO) {
  34844. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34845. }
  34846. else {
  34847. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34848. }
  34849. };
  34850. /**
  34851. * Specifies if material alpha testing should be turned on for the mesh
  34852. * @param mesh defines the mesh to check
  34853. */
  34854. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34855. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34856. };
  34857. /**
  34858. * Processes to execute after binding the material to a mesh
  34859. * @param mesh defines the rendered mesh
  34860. */
  34861. Material.prototype._afterBind = function (mesh) {
  34862. this._scene._cachedMaterial = this;
  34863. if (mesh) {
  34864. this._scene._cachedVisibility = mesh.visibility;
  34865. }
  34866. else {
  34867. this._scene._cachedVisibility = 1;
  34868. }
  34869. if (this._onBindObservable && mesh) {
  34870. this._onBindObservable.notifyObservers(mesh);
  34871. }
  34872. if (this.disableDepthWrite) {
  34873. var engine = this._scene.getEngine();
  34874. this._cachedDepthWriteState = engine.getDepthWrite();
  34875. engine.setDepthWrite(false);
  34876. }
  34877. };
  34878. /**
  34879. * Unbinds the material from the mesh
  34880. */
  34881. Material.prototype.unbind = function () {
  34882. if (this._onUnBindObservable) {
  34883. this._onUnBindObservable.notifyObservers(this);
  34884. }
  34885. if (this.disableDepthWrite) {
  34886. var engine = this._scene.getEngine();
  34887. engine.setDepthWrite(this._cachedDepthWriteState);
  34888. }
  34889. };
  34890. /**
  34891. * Gets the active textures from the material
  34892. * @returns an array of textures
  34893. */
  34894. Material.prototype.getActiveTextures = function () {
  34895. return [];
  34896. };
  34897. /**
  34898. * Specifies if the material uses a texture
  34899. * @param texture defines the texture to check against the material
  34900. * @returns a boolean specifying if the material uses the texture
  34901. */
  34902. Material.prototype.hasTexture = function (texture) {
  34903. return false;
  34904. };
  34905. /**
  34906. * Makes a duplicate of the material, and gives it a new name
  34907. * @param name defines the new name for the duplicated material
  34908. * @returns the cloned material
  34909. */
  34910. Material.prototype.clone = function (name) {
  34911. return null;
  34912. };
  34913. /**
  34914. * Gets the meshes bound to the material
  34915. * @returns an array of meshes bound to the material
  34916. */
  34917. Material.prototype.getBindedMeshes = function () {
  34918. var result = new Array();
  34919. for (var index = 0; index < this._scene.meshes.length; index++) {
  34920. var mesh = this._scene.meshes[index];
  34921. if (mesh.material === this) {
  34922. result.push(mesh);
  34923. }
  34924. }
  34925. return result;
  34926. };
  34927. /**
  34928. * Force shader compilation
  34929. * @param mesh defines the mesh associated with this material
  34930. * @param onCompiled defines a function to execute once the material is compiled
  34931. * @param options defines the options to configure the compilation
  34932. */
  34933. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34934. var _this = this;
  34935. var localOptions = __assign({ clipPlane: false }, options);
  34936. var subMesh = new BABYLON.BaseSubMesh();
  34937. var scene = this.getScene();
  34938. var checkReady = function () {
  34939. if (!_this._scene || !_this._scene.getEngine()) {
  34940. return;
  34941. }
  34942. if (subMesh._materialDefines) {
  34943. subMesh._materialDefines._renderId = -1;
  34944. }
  34945. var clipPlaneState = scene.clipPlane;
  34946. if (localOptions.clipPlane) {
  34947. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  34948. }
  34949. if (_this.storeEffectOnSubMeshes) {
  34950. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  34951. if (onCompiled) {
  34952. onCompiled(_this);
  34953. }
  34954. }
  34955. else {
  34956. setTimeout(checkReady, 16);
  34957. }
  34958. }
  34959. else {
  34960. if (_this.isReady(mesh)) {
  34961. if (onCompiled) {
  34962. onCompiled(_this);
  34963. }
  34964. }
  34965. else {
  34966. setTimeout(checkReady, 16);
  34967. }
  34968. }
  34969. if (localOptions.clipPlane) {
  34970. scene.clipPlane = clipPlaneState;
  34971. }
  34972. };
  34973. checkReady();
  34974. };
  34975. /**
  34976. * Force shader compilation
  34977. * @param mesh defines the mesh that will use this material
  34978. * @param options defines additional options for compiling the shaders
  34979. * @returns a promise that resolves when the compilation completes
  34980. */
  34981. Material.prototype.forceCompilationAsync = function (mesh, options) {
  34982. var _this = this;
  34983. return new Promise(function (resolve) {
  34984. _this.forceCompilation(mesh, function () {
  34985. resolve();
  34986. }, options);
  34987. });
  34988. };
  34989. /**
  34990. * Marks a define in the material to indicate that it needs to be re-computed
  34991. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  34992. */
  34993. Material.prototype.markAsDirty = function (flag) {
  34994. if (flag & Material.TextureDirtyFlag) {
  34995. this._markAllSubMeshesAsTexturesDirty();
  34996. }
  34997. if (flag & Material.LightDirtyFlag) {
  34998. this._markAllSubMeshesAsLightsDirty();
  34999. }
  35000. if (flag & Material.FresnelDirtyFlag) {
  35001. this._markAllSubMeshesAsFresnelDirty();
  35002. }
  35003. if (flag & Material.AttributesDirtyFlag) {
  35004. this._markAllSubMeshesAsAttributesDirty();
  35005. }
  35006. if (flag & Material.MiscDirtyFlag) {
  35007. this._markAllSubMeshesAsMiscDirty();
  35008. }
  35009. this.getScene().resetCachedMaterial();
  35010. };
  35011. /**
  35012. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35013. * @param func defines a function which checks material defines against the submeshes
  35014. */
  35015. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35016. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35017. var mesh = _a[_i];
  35018. if (!mesh.subMeshes) {
  35019. continue;
  35020. }
  35021. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35022. var subMesh = _c[_b];
  35023. if (subMesh.getMaterial() !== this) {
  35024. continue;
  35025. }
  35026. if (!subMesh._materialDefines) {
  35027. continue;
  35028. }
  35029. func(subMesh._materialDefines);
  35030. }
  35031. }
  35032. };
  35033. /**
  35034. * Indicates that image processing needs to be re-calculated for all submeshes
  35035. */
  35036. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35037. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35038. };
  35039. /**
  35040. * Indicates that textures need to be re-calculated for all submeshes
  35041. */
  35042. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35043. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35044. };
  35045. /**
  35046. * Indicates that fresnel needs to be re-calculated for all submeshes
  35047. */
  35048. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35049. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35050. };
  35051. /**
  35052. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35053. */
  35054. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35055. this._markAllSubMeshesAsDirty(function (defines) {
  35056. defines.markAsFresnelDirty();
  35057. defines.markAsMiscDirty();
  35058. });
  35059. };
  35060. /**
  35061. * Indicates that lights need to be re-calculated for all submeshes
  35062. */
  35063. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35064. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35065. };
  35066. /**
  35067. * Indicates that attributes need to be re-calculated for all submeshes
  35068. */
  35069. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35070. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35071. };
  35072. /**
  35073. * Indicates that misc needs to be re-calculated for all submeshes
  35074. */
  35075. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35076. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35077. };
  35078. /**
  35079. * Indicates that textures and misc need to be re-calculated for all submeshes
  35080. */
  35081. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35082. this._markAllSubMeshesAsDirty(function (defines) {
  35083. defines.markAsTexturesDirty();
  35084. defines.markAsMiscDirty();
  35085. });
  35086. };
  35087. /**
  35088. * Disposes the material
  35089. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35090. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35091. */
  35092. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35093. // Animations
  35094. this.getScene().stopAnimation(this);
  35095. this.getScene().freeProcessedMaterials();
  35096. // Remove from scene
  35097. var index = this._scene.materials.indexOf(this);
  35098. if (index >= 0) {
  35099. this._scene.materials.splice(index, 1);
  35100. }
  35101. // Remove from meshes
  35102. for (index = 0; index < this._scene.meshes.length; index++) {
  35103. var mesh = this._scene.meshes[index];
  35104. if (mesh.material === this) {
  35105. mesh.material = null;
  35106. if (mesh.geometry) {
  35107. var geometry = (mesh.geometry);
  35108. if (this.storeEffectOnSubMeshes) {
  35109. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35110. var subMesh = _a[_i];
  35111. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35112. if (forceDisposeEffect && subMesh._materialEffect) {
  35113. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35114. }
  35115. }
  35116. }
  35117. else {
  35118. geometry._releaseVertexArrayObject(this._effect);
  35119. }
  35120. }
  35121. }
  35122. }
  35123. this._uniformBuffer.dispose();
  35124. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35125. if (forceDisposeEffect && this._effect) {
  35126. if (!this.storeEffectOnSubMeshes) {
  35127. this._scene.getEngine()._releaseEffect(this._effect);
  35128. }
  35129. this._effect = null;
  35130. }
  35131. // Callback
  35132. this.onDisposeObservable.notifyObservers(this);
  35133. this.onDisposeObservable.clear();
  35134. if (this._onBindObservable) {
  35135. this._onBindObservable.clear();
  35136. }
  35137. if (this._onUnBindObservable) {
  35138. this._onUnBindObservable.clear();
  35139. }
  35140. };
  35141. /**
  35142. * Serializes this material
  35143. * @returns the serialized material object
  35144. */
  35145. Material.prototype.serialize = function () {
  35146. return BABYLON.SerializationHelper.Serialize(this);
  35147. };
  35148. /**
  35149. * Creates a MultiMaterial from parsed MultiMaterial data.
  35150. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35151. * @param scene defines the hosting scene
  35152. * @returns a new MultiMaterial
  35153. */
  35154. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35155. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35156. multiMaterial.id = parsedMultiMaterial.id;
  35157. if (BABYLON.Tags) {
  35158. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35159. }
  35160. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35161. var subMatId = parsedMultiMaterial.materials[matIndex];
  35162. if (subMatId) {
  35163. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35164. }
  35165. else {
  35166. multiMaterial.subMaterials.push(null);
  35167. }
  35168. }
  35169. return multiMaterial;
  35170. };
  35171. /**
  35172. * Creates a material from parsed material data
  35173. * @param parsedMaterial defines parsed material data
  35174. * @param scene defines the hosting scene
  35175. * @param rootUrl defines the root URL to use to load textures
  35176. * @returns a new material
  35177. */
  35178. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35179. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35180. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35181. }
  35182. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35183. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35184. if (!BABYLON.LegacyPBRMaterial) {
  35185. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35186. return;
  35187. }
  35188. }
  35189. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35190. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35191. };
  35192. // Triangle views
  35193. Material._TriangleFillMode = 0;
  35194. Material._WireFrameFillMode = 1;
  35195. Material._PointFillMode = 2;
  35196. // Draw modes
  35197. Material._PointListDrawMode = 3;
  35198. Material._LineListDrawMode = 4;
  35199. Material._LineLoopDrawMode = 5;
  35200. Material._LineStripDrawMode = 6;
  35201. Material._TriangleStripDrawMode = 7;
  35202. Material._TriangleFanDrawMode = 8;
  35203. /**
  35204. * Stores the clock-wise side orientation
  35205. */
  35206. Material._ClockWiseSideOrientation = 0;
  35207. /**
  35208. * Stores the counter clock-wise side orientation
  35209. */
  35210. Material._CounterClockWiseSideOrientation = 1;
  35211. /**
  35212. * The dirty texture flag value
  35213. */
  35214. Material._TextureDirtyFlag = 1;
  35215. /**
  35216. * The dirty light flag value
  35217. */
  35218. Material._LightDirtyFlag = 2;
  35219. /**
  35220. * The dirty fresnel flag value
  35221. */
  35222. Material._FresnelDirtyFlag = 4;
  35223. /**
  35224. * The dirty attribute flag value
  35225. */
  35226. Material._AttributesDirtyFlag = 8;
  35227. /**
  35228. * The dirty misc flag value
  35229. */
  35230. Material._MiscDirtyFlag = 16;
  35231. __decorate([
  35232. BABYLON.serialize()
  35233. ], Material.prototype, "id", void 0);
  35234. __decorate([
  35235. BABYLON.serialize()
  35236. ], Material.prototype, "uniqueId", void 0);
  35237. __decorate([
  35238. BABYLON.serialize()
  35239. ], Material.prototype, "name", void 0);
  35240. __decorate([
  35241. BABYLON.serialize()
  35242. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35243. __decorate([
  35244. BABYLON.serialize()
  35245. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35246. __decorate([
  35247. BABYLON.serialize()
  35248. ], Material.prototype, "state", void 0);
  35249. __decorate([
  35250. BABYLON.serialize("alpha")
  35251. ], Material.prototype, "_alpha", void 0);
  35252. __decorate([
  35253. BABYLON.serialize("backFaceCulling")
  35254. ], Material.prototype, "_backFaceCulling", void 0);
  35255. __decorate([
  35256. BABYLON.serialize()
  35257. ], Material.prototype, "sideOrientation", void 0);
  35258. __decorate([
  35259. BABYLON.serialize("alphaMode")
  35260. ], Material.prototype, "_alphaMode", void 0);
  35261. __decorate([
  35262. BABYLON.serialize()
  35263. ], Material.prototype, "_needDepthPrePass", void 0);
  35264. __decorate([
  35265. BABYLON.serialize()
  35266. ], Material.prototype, "disableDepthWrite", void 0);
  35267. __decorate([
  35268. BABYLON.serialize()
  35269. ], Material.prototype, "forceDepthWrite", void 0);
  35270. __decorate([
  35271. BABYLON.serialize()
  35272. ], Material.prototype, "separateCullingPass", void 0);
  35273. __decorate([
  35274. BABYLON.serialize("fogEnabled")
  35275. ], Material.prototype, "_fogEnabled", void 0);
  35276. __decorate([
  35277. BABYLON.serialize()
  35278. ], Material.prototype, "pointSize", void 0);
  35279. __decorate([
  35280. BABYLON.serialize()
  35281. ], Material.prototype, "zOffset", void 0);
  35282. __decorate([
  35283. BABYLON.serialize()
  35284. ], Material.prototype, "wireframe", null);
  35285. __decorate([
  35286. BABYLON.serialize()
  35287. ], Material.prototype, "pointsCloud", null);
  35288. __decorate([
  35289. BABYLON.serialize()
  35290. ], Material.prototype, "fillMode", null);
  35291. return Material;
  35292. }());
  35293. BABYLON.Material = Material;
  35294. })(BABYLON || (BABYLON = {}));
  35295. //# sourceMappingURL=babylon.material.js.map
  35296. var BABYLON;
  35297. (function (BABYLON) {
  35298. var UniformBuffer = /** @class */ (function () {
  35299. /**
  35300. * Uniform buffer objects.
  35301. *
  35302. * Handles blocks of uniform on the GPU.
  35303. *
  35304. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35305. *
  35306. * For more information, please refer to :
  35307. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35308. */
  35309. function UniformBuffer(engine, data, dynamic) {
  35310. this._engine = engine;
  35311. this._noUBO = !engine.supportsUniformBuffers;
  35312. this._dynamic = dynamic;
  35313. this._data = data || [];
  35314. this._uniformLocations = {};
  35315. this._uniformSizes = {};
  35316. this._uniformLocationPointer = 0;
  35317. this._needSync = false;
  35318. if (this._noUBO) {
  35319. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35320. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35321. this.updateFloat = this._updateFloatForEffect;
  35322. this.updateFloat2 = this._updateFloat2ForEffect;
  35323. this.updateFloat3 = this._updateFloat3ForEffect;
  35324. this.updateFloat4 = this._updateFloat4ForEffect;
  35325. this.updateMatrix = this._updateMatrixForEffect;
  35326. this.updateVector3 = this._updateVector3ForEffect;
  35327. this.updateVector4 = this._updateVector4ForEffect;
  35328. this.updateColor3 = this._updateColor3ForEffect;
  35329. this.updateColor4 = this._updateColor4ForEffect;
  35330. }
  35331. else {
  35332. this._engine._uniformBuffers.push(this);
  35333. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35334. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35335. this.updateFloat = this._updateFloatForUniform;
  35336. this.updateFloat2 = this._updateFloat2ForUniform;
  35337. this.updateFloat3 = this._updateFloat3ForUniform;
  35338. this.updateFloat4 = this._updateFloat4ForUniform;
  35339. this.updateMatrix = this._updateMatrixForUniform;
  35340. this.updateVector3 = this._updateVector3ForUniform;
  35341. this.updateVector4 = this._updateVector4ForUniform;
  35342. this.updateColor3 = this._updateColor3ForUniform;
  35343. this.updateColor4 = this._updateColor4ForUniform;
  35344. }
  35345. }
  35346. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35347. // Properties
  35348. /**
  35349. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35350. * or just falling back on setUniformXXX calls.
  35351. */
  35352. get: function () {
  35353. return !this._noUBO;
  35354. },
  35355. enumerable: true,
  35356. configurable: true
  35357. });
  35358. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35359. /**
  35360. * Indicates if the WebGL underlying uniform buffer is in sync
  35361. * with the javascript cache data.
  35362. */
  35363. get: function () {
  35364. return !this._needSync;
  35365. },
  35366. enumerable: true,
  35367. configurable: true
  35368. });
  35369. /**
  35370. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35371. * Also, a dynamic UniformBuffer will disable cache verification and always
  35372. * update the underlying WebGL uniform buffer to the GPU.
  35373. */
  35374. UniformBuffer.prototype.isDynamic = function () {
  35375. return this._dynamic !== undefined;
  35376. };
  35377. /**
  35378. * The data cache on JS side.
  35379. */
  35380. UniformBuffer.prototype.getData = function () {
  35381. return this._bufferData;
  35382. };
  35383. /**
  35384. * The underlying WebGL Uniform buffer.
  35385. */
  35386. UniformBuffer.prototype.getBuffer = function () {
  35387. return this._buffer;
  35388. };
  35389. /**
  35390. * std140 layout specifies how to align data within an UBO structure.
  35391. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35392. * for specs.
  35393. */
  35394. UniformBuffer.prototype._fillAlignment = function (size) {
  35395. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35396. // and 4x4 matrices
  35397. // TODO : change if other types are used
  35398. var alignment;
  35399. if (size <= 2) {
  35400. alignment = size;
  35401. }
  35402. else {
  35403. alignment = 4;
  35404. }
  35405. if ((this._uniformLocationPointer % alignment) !== 0) {
  35406. var oldPointer = this._uniformLocationPointer;
  35407. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35408. var diff = this._uniformLocationPointer - oldPointer;
  35409. for (var i = 0; i < diff; i++) {
  35410. this._data.push(0);
  35411. }
  35412. }
  35413. };
  35414. /**
  35415. * Adds an uniform in the buffer.
  35416. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35417. * for the layout to be correct !
  35418. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35419. * @param {number|number[]} size Data size, or data directly.
  35420. */
  35421. UniformBuffer.prototype.addUniform = function (name, size) {
  35422. if (this._noUBO) {
  35423. return;
  35424. }
  35425. if (this._uniformLocations[name] !== undefined) {
  35426. // Already existing uniform
  35427. return;
  35428. }
  35429. // This function must be called in the order of the shader layout !
  35430. // size can be the size of the uniform, or data directly
  35431. var data;
  35432. if (size instanceof Array) {
  35433. data = size;
  35434. size = data.length;
  35435. }
  35436. else {
  35437. size = size;
  35438. data = [];
  35439. // Fill with zeros
  35440. for (var i = 0; i < size; i++) {
  35441. data.push(0);
  35442. }
  35443. }
  35444. this._fillAlignment(size);
  35445. this._uniformSizes[name] = size;
  35446. this._uniformLocations[name] = this._uniformLocationPointer;
  35447. this._uniformLocationPointer += size;
  35448. for (var i = 0; i < size; i++) {
  35449. this._data.push(data[i]);
  35450. }
  35451. this._needSync = true;
  35452. };
  35453. /**
  35454. * Wrapper for addUniform.
  35455. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35456. * @param {Matrix} mat A 4x4 matrix.
  35457. */
  35458. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35459. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35460. };
  35461. /**
  35462. * Wrapper for addUniform.
  35463. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35464. * @param {number} x
  35465. * @param {number} y
  35466. */
  35467. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35468. var temp = [x, y];
  35469. this.addUniform(name, temp);
  35470. };
  35471. /**
  35472. * Wrapper for addUniform.
  35473. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35474. * @param {number} x
  35475. * @param {number} y
  35476. * @param {number} z
  35477. */
  35478. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35479. var temp = [x, y, z];
  35480. this.addUniform(name, temp);
  35481. };
  35482. /**
  35483. * Wrapper for addUniform.
  35484. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35485. * @param {Color3} color
  35486. */
  35487. UniformBuffer.prototype.addColor3 = function (name, color) {
  35488. var temp = new Array();
  35489. color.toArray(temp);
  35490. this.addUniform(name, temp);
  35491. };
  35492. /**
  35493. * Wrapper for addUniform.
  35494. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35495. * @param {Color3} color
  35496. * @param {number} alpha
  35497. */
  35498. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35499. var temp = new Array();
  35500. color.toArray(temp);
  35501. temp.push(alpha);
  35502. this.addUniform(name, temp);
  35503. };
  35504. /**
  35505. * Wrapper for addUniform.
  35506. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35507. * @param {Vector3} vector
  35508. */
  35509. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35510. var temp = new Array();
  35511. vector.toArray(temp);
  35512. this.addUniform(name, temp);
  35513. };
  35514. /**
  35515. * Wrapper for addUniform.
  35516. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35517. */
  35518. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35519. this.addUniform(name, 12);
  35520. };
  35521. /**
  35522. * Wrapper for addUniform.
  35523. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35524. */
  35525. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35526. this.addUniform(name, 8);
  35527. };
  35528. /**
  35529. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35530. */
  35531. UniformBuffer.prototype.create = function () {
  35532. if (this._noUBO) {
  35533. return;
  35534. }
  35535. if (this._buffer) {
  35536. return; // nothing to do
  35537. }
  35538. // See spec, alignment must be filled as a vec4
  35539. this._fillAlignment(4);
  35540. this._bufferData = new Float32Array(this._data);
  35541. this._rebuild();
  35542. this._needSync = true;
  35543. };
  35544. /** @hidden */
  35545. UniformBuffer.prototype._rebuild = function () {
  35546. if (this._noUBO) {
  35547. return;
  35548. }
  35549. if (this._dynamic) {
  35550. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35551. }
  35552. else {
  35553. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35554. }
  35555. };
  35556. /**
  35557. * Updates the WebGL Uniform Buffer on the GPU.
  35558. * If the `dynamic` flag is set to true, no cache comparison is done.
  35559. * Otherwise, the buffer will be updated only if the cache differs.
  35560. */
  35561. UniformBuffer.prototype.update = function () {
  35562. if (!this._buffer) {
  35563. this.create();
  35564. return;
  35565. }
  35566. if (!this._dynamic && !this._needSync) {
  35567. return;
  35568. }
  35569. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35570. this._needSync = false;
  35571. };
  35572. /**
  35573. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35574. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35575. * @param {number[]|Float32Array} data Flattened data
  35576. * @param {number} size Size of the data.
  35577. */
  35578. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35579. var location = this._uniformLocations[uniformName];
  35580. if (location === undefined) {
  35581. if (this._buffer) {
  35582. // Cannot add an uniform if the buffer is already created
  35583. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35584. return;
  35585. }
  35586. this.addUniform(uniformName, size);
  35587. location = this._uniformLocations[uniformName];
  35588. }
  35589. if (!this._buffer) {
  35590. this.create();
  35591. }
  35592. if (!this._dynamic) {
  35593. // Cache for static uniform buffers
  35594. var changed = false;
  35595. for (var i = 0; i < size; i++) {
  35596. if (this._bufferData[location + i] !== data[i]) {
  35597. changed = true;
  35598. this._bufferData[location + i] = data[i];
  35599. }
  35600. }
  35601. this._needSync = this._needSync || changed;
  35602. }
  35603. else {
  35604. // No cache for dynamic
  35605. for (var i = 0; i < size; i++) {
  35606. this._bufferData[location + i] = data[i];
  35607. }
  35608. }
  35609. };
  35610. // Update methods
  35611. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35612. // To match std140, matrix must be realigned
  35613. for (var i = 0; i < 3; i++) {
  35614. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35615. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35616. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35617. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35618. }
  35619. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35620. };
  35621. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35622. this._currentEffect.setMatrix3x3(name, matrix);
  35623. };
  35624. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35625. this._currentEffect.setMatrix2x2(name, matrix);
  35626. };
  35627. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35628. // To match std140, matrix must be realigned
  35629. for (var i = 0; i < 2; i++) {
  35630. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35631. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35632. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35633. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35634. }
  35635. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35636. };
  35637. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35638. this._currentEffect.setFloat(name, x);
  35639. };
  35640. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35641. UniformBuffer._tempBuffer[0] = x;
  35642. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35643. };
  35644. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35645. if (suffix === void 0) { suffix = ""; }
  35646. this._currentEffect.setFloat2(name + suffix, x, y);
  35647. };
  35648. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35649. if (suffix === void 0) { suffix = ""; }
  35650. UniformBuffer._tempBuffer[0] = x;
  35651. UniformBuffer._tempBuffer[1] = y;
  35652. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35653. };
  35654. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35655. if (suffix === void 0) { suffix = ""; }
  35656. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35657. };
  35658. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35659. if (suffix === void 0) { suffix = ""; }
  35660. UniformBuffer._tempBuffer[0] = x;
  35661. UniformBuffer._tempBuffer[1] = y;
  35662. UniformBuffer._tempBuffer[2] = z;
  35663. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35664. };
  35665. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35666. if (suffix === void 0) { suffix = ""; }
  35667. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35668. };
  35669. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35670. if (suffix === void 0) { suffix = ""; }
  35671. UniformBuffer._tempBuffer[0] = x;
  35672. UniformBuffer._tempBuffer[1] = y;
  35673. UniformBuffer._tempBuffer[2] = z;
  35674. UniformBuffer._tempBuffer[3] = w;
  35675. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35676. };
  35677. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35678. this._currentEffect.setMatrix(name, mat);
  35679. };
  35680. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35681. this.updateUniform(name, mat.toArray(), 16);
  35682. };
  35683. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35684. this._currentEffect.setVector3(name, vector);
  35685. };
  35686. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35687. vector.toArray(UniformBuffer._tempBuffer);
  35688. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35689. };
  35690. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35691. this._currentEffect.setVector4(name, vector);
  35692. };
  35693. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35694. vector.toArray(UniformBuffer._tempBuffer);
  35695. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35696. };
  35697. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35698. if (suffix === void 0) { suffix = ""; }
  35699. this._currentEffect.setColor3(name + suffix, color);
  35700. };
  35701. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35702. if (suffix === void 0) { suffix = ""; }
  35703. color.toArray(UniformBuffer._tempBuffer);
  35704. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35705. };
  35706. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35707. if (suffix === void 0) { suffix = ""; }
  35708. this._currentEffect.setColor4(name + suffix, color, alpha);
  35709. };
  35710. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35711. if (suffix === void 0) { suffix = ""; }
  35712. color.toArray(UniformBuffer._tempBuffer);
  35713. UniformBuffer._tempBuffer[3] = alpha;
  35714. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35715. };
  35716. /**
  35717. * Sets a sampler uniform on the effect.
  35718. * @param {string} name Name of the sampler.
  35719. * @param {Texture} texture
  35720. */
  35721. UniformBuffer.prototype.setTexture = function (name, texture) {
  35722. this._currentEffect.setTexture(name, texture);
  35723. };
  35724. /**
  35725. * Directly updates the value of the uniform in the cache AND on the GPU.
  35726. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35727. * @param {number[]|Float32Array} data Flattened data
  35728. */
  35729. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35730. this.updateUniform(uniformName, data, data.length);
  35731. this.update();
  35732. };
  35733. /**
  35734. * Binds this uniform buffer to an effect.
  35735. * @param {Effect} effect
  35736. * @param {string} name Name of the uniform block in the shader.
  35737. */
  35738. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35739. this._currentEffect = effect;
  35740. if (this._noUBO || !this._buffer) {
  35741. return;
  35742. }
  35743. effect.bindUniformBuffer(this._buffer, name);
  35744. };
  35745. /**
  35746. * Disposes the uniform buffer.
  35747. */
  35748. UniformBuffer.prototype.dispose = function () {
  35749. if (this._noUBO) {
  35750. return;
  35751. }
  35752. var index = this._engine._uniformBuffers.indexOf(this);
  35753. if (index !== -1) {
  35754. this._engine._uniformBuffers.splice(index, 1);
  35755. }
  35756. if (!this._buffer) {
  35757. return;
  35758. }
  35759. if (this._engine._releaseBuffer(this._buffer)) {
  35760. this._buffer = null;
  35761. }
  35762. };
  35763. // Pool for avoiding memory leaks
  35764. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35765. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35766. return UniformBuffer;
  35767. }());
  35768. BABYLON.UniformBuffer = UniformBuffer;
  35769. })(BABYLON || (BABYLON = {}));
  35770. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35771. var BABYLON;
  35772. (function (BABYLON) {
  35773. /**
  35774. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35775. */
  35776. var VertexData = /** @class */ (function () {
  35777. function VertexData() {
  35778. }
  35779. /**
  35780. * Uses the passed data array to set the set the values for the specified kind of data
  35781. * @param data a linear array of floating numbers
  35782. * @param kind the type of data that is being set, eg positions, colors etc
  35783. */
  35784. VertexData.prototype.set = function (data, kind) {
  35785. switch (kind) {
  35786. case BABYLON.VertexBuffer.PositionKind:
  35787. this.positions = data;
  35788. break;
  35789. case BABYLON.VertexBuffer.NormalKind:
  35790. this.normals = data;
  35791. break;
  35792. case BABYLON.VertexBuffer.TangentKind:
  35793. this.tangents = data;
  35794. break;
  35795. case BABYLON.VertexBuffer.UVKind:
  35796. this.uvs = data;
  35797. break;
  35798. case BABYLON.VertexBuffer.UV2Kind:
  35799. this.uvs2 = data;
  35800. break;
  35801. case BABYLON.VertexBuffer.UV3Kind:
  35802. this.uvs3 = data;
  35803. break;
  35804. case BABYLON.VertexBuffer.UV4Kind:
  35805. this.uvs4 = data;
  35806. break;
  35807. case BABYLON.VertexBuffer.UV5Kind:
  35808. this.uvs5 = data;
  35809. break;
  35810. case BABYLON.VertexBuffer.UV6Kind:
  35811. this.uvs6 = data;
  35812. break;
  35813. case BABYLON.VertexBuffer.ColorKind:
  35814. this.colors = data;
  35815. break;
  35816. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35817. this.matricesIndices = data;
  35818. break;
  35819. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35820. this.matricesWeights = data;
  35821. break;
  35822. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35823. this.matricesIndicesExtra = data;
  35824. break;
  35825. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35826. this.matricesWeightsExtra = data;
  35827. break;
  35828. }
  35829. };
  35830. /**
  35831. * Associates the vertexData to the passed Mesh.
  35832. * Sets it as updatable or not (default `false`)
  35833. * @param mesh the mesh the vertexData is applied to
  35834. * @param updatable when used and having the value true allows new data to update the vertexData
  35835. * @returns the VertexData
  35836. */
  35837. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35838. this._applyTo(mesh, updatable);
  35839. return this;
  35840. };
  35841. /**
  35842. * Associates the vertexData to the passed Geometry.
  35843. * Sets it as updatable or not (default `false`)
  35844. * @param geometry the geometry the vertexData is applied to
  35845. * @param updatable when used and having the value true allows new data to update the vertexData
  35846. * @returns VertexData
  35847. */
  35848. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35849. this._applyTo(geometry, updatable);
  35850. return this;
  35851. };
  35852. /**
  35853. * Updates the associated mesh
  35854. * @param mesh the mesh to be updated
  35855. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35856. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  35857. * @returns VertexData
  35858. */
  35859. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35860. this._update(mesh);
  35861. return this;
  35862. };
  35863. /**
  35864. * Updates the associated geometry
  35865. * @param geometry the geometry to be updated
  35866. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35867. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  35868. * @returns VertexData.
  35869. */
  35870. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35871. this._update(geometry);
  35872. return this;
  35873. };
  35874. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35875. if (updatable === void 0) { updatable = false; }
  35876. if (this.positions) {
  35877. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35878. }
  35879. if (this.normals) {
  35880. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35881. }
  35882. if (this.tangents) {
  35883. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35884. }
  35885. if (this.uvs) {
  35886. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35887. }
  35888. if (this.uvs2) {
  35889. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35890. }
  35891. if (this.uvs3) {
  35892. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35893. }
  35894. if (this.uvs4) {
  35895. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35896. }
  35897. if (this.uvs5) {
  35898. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35899. }
  35900. if (this.uvs6) {
  35901. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35902. }
  35903. if (this.colors) {
  35904. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35905. }
  35906. if (this.matricesIndices) {
  35907. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35908. }
  35909. if (this.matricesWeights) {
  35910. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35911. }
  35912. if (this.matricesIndicesExtra) {
  35913. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35914. }
  35915. if (this.matricesWeightsExtra) {
  35916. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35917. }
  35918. if (this.indices) {
  35919. meshOrGeometry.setIndices(this.indices, null, updatable);
  35920. }
  35921. else {
  35922. meshOrGeometry.setIndices([], null);
  35923. }
  35924. return this;
  35925. };
  35926. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35927. if (this.positions) {
  35928. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35929. }
  35930. if (this.normals) {
  35931. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35932. }
  35933. if (this.tangents) {
  35934. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35935. }
  35936. if (this.uvs) {
  35937. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35938. }
  35939. if (this.uvs2) {
  35940. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35941. }
  35942. if (this.uvs3) {
  35943. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35944. }
  35945. if (this.uvs4) {
  35946. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35947. }
  35948. if (this.uvs5) {
  35949. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35950. }
  35951. if (this.uvs6) {
  35952. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35953. }
  35954. if (this.colors) {
  35955. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35956. }
  35957. if (this.matricesIndices) {
  35958. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35959. }
  35960. if (this.matricesWeights) {
  35961. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35962. }
  35963. if (this.matricesIndicesExtra) {
  35964. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35965. }
  35966. if (this.matricesWeightsExtra) {
  35967. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35968. }
  35969. if (this.indices) {
  35970. meshOrGeometry.setIndices(this.indices, null);
  35971. }
  35972. return this;
  35973. };
  35974. /**
  35975. * Transforms each position and each normal of the vertexData according to the passed Matrix
  35976. * @param matrix the transforming matrix
  35977. * @returns the VertexData
  35978. */
  35979. VertexData.prototype.transform = function (matrix) {
  35980. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  35981. var transformed = BABYLON.Vector3.Zero();
  35982. var index;
  35983. if (this.positions) {
  35984. var position = BABYLON.Vector3.Zero();
  35985. for (index = 0; index < this.positions.length; index += 3) {
  35986. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  35987. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  35988. this.positions[index] = transformed.x;
  35989. this.positions[index + 1] = transformed.y;
  35990. this.positions[index + 2] = transformed.z;
  35991. }
  35992. }
  35993. if (this.normals) {
  35994. var normal = BABYLON.Vector3.Zero();
  35995. for (index = 0; index < this.normals.length; index += 3) {
  35996. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  35997. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  35998. this.normals[index] = transformed.x;
  35999. this.normals[index + 1] = transformed.y;
  36000. this.normals[index + 2] = transformed.z;
  36001. }
  36002. }
  36003. if (this.tangents) {
  36004. var tangent = BABYLON.Vector4.Zero();
  36005. var tangentTransformed = BABYLON.Vector4.Zero();
  36006. for (index = 0; index < this.tangents.length; index += 4) {
  36007. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36008. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36009. this.tangents[index] = tangentTransformed.x;
  36010. this.tangents[index + 1] = tangentTransformed.y;
  36011. this.tangents[index + 2] = tangentTransformed.z;
  36012. this.tangents[index + 3] = tangentTransformed.w;
  36013. }
  36014. }
  36015. if (flip && this.indices) {
  36016. for (index = 0; index < this.indices.length; index += 3) {
  36017. var tmp = this.indices[index + 1];
  36018. this.indices[index + 1] = this.indices[index + 2];
  36019. this.indices[index + 2] = tmp;
  36020. }
  36021. }
  36022. return this;
  36023. };
  36024. /**
  36025. * Merges the passed VertexData into the current one
  36026. * @param other the VertexData to be merged into the current one
  36027. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36028. * @returns the modified VertexData
  36029. */
  36030. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36031. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36032. this._validate();
  36033. other._validate();
  36034. if (!this.normals !== !other.normals ||
  36035. !this.tangents !== !other.tangents ||
  36036. !this.uvs !== !other.uvs ||
  36037. !this.uvs2 !== !other.uvs2 ||
  36038. !this.uvs3 !== !other.uvs3 ||
  36039. !this.uvs4 !== !other.uvs4 ||
  36040. !this.uvs5 !== !other.uvs5 ||
  36041. !this.uvs6 !== !other.uvs6 ||
  36042. !this.colors !== !other.colors ||
  36043. !this.matricesIndices !== !other.matricesIndices ||
  36044. !this.matricesWeights !== !other.matricesWeights ||
  36045. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36046. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36047. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36048. }
  36049. if (other.indices) {
  36050. if (!this.indices) {
  36051. this.indices = [];
  36052. }
  36053. var offset = this.positions ? this.positions.length / 3 : 0;
  36054. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36055. if (isSrcTypedArray) {
  36056. var len = this.indices.length + other.indices.length;
  36057. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36058. temp.set(this.indices);
  36059. var decal = this.indices.length;
  36060. for (var index = 0; index < other.indices.length; index++) {
  36061. temp[decal + index] = other.indices[index] + offset;
  36062. }
  36063. this.indices = temp;
  36064. }
  36065. else {
  36066. for (var index = 0; index < other.indices.length; index++) {
  36067. this.indices.push(other.indices[index] + offset);
  36068. }
  36069. }
  36070. }
  36071. this.positions = this._mergeElement(this.positions, other.positions);
  36072. this.normals = this._mergeElement(this.normals, other.normals);
  36073. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36074. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36075. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36076. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36077. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36078. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36079. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36080. this.colors = this._mergeElement(this.colors, other.colors);
  36081. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36082. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36083. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36084. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36085. return this;
  36086. };
  36087. VertexData.prototype._mergeElement = function (source, other) {
  36088. if (!source) {
  36089. return other;
  36090. }
  36091. if (!other) {
  36092. return source;
  36093. }
  36094. var len = other.length + source.length;
  36095. var isSrcTypedArray = source instanceof Float32Array;
  36096. var isOthTypedArray = other instanceof Float32Array;
  36097. // use non-loop method when the source is Float32Array
  36098. if (isSrcTypedArray) {
  36099. var ret32 = new Float32Array(len);
  36100. ret32.set(source);
  36101. ret32.set(other, source.length);
  36102. return ret32;
  36103. // source is number[], when other is also use concat
  36104. }
  36105. else if (!isOthTypedArray) {
  36106. return source.concat(other);
  36107. // source is a number[], but other is a Float32Array, loop required
  36108. }
  36109. else {
  36110. var ret = source.slice(0); // copy source to a separate array
  36111. for (var i = 0, len = other.length; i < len; i++) {
  36112. ret.push(other[i]);
  36113. }
  36114. return ret;
  36115. }
  36116. };
  36117. VertexData.prototype._validate = function () {
  36118. if (!this.positions) {
  36119. throw new Error("Positions are required");
  36120. }
  36121. var getElementCount = function (kind, values) {
  36122. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36123. if ((values.length % stride) !== 0) {
  36124. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36125. }
  36126. return values.length / stride;
  36127. };
  36128. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36129. var validateElementCount = function (kind, values) {
  36130. var elementCount = getElementCount(kind, values);
  36131. if (elementCount !== positionsElementCount) {
  36132. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36133. }
  36134. };
  36135. if (this.normals)
  36136. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36137. if (this.tangents)
  36138. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36139. if (this.uvs)
  36140. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36141. if (this.uvs2)
  36142. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36143. if (this.uvs3)
  36144. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36145. if (this.uvs4)
  36146. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36147. if (this.uvs5)
  36148. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36149. if (this.uvs6)
  36150. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36151. if (this.colors)
  36152. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36153. if (this.matricesIndices)
  36154. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36155. if (this.matricesWeights)
  36156. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36157. if (this.matricesIndicesExtra)
  36158. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36159. if (this.matricesWeightsExtra)
  36160. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36161. };
  36162. /**
  36163. * Serializes the VertexData
  36164. * @returns a serialized object
  36165. */
  36166. VertexData.prototype.serialize = function () {
  36167. var serializationObject = this.serialize();
  36168. if (this.positions) {
  36169. serializationObject.positions = this.positions;
  36170. }
  36171. if (this.normals) {
  36172. serializationObject.normals = this.normals;
  36173. }
  36174. if (this.tangents) {
  36175. serializationObject.tangents = this.tangents;
  36176. }
  36177. if (this.uvs) {
  36178. serializationObject.uvs = this.uvs;
  36179. }
  36180. if (this.uvs2) {
  36181. serializationObject.uvs2 = this.uvs2;
  36182. }
  36183. if (this.uvs3) {
  36184. serializationObject.uvs3 = this.uvs3;
  36185. }
  36186. if (this.uvs4) {
  36187. serializationObject.uvs4 = this.uvs4;
  36188. }
  36189. if (this.uvs5) {
  36190. serializationObject.uvs5 = this.uvs5;
  36191. }
  36192. if (this.uvs6) {
  36193. serializationObject.uvs6 = this.uvs6;
  36194. }
  36195. if (this.colors) {
  36196. serializationObject.colors = this.colors;
  36197. }
  36198. if (this.matricesIndices) {
  36199. serializationObject.matricesIndices = this.matricesIndices;
  36200. serializationObject.matricesIndices._isExpanded = true;
  36201. }
  36202. if (this.matricesWeights) {
  36203. serializationObject.matricesWeights = this.matricesWeights;
  36204. }
  36205. if (this.matricesIndicesExtra) {
  36206. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36207. serializationObject.matricesIndicesExtra._isExpanded = true;
  36208. }
  36209. if (this.matricesWeightsExtra) {
  36210. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36211. }
  36212. serializationObject.indices = this.indices;
  36213. return serializationObject;
  36214. };
  36215. // Statics
  36216. /**
  36217. * Extracts the vertexData from a mesh
  36218. * @param mesh the mesh from which to extract the VertexData
  36219. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36220. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36221. * @returns the object VertexData associated to the passed mesh
  36222. */
  36223. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36224. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36225. };
  36226. /**
  36227. * Extracts the vertexData from the geometry
  36228. * @param geometry the geometry from which to extract the VertexData
  36229. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36230. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36231. * @returns the object VertexData associated to the passed mesh
  36232. */
  36233. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36234. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36235. };
  36236. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36237. var result = new VertexData();
  36238. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36239. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36240. }
  36241. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36242. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36243. }
  36244. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36245. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36246. }
  36247. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36248. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36249. }
  36250. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36251. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36252. }
  36253. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36254. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36255. }
  36256. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36257. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36258. }
  36259. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36260. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36261. }
  36262. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36263. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36264. }
  36265. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36266. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36267. }
  36268. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36269. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36270. }
  36271. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36272. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36273. }
  36274. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36275. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36276. }
  36277. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36278. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36279. }
  36280. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36281. return result;
  36282. };
  36283. /**
  36284. * Creates the VertexData for a Ribbon
  36285. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36286. * * pathArray array of paths, each of which an array of successive Vector3
  36287. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36288. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36289. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  36290. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36291. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36292. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36293. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36294. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36295. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36296. * @returns the VertexData of the ribbon
  36297. */
  36298. VertexData.CreateRibbon = function (options) {
  36299. var pathArray = options.pathArray;
  36300. var closeArray = options.closeArray || false;
  36301. var closePath = options.closePath || false;
  36302. var invertUV = options.invertUV || false;
  36303. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36304. var offset = options.offset || defaultOffset;
  36305. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36306. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36307. var customUV = options.uvs;
  36308. var customColors = options.colors;
  36309. var positions = [];
  36310. var indices = [];
  36311. var normals = [];
  36312. var uvs = [];
  36313. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36314. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36315. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36316. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36317. var minlg; // minimal length among all paths from pathArray
  36318. var lg = []; // array of path lengths : nb of vertex per path
  36319. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36320. var p; // path iterator
  36321. var i; // point iterator
  36322. var j; // point iterator
  36323. // if single path in pathArray
  36324. if (pathArray.length < 2) {
  36325. var ar1 = [];
  36326. var ar2 = [];
  36327. for (i = 0; i < pathArray[0].length - offset; i++) {
  36328. ar1.push(pathArray[0][i]);
  36329. ar2.push(pathArray[0][i + offset]);
  36330. }
  36331. pathArray = [ar1, ar2];
  36332. }
  36333. // positions and horizontal distances (u)
  36334. var idc = 0;
  36335. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36336. var path;
  36337. var l;
  36338. minlg = pathArray[0].length;
  36339. var vectlg;
  36340. var dist;
  36341. for (p = 0; p < pathArray.length; p++) {
  36342. uTotalDistance[p] = 0;
  36343. us[p] = [0];
  36344. path = pathArray[p];
  36345. l = path.length;
  36346. minlg = (minlg < l) ? minlg : l;
  36347. j = 0;
  36348. while (j < l) {
  36349. positions.push(path[j].x, path[j].y, path[j].z);
  36350. if (j > 0) {
  36351. vectlg = path[j].subtract(path[j - 1]).length();
  36352. dist = vectlg + uTotalDistance[p];
  36353. us[p].push(dist);
  36354. uTotalDistance[p] = dist;
  36355. }
  36356. j++;
  36357. }
  36358. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36359. j--;
  36360. positions.push(path[0].x, path[0].y, path[0].z);
  36361. vectlg = path[j].subtract(path[0]).length();
  36362. dist = vectlg + uTotalDistance[p];
  36363. us[p].push(dist);
  36364. uTotalDistance[p] = dist;
  36365. }
  36366. lg[p] = l + closePathCorr;
  36367. idx[p] = idc;
  36368. idc += (l + closePathCorr);
  36369. }
  36370. // vertical distances (v)
  36371. var path1;
  36372. var path2;
  36373. var vertex1 = null;
  36374. var vertex2 = null;
  36375. for (i = 0; i < minlg + closePathCorr; i++) {
  36376. vTotalDistance[i] = 0;
  36377. vs[i] = [0];
  36378. for (p = 0; p < pathArray.length - 1; p++) {
  36379. path1 = pathArray[p];
  36380. path2 = pathArray[p + 1];
  36381. if (i === minlg) { // closePath
  36382. vertex1 = path1[0];
  36383. vertex2 = path2[0];
  36384. }
  36385. else {
  36386. vertex1 = path1[i];
  36387. vertex2 = path2[i];
  36388. }
  36389. vectlg = vertex2.subtract(vertex1).length();
  36390. dist = vectlg + vTotalDistance[i];
  36391. vs[i].push(dist);
  36392. vTotalDistance[i] = dist;
  36393. }
  36394. if (closeArray && vertex2 && vertex1) {
  36395. path1 = pathArray[p];
  36396. path2 = pathArray[0];
  36397. if (i === minlg) { // closePath
  36398. vertex2 = path2[0];
  36399. }
  36400. vectlg = vertex2.subtract(vertex1).length();
  36401. dist = vectlg + vTotalDistance[i];
  36402. vTotalDistance[i] = dist;
  36403. }
  36404. }
  36405. // uvs
  36406. var u;
  36407. var v;
  36408. if (customUV) {
  36409. for (p = 0; p < customUV.length; p++) {
  36410. uvs.push(customUV[p].x, customUV[p].y);
  36411. }
  36412. }
  36413. else {
  36414. for (p = 0; p < pathArray.length; p++) {
  36415. for (i = 0; i < minlg + closePathCorr; i++) {
  36416. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36417. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36418. if (invertUV) {
  36419. uvs.push(v, u);
  36420. }
  36421. else {
  36422. uvs.push(u, v);
  36423. }
  36424. }
  36425. }
  36426. }
  36427. // indices
  36428. p = 0; // path index
  36429. var pi = 0; // positions array index
  36430. var l1 = lg[p] - 1; // path1 length
  36431. var l2 = lg[p + 1] - 1; // path2 length
  36432. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36433. var shft = idx[1] - idx[0]; // shift
  36434. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36435. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36436. // 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
  36437. indices.push(pi, pi + shft, pi + 1);
  36438. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36439. pi += 1;
  36440. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36441. p++;
  36442. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36443. shft = idx[0] - idx[p];
  36444. l1 = lg[p] - 1;
  36445. l2 = lg[0] - 1;
  36446. }
  36447. else {
  36448. shft = idx[p + 1] - idx[p];
  36449. l1 = lg[p] - 1;
  36450. l2 = lg[p + 1] - 1;
  36451. }
  36452. pi = idx[p];
  36453. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36454. }
  36455. }
  36456. // normals
  36457. VertexData.ComputeNormals(positions, indices, normals);
  36458. if (closePath) { // update both the first and last vertex normals to their average value
  36459. var indexFirst = 0;
  36460. var indexLast = 0;
  36461. for (p = 0; p < pathArray.length; p++) {
  36462. indexFirst = idx[p] * 3;
  36463. if (p + 1 < pathArray.length) {
  36464. indexLast = (idx[p + 1] - 1) * 3;
  36465. }
  36466. else {
  36467. indexLast = normals.length - 3;
  36468. }
  36469. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36470. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36471. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36472. normals[indexLast] = normals[indexFirst];
  36473. normals[indexLast + 1] = normals[indexFirst + 1];
  36474. normals[indexLast + 2] = normals[indexFirst + 2];
  36475. }
  36476. }
  36477. // sides
  36478. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36479. // Colors
  36480. var colors = null;
  36481. if (customColors) {
  36482. colors = new Float32Array(customColors.length * 4);
  36483. for (var c = 0; c < customColors.length; c++) {
  36484. colors[c * 4] = customColors[c].r;
  36485. colors[c * 4 + 1] = customColors[c].g;
  36486. colors[c * 4 + 2] = customColors[c].b;
  36487. colors[c * 4 + 3] = customColors[c].a;
  36488. }
  36489. }
  36490. // Result
  36491. var vertexData = new VertexData();
  36492. var positions32 = new Float32Array(positions);
  36493. var normals32 = new Float32Array(normals);
  36494. var uvs32 = new Float32Array(uvs);
  36495. vertexData.indices = indices;
  36496. vertexData.positions = positions32;
  36497. vertexData.normals = normals32;
  36498. vertexData.uvs = uvs32;
  36499. if (colors) {
  36500. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36501. }
  36502. if (closePath) {
  36503. vertexData._idx = idx;
  36504. }
  36505. return vertexData;
  36506. };
  36507. /**
  36508. * Creates the VertexData for a box
  36509. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36510. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36511. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36512. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36513. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36514. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36515. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36516. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36517. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36518. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36519. * @returns the VertexData of the box
  36520. */
  36521. VertexData.CreateBox = function (options) {
  36522. var normalsSource = [
  36523. new BABYLON.Vector3(0, 0, 1),
  36524. new BABYLON.Vector3(0, 0, -1),
  36525. new BABYLON.Vector3(1, 0, 0),
  36526. new BABYLON.Vector3(-1, 0, 0),
  36527. new BABYLON.Vector3(0, 1, 0),
  36528. new BABYLON.Vector3(0, -1, 0)
  36529. ];
  36530. var indices = [];
  36531. var positions = [];
  36532. var normals = [];
  36533. var uvs = [];
  36534. var width = options.width || options.size || 1;
  36535. var height = options.height || options.size || 1;
  36536. var depth = options.depth || options.size || 1;
  36537. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36538. var faceUV = options.faceUV || new Array(6);
  36539. var faceColors = options.faceColors;
  36540. var colors = [];
  36541. // default face colors and UV if undefined
  36542. for (var f = 0; f < 6; f++) {
  36543. if (faceUV[f] === undefined) {
  36544. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36545. }
  36546. if (faceColors && faceColors[f] === undefined) {
  36547. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36548. }
  36549. }
  36550. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36551. // Create each face in turn.
  36552. for (var index = 0; index < normalsSource.length; index++) {
  36553. var normal = normalsSource[index];
  36554. // Get two vectors perpendicular to the face normal and to each other.
  36555. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36556. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36557. // Six indices (two triangles) per face.
  36558. var verticesLength = positions.length / 3;
  36559. indices.push(verticesLength);
  36560. indices.push(verticesLength + 1);
  36561. indices.push(verticesLength + 2);
  36562. indices.push(verticesLength);
  36563. indices.push(verticesLength + 2);
  36564. indices.push(verticesLength + 3);
  36565. // Four vertices per face.
  36566. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36567. positions.push(vertex.x, vertex.y, vertex.z);
  36568. normals.push(normal.x, normal.y, normal.z);
  36569. uvs.push(faceUV[index].z, faceUV[index].w);
  36570. if (faceColors) {
  36571. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36572. }
  36573. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36574. positions.push(vertex.x, vertex.y, vertex.z);
  36575. normals.push(normal.x, normal.y, normal.z);
  36576. uvs.push(faceUV[index].x, faceUV[index].w);
  36577. if (faceColors) {
  36578. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36579. }
  36580. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36581. positions.push(vertex.x, vertex.y, vertex.z);
  36582. normals.push(normal.x, normal.y, normal.z);
  36583. uvs.push(faceUV[index].x, faceUV[index].y);
  36584. if (faceColors) {
  36585. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36586. }
  36587. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36588. positions.push(vertex.x, vertex.y, vertex.z);
  36589. normals.push(normal.x, normal.y, normal.z);
  36590. uvs.push(faceUV[index].z, faceUV[index].y);
  36591. if (faceColors) {
  36592. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36593. }
  36594. }
  36595. // sides
  36596. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36597. // Result
  36598. var vertexData = new VertexData();
  36599. vertexData.indices = indices;
  36600. vertexData.positions = positions;
  36601. vertexData.normals = normals;
  36602. vertexData.uvs = uvs;
  36603. if (faceColors) {
  36604. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36605. vertexData.colors = totalColors;
  36606. }
  36607. return vertexData;
  36608. };
  36609. /**
  36610. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36611. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36612. * * segments sets the number of horizontal strips optional, default 32
  36613. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36614. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36615. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36616. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36617. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  36618. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  36619. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36620. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36621. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36622. * @returns the VertexData of the ellipsoid
  36623. */
  36624. VertexData.CreateSphere = function (options) {
  36625. var segments = options.segments || 32;
  36626. var diameterX = options.diameterX || options.diameter || 1;
  36627. var diameterY = options.diameterY || options.diameter || 1;
  36628. var diameterZ = options.diameterZ || options.diameter || 1;
  36629. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36630. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36631. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36632. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36633. var totalZRotationSteps = 2 + segments;
  36634. var totalYRotationSteps = 2 * totalZRotationSteps;
  36635. var indices = [];
  36636. var positions = [];
  36637. var normals = [];
  36638. var uvs = [];
  36639. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36640. var normalizedZ = zRotationStep / totalZRotationSteps;
  36641. var angleZ = normalizedZ * Math.PI * slice;
  36642. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36643. var normalizedY = yRotationStep / totalYRotationSteps;
  36644. var angleY = normalizedY * Math.PI * 2 * arc;
  36645. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36646. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36647. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36648. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36649. var vertex = complete.multiply(radius);
  36650. var normal = complete.divide(radius).normalize();
  36651. positions.push(vertex.x, vertex.y, vertex.z);
  36652. normals.push(normal.x, normal.y, normal.z);
  36653. uvs.push(normalizedY, normalizedZ);
  36654. }
  36655. if (zRotationStep > 0) {
  36656. var verticesCount = positions.length / 3;
  36657. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36658. indices.push((firstIndex));
  36659. indices.push((firstIndex + 1));
  36660. indices.push(firstIndex + totalYRotationSteps + 1);
  36661. indices.push((firstIndex + totalYRotationSteps + 1));
  36662. indices.push((firstIndex + 1));
  36663. indices.push((firstIndex + totalYRotationSteps + 2));
  36664. }
  36665. }
  36666. }
  36667. // Sides
  36668. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36669. // Result
  36670. var vertexData = new VertexData();
  36671. vertexData.indices = indices;
  36672. vertexData.positions = positions;
  36673. vertexData.normals = normals;
  36674. vertexData.uvs = uvs;
  36675. return vertexData;
  36676. };
  36677. /**
  36678. * Creates the VertexData for a cylinder, cone or prism
  36679. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36680. * * height sets the height (y direction) of the cylinder, optional, default 2
  36681. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36682. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36683. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36684. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36685. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36686. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  36687. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36688. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36689. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36690. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36691. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36692. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36693. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36694. * @returns the VertexData of the cylinder, cone or prism
  36695. */
  36696. VertexData.CreateCylinder = function (options) {
  36697. var height = options.height || 2;
  36698. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36699. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36700. var tessellation = options.tessellation || 24;
  36701. var subdivisions = options.subdivisions || 1;
  36702. var hasRings = options.hasRings ? true : false;
  36703. var enclose = options.enclose ? true : false;
  36704. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36705. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36706. var faceUV = options.faceUV || new Array(3);
  36707. var faceColors = options.faceColors;
  36708. // default face colors and UV if undefined
  36709. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36710. var ringNb = (hasRings) ? subdivisions : 1;
  36711. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36712. var f;
  36713. for (f = 0; f < surfaceNb; f++) {
  36714. if (faceColors && faceColors[f] === undefined) {
  36715. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36716. }
  36717. }
  36718. for (f = 0; f < surfaceNb; f++) {
  36719. if (faceUV && faceUV[f] === undefined) {
  36720. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36721. }
  36722. }
  36723. var indices = new Array();
  36724. var positions = new Array();
  36725. var normals = new Array();
  36726. var uvs = new Array();
  36727. var colors = new Array();
  36728. var angle_step = Math.PI * 2 * arc / tessellation;
  36729. var angle;
  36730. var h;
  36731. var radius;
  36732. var tan = (diameterBottom - diameterTop) / 2 / height;
  36733. var ringVertex = BABYLON.Vector3.Zero();
  36734. var ringNormal = BABYLON.Vector3.Zero();
  36735. var ringFirstVertex = BABYLON.Vector3.Zero();
  36736. var ringFirstNormal = BABYLON.Vector3.Zero();
  36737. var quadNormal = BABYLON.Vector3.Zero();
  36738. var Y = BABYLON.Axis.Y;
  36739. // positions, normals, uvs
  36740. var i;
  36741. var j;
  36742. var r;
  36743. var ringIdx = 1;
  36744. var s = 1; // surface index
  36745. var cs = 0;
  36746. var v = 0;
  36747. for (i = 0; i <= subdivisions; i++) {
  36748. h = i / subdivisions;
  36749. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36750. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36751. for (r = 0; r < ringIdx; r++) {
  36752. if (hasRings) {
  36753. s += r;
  36754. }
  36755. if (enclose) {
  36756. s += 2 * r;
  36757. }
  36758. for (j = 0; j <= tessellation; j++) {
  36759. angle = j * angle_step;
  36760. // position
  36761. ringVertex.x = Math.cos(-angle) * radius;
  36762. ringVertex.y = -height / 2 + h * height;
  36763. ringVertex.z = Math.sin(-angle) * radius;
  36764. // normal
  36765. if (diameterTop === 0 && i === subdivisions) {
  36766. // if no top cap, reuse former normals
  36767. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36768. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36769. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36770. }
  36771. else {
  36772. ringNormal.x = ringVertex.x;
  36773. ringNormal.z = ringVertex.z;
  36774. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36775. ringNormal.normalize();
  36776. }
  36777. // keep first ring vertex values for enclose
  36778. if (j === 0) {
  36779. ringFirstVertex.copyFrom(ringVertex);
  36780. ringFirstNormal.copyFrom(ringNormal);
  36781. }
  36782. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36783. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36784. if (hasRings) {
  36785. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36786. }
  36787. else {
  36788. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36789. }
  36790. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36791. if (faceColors) {
  36792. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36793. }
  36794. }
  36795. // if enclose, add four vertices and their dedicated normals
  36796. if (arc !== 1 && enclose) {
  36797. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36798. positions.push(0, ringVertex.y, 0);
  36799. positions.push(0, ringVertex.y, 0);
  36800. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36801. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36802. quadNormal.normalize();
  36803. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36804. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36805. quadNormal.normalize();
  36806. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36807. if (hasRings) {
  36808. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36809. }
  36810. else {
  36811. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36812. }
  36813. uvs.push(faceUV[s + 1].x, v);
  36814. uvs.push(faceUV[s + 1].z, v);
  36815. if (hasRings) {
  36816. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36817. }
  36818. else {
  36819. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36820. }
  36821. uvs.push(faceUV[s + 2].x, v);
  36822. uvs.push(faceUV[s + 2].z, v);
  36823. if (faceColors) {
  36824. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36825. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36826. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36827. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36828. }
  36829. }
  36830. if (cs !== s) {
  36831. cs = s;
  36832. }
  36833. }
  36834. }
  36835. // indices
  36836. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36837. var s;
  36838. i = 0;
  36839. for (s = 0; s < subdivisions; s++) {
  36840. var i0 = 0;
  36841. var i1 = 0;
  36842. var i2 = 0;
  36843. var i3 = 0;
  36844. for (j = 0; j < tessellation; j++) {
  36845. i0 = i * (e + 1) + j;
  36846. i1 = (i + 1) * (e + 1) + j;
  36847. i2 = i * (e + 1) + (j + 1);
  36848. i3 = (i + 1) * (e + 1) + (j + 1);
  36849. indices.push(i0, i1, i2);
  36850. indices.push(i3, i2, i1);
  36851. }
  36852. if (arc !== 1 && enclose) { // if enclose, add two quads
  36853. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36854. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36855. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36856. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36857. }
  36858. i = (hasRings) ? (i + 2) : (i + 1);
  36859. }
  36860. // Caps
  36861. var createCylinderCap = function (isTop) {
  36862. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36863. if (radius === 0) {
  36864. return;
  36865. }
  36866. // Cap positions, normals & uvs
  36867. var angle;
  36868. var circleVector;
  36869. var i;
  36870. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36871. var c = null;
  36872. if (faceColors) {
  36873. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36874. }
  36875. // cap center
  36876. var vbase = positions.length / 3;
  36877. var offset = isTop ? height / 2 : -height / 2;
  36878. var center = new BABYLON.Vector3(0, offset, 0);
  36879. positions.push(center.x, center.y, center.z);
  36880. normals.push(0, isTop ? 1 : -1, 0);
  36881. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36882. if (c) {
  36883. colors.push(c.r, c.g, c.b, c.a);
  36884. }
  36885. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36886. for (i = 0; i <= tessellation; i++) {
  36887. angle = Math.PI * 2 * i * arc / tessellation;
  36888. var cos = Math.cos(-angle);
  36889. var sin = Math.sin(-angle);
  36890. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36891. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36892. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36893. normals.push(0, isTop ? 1 : -1, 0);
  36894. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36895. if (c) {
  36896. colors.push(c.r, c.g, c.b, c.a);
  36897. }
  36898. }
  36899. // Cap indices
  36900. for (i = 0; i < tessellation; i++) {
  36901. if (!isTop) {
  36902. indices.push(vbase);
  36903. indices.push(vbase + (i + 1));
  36904. indices.push(vbase + (i + 2));
  36905. }
  36906. else {
  36907. indices.push(vbase);
  36908. indices.push(vbase + (i + 2));
  36909. indices.push(vbase + (i + 1));
  36910. }
  36911. }
  36912. };
  36913. // add caps to geometry
  36914. createCylinderCap(false);
  36915. createCylinderCap(true);
  36916. // Sides
  36917. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36918. var vertexData = new VertexData();
  36919. vertexData.indices = indices;
  36920. vertexData.positions = positions;
  36921. vertexData.normals = normals;
  36922. vertexData.uvs = uvs;
  36923. if (faceColors) {
  36924. vertexData.colors = colors;
  36925. }
  36926. return vertexData;
  36927. };
  36928. /**
  36929. * Creates the VertexData for a torus
  36930. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36931. * * diameter the diameter of the torus, optional default 1
  36932. * * thickness the diameter of the tube forming the torus, optional default 0.5
  36933. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36934. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36935. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36936. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36937. * @returns the VertexData of the torus
  36938. */
  36939. VertexData.CreateTorus = function (options) {
  36940. var indices = [];
  36941. var positions = [];
  36942. var normals = [];
  36943. var uvs = [];
  36944. var diameter = options.diameter || 1;
  36945. var thickness = options.thickness || 0.5;
  36946. var tessellation = options.tessellation || 16;
  36947. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36948. var stride = tessellation + 1;
  36949. for (var i = 0; i <= tessellation; i++) {
  36950. var u = i / tessellation;
  36951. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36952. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36953. for (var j = 0; j <= tessellation; j++) {
  36954. var v = 1 - j / tessellation;
  36955. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36956. var dx = Math.cos(innerAngle);
  36957. var dy = Math.sin(innerAngle);
  36958. // Create a vertex.
  36959. var normal = new BABYLON.Vector3(dx, dy, 0);
  36960. var position = normal.scale(thickness / 2);
  36961. var textureCoordinate = new BABYLON.Vector2(u, v);
  36962. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36963. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36964. positions.push(position.x, position.y, position.z);
  36965. normals.push(normal.x, normal.y, normal.z);
  36966. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36967. // And create indices for two triangles.
  36968. var nextI = (i + 1) % stride;
  36969. var nextJ = (j + 1) % stride;
  36970. indices.push(i * stride + j);
  36971. indices.push(i * stride + nextJ);
  36972. indices.push(nextI * stride + j);
  36973. indices.push(i * stride + nextJ);
  36974. indices.push(nextI * stride + nextJ);
  36975. indices.push(nextI * stride + j);
  36976. }
  36977. }
  36978. // Sides
  36979. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36980. // Result
  36981. var vertexData = new VertexData();
  36982. vertexData.indices = indices;
  36983. vertexData.positions = positions;
  36984. vertexData.normals = normals;
  36985. vertexData.uvs = uvs;
  36986. return vertexData;
  36987. };
  36988. /**
  36989. * Creates the VertexData of the LineSystem
  36990. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  36991. * - lines an array of lines, each line being an array of successive Vector3
  36992. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  36993. * @returns the VertexData of the LineSystem
  36994. */
  36995. VertexData.CreateLineSystem = function (options) {
  36996. var indices = [];
  36997. var positions = [];
  36998. var lines = options.lines;
  36999. var colors = options.colors;
  37000. var vertexColors = [];
  37001. var idx = 0;
  37002. for (var l = 0; l < lines.length; l++) {
  37003. var points = lines[l];
  37004. for (var index = 0; index < points.length; index++) {
  37005. positions.push(points[index].x, points[index].y, points[index].z);
  37006. if (colors) {
  37007. var color = colors[l];
  37008. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37009. }
  37010. if (index > 0) {
  37011. indices.push(idx - 1);
  37012. indices.push(idx);
  37013. }
  37014. idx++;
  37015. }
  37016. }
  37017. var vertexData = new VertexData();
  37018. vertexData.indices = indices;
  37019. vertexData.positions = positions;
  37020. if (colors) {
  37021. vertexData.colors = vertexColors;
  37022. }
  37023. return vertexData;
  37024. };
  37025. /**
  37026. * Create the VertexData for a DashedLines
  37027. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37028. * - points an array successive Vector3
  37029. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37030. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37031. * - dashNb the intended total number of dashes, optional, default 200
  37032. * @returns the VertexData for the DashedLines
  37033. */
  37034. VertexData.CreateDashedLines = function (options) {
  37035. var dashSize = options.dashSize || 3;
  37036. var gapSize = options.gapSize || 1;
  37037. var dashNb = options.dashNb || 200;
  37038. var points = options.points;
  37039. var positions = new Array();
  37040. var indices = new Array();
  37041. var curvect = BABYLON.Vector3.Zero();
  37042. var lg = 0;
  37043. var nb = 0;
  37044. var shft = 0;
  37045. var dashshft = 0;
  37046. var curshft = 0;
  37047. var idx = 0;
  37048. var i = 0;
  37049. for (i = 0; i < points.length - 1; i++) {
  37050. points[i + 1].subtractToRef(points[i], curvect);
  37051. lg += curvect.length();
  37052. }
  37053. shft = lg / dashNb;
  37054. dashshft = dashSize * shft / (dashSize + gapSize);
  37055. for (i = 0; i < points.length - 1; i++) {
  37056. points[i + 1].subtractToRef(points[i], curvect);
  37057. nb = Math.floor(curvect.length() / shft);
  37058. curvect.normalize();
  37059. for (var j = 0; j < nb; j++) {
  37060. curshft = shft * j;
  37061. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37062. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37063. indices.push(idx, idx + 1);
  37064. idx += 2;
  37065. }
  37066. }
  37067. // Result
  37068. var vertexData = new VertexData();
  37069. vertexData.positions = positions;
  37070. vertexData.indices = indices;
  37071. return vertexData;
  37072. };
  37073. /**
  37074. * Creates the VertexData for a Ground
  37075. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37076. * - width the width (x direction) of the ground, optional, default 1
  37077. * - height the height (z direction) of the ground, optional, default 1
  37078. * - subdivisions the number of subdivisions per side, optional, default 1
  37079. * @returns the VertexData of the Ground
  37080. */
  37081. VertexData.CreateGround = function (options) {
  37082. var indices = [];
  37083. var positions = [];
  37084. var normals = [];
  37085. var uvs = [];
  37086. var row, col;
  37087. var width = options.width || 1;
  37088. var height = options.height || 1;
  37089. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37090. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37091. for (row = 0; row <= subdivisionsY; row++) {
  37092. for (col = 0; col <= subdivisionsX; col++) {
  37093. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37094. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37095. positions.push(position.x, position.y, position.z);
  37096. normals.push(normal.x, normal.y, normal.z);
  37097. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37098. }
  37099. }
  37100. for (row = 0; row < subdivisionsY; row++) {
  37101. for (col = 0; col < subdivisionsX; col++) {
  37102. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37103. indices.push(col + 1 + row * (subdivisionsX + 1));
  37104. indices.push(col + row * (subdivisionsX + 1));
  37105. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37106. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37107. indices.push(col + row * (subdivisionsX + 1));
  37108. }
  37109. }
  37110. // Result
  37111. var vertexData = new VertexData();
  37112. vertexData.indices = indices;
  37113. vertexData.positions = positions;
  37114. vertexData.normals = normals;
  37115. vertexData.uvs = uvs;
  37116. return vertexData;
  37117. };
  37118. /**
  37119. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37120. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37121. * * xmin the ground minimum X coordinate, optional, default -1
  37122. * * zmin the ground minimum Z coordinate, optional, default -1
  37123. * * xmax the ground maximum X coordinate, optional, default 1
  37124. * * zmax the ground maximum Z coordinate, optional, default 1
  37125. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37126. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37127. * @returns the VertexData of the TiledGround
  37128. */
  37129. VertexData.CreateTiledGround = function (options) {
  37130. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37131. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37132. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37133. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37134. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37135. var precision = options.precision || { w: 1, h: 1 };
  37136. var indices = new Array();
  37137. var positions = new Array();
  37138. var normals = new Array();
  37139. var uvs = new Array();
  37140. var row, col, tileRow, tileCol;
  37141. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37142. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37143. precision.w = (precision.w < 1) ? 1 : precision.w;
  37144. precision.h = (precision.h < 1) ? 1 : precision.h;
  37145. var tileSize = {
  37146. 'w': (xmax - xmin) / subdivisions.w,
  37147. 'h': (zmax - zmin) / subdivisions.h
  37148. };
  37149. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37150. // Indices
  37151. var base = positions.length / 3;
  37152. var rowLength = precision.w + 1;
  37153. for (row = 0; row < precision.h; row++) {
  37154. for (col = 0; col < precision.w; col++) {
  37155. var square = [
  37156. base + col + row * rowLength,
  37157. base + (col + 1) + row * rowLength,
  37158. base + (col + 1) + (row + 1) * rowLength,
  37159. base + col + (row + 1) * rowLength
  37160. ];
  37161. indices.push(square[1]);
  37162. indices.push(square[2]);
  37163. indices.push(square[3]);
  37164. indices.push(square[0]);
  37165. indices.push(square[1]);
  37166. indices.push(square[3]);
  37167. }
  37168. }
  37169. // Position, normals and uvs
  37170. var position = BABYLON.Vector3.Zero();
  37171. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37172. for (row = 0; row <= precision.h; row++) {
  37173. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37174. for (col = 0; col <= precision.w; col++) {
  37175. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37176. position.y = 0;
  37177. positions.push(position.x, position.y, position.z);
  37178. normals.push(normal.x, normal.y, normal.z);
  37179. uvs.push(col / precision.w, row / precision.h);
  37180. }
  37181. }
  37182. }
  37183. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37184. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37185. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37186. }
  37187. }
  37188. // Result
  37189. var vertexData = new VertexData();
  37190. vertexData.indices = indices;
  37191. vertexData.positions = positions;
  37192. vertexData.normals = normals;
  37193. vertexData.uvs = uvs;
  37194. return vertexData;
  37195. };
  37196. /**
  37197. * Creates the VertexData of the Ground designed from a heightmap
  37198. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37199. * * width the width (x direction) of the ground
  37200. * * height the height (z direction) of the ground
  37201. * * subdivisions the number of subdivisions per side
  37202. * * minHeight the minimum altitude on the ground, optional, default 0
  37203. * * maxHeight the maximum altitude on the ground, optional default 1
  37204. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37205. * * buffer the array holding the image color data
  37206. * * bufferWidth the width of image
  37207. * * bufferHeight the height of image
  37208. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  37209. * @returns the VertexData of the Ground designed from a heightmap
  37210. */
  37211. VertexData.CreateGroundFromHeightMap = function (options) {
  37212. var indices = [];
  37213. var positions = [];
  37214. var normals = [];
  37215. var uvs = [];
  37216. var row, col;
  37217. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37218. var alphaFilter = options.alphaFilter || 0.0;
  37219. // Vertices
  37220. for (row = 0; row <= options.subdivisions; row++) {
  37221. for (col = 0; col <= options.subdivisions; col++) {
  37222. 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));
  37223. // Compute height
  37224. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37225. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37226. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37227. var r = options.buffer[pos] / 255.0;
  37228. var g = options.buffer[pos + 1] / 255.0;
  37229. var b = options.buffer[pos + 2] / 255.0;
  37230. var a = options.buffer[pos + 3] / 255.0;
  37231. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37232. // If our alpha channel is not within our filter then we will assign a 'special' height
  37233. // Then when building the indices, we will ignore any vertex that is using the special height
  37234. if (a >= alphaFilter)
  37235. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37236. else {
  37237. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  37238. }
  37239. // Add vertex
  37240. positions.push(position.x, position.y, position.z);
  37241. normals.push(0, 0, 0);
  37242. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37243. }
  37244. }
  37245. // Indices
  37246. for (row = 0; row < options.subdivisions; row++) {
  37247. for (col = 0; col < options.subdivisions; col++) {
  37248. // Calculate Indices
  37249. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  37250. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  37251. var idx3 = (col + row * (options.subdivisions + 1));
  37252. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  37253. // Check that all indices are visible (based on our special height)
  37254. // Only display the vertex if all Indices are visible
  37255. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  37256. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  37257. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  37258. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  37259. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  37260. indices.push(idx1);
  37261. indices.push(idx2);
  37262. indices.push(idx3);
  37263. }
  37264. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  37265. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  37266. indices.push(idx4);
  37267. indices.push(idx1);
  37268. indices.push(idx3);
  37269. }
  37270. }
  37271. }
  37272. // Normals
  37273. VertexData.ComputeNormals(positions, indices, normals);
  37274. // Result
  37275. var vertexData = new VertexData();
  37276. vertexData.indices = indices;
  37277. vertexData.positions = positions;
  37278. vertexData.normals = normals;
  37279. vertexData.uvs = uvs;
  37280. return vertexData;
  37281. };
  37282. /**
  37283. * Creates the VertexData for a Plane
  37284. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37285. * * size sets the width and height of the plane to the value of size, optional default 1
  37286. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37287. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37288. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37289. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37290. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37291. * @returns the VertexData of the box
  37292. */
  37293. VertexData.CreatePlane = function (options) {
  37294. var indices = [];
  37295. var positions = [];
  37296. var normals = [];
  37297. var uvs = [];
  37298. var width = options.width || options.size || 1;
  37299. var height = options.height || options.size || 1;
  37300. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37301. // Vertices
  37302. var halfWidth = width / 2.0;
  37303. var halfHeight = height / 2.0;
  37304. positions.push(-halfWidth, -halfHeight, 0);
  37305. normals.push(0, 0, -1.0);
  37306. uvs.push(0.0, 0.0);
  37307. positions.push(halfWidth, -halfHeight, 0);
  37308. normals.push(0, 0, -1.0);
  37309. uvs.push(1.0, 0.0);
  37310. positions.push(halfWidth, halfHeight, 0);
  37311. normals.push(0, 0, -1.0);
  37312. uvs.push(1.0, 1.0);
  37313. positions.push(-halfWidth, halfHeight, 0);
  37314. normals.push(0, 0, -1.0);
  37315. uvs.push(0.0, 1.0);
  37316. // Indices
  37317. indices.push(0);
  37318. indices.push(1);
  37319. indices.push(2);
  37320. indices.push(0);
  37321. indices.push(2);
  37322. indices.push(3);
  37323. // Sides
  37324. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37325. // Result
  37326. var vertexData = new VertexData();
  37327. vertexData.indices = indices;
  37328. vertexData.positions = positions;
  37329. vertexData.normals = normals;
  37330. vertexData.uvs = uvs;
  37331. return vertexData;
  37332. };
  37333. /**
  37334. * Creates the VertexData of the Disc or regular Polygon
  37335. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37336. * * radius the radius of the disc, optional default 0.5
  37337. * * tessellation the number of polygon sides, optional, default 64
  37338. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  37339. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37340. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37341. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37342. * @returns the VertexData of the box
  37343. */
  37344. VertexData.CreateDisc = function (options) {
  37345. var positions = new Array();
  37346. var indices = new Array();
  37347. var normals = new Array();
  37348. var uvs = new Array();
  37349. var radius = options.radius || 0.5;
  37350. var tessellation = options.tessellation || 64;
  37351. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37352. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37353. // positions and uvs
  37354. positions.push(0, 0, 0); // disc center first
  37355. uvs.push(0.5, 0.5);
  37356. var theta = Math.PI * 2 * arc;
  37357. var step = theta / tessellation;
  37358. for (var a = 0; a < theta; a += step) {
  37359. var x = Math.cos(a);
  37360. var y = Math.sin(a);
  37361. var u = (x + 1) / 2;
  37362. var v = (1 - y) / 2;
  37363. positions.push(radius * x, radius * y, 0);
  37364. uvs.push(u, v);
  37365. }
  37366. if (arc === 1) {
  37367. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37368. uvs.push(uvs[2], uvs[3]);
  37369. }
  37370. //indices
  37371. var vertexNb = positions.length / 3;
  37372. for (var i = 1; i < vertexNb - 1; i++) {
  37373. indices.push(i + 1, 0, i);
  37374. }
  37375. // result
  37376. VertexData.ComputeNormals(positions, indices, normals);
  37377. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37378. var vertexData = new VertexData();
  37379. vertexData.indices = indices;
  37380. vertexData.positions = positions;
  37381. vertexData.normals = normals;
  37382. vertexData.uvs = uvs;
  37383. return vertexData;
  37384. };
  37385. /**
  37386. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37387. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37388. * @param polygon a mesh built from polygonTriangulation.build()
  37389. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37390. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37391. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37392. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37393. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37394. * @returns the VertexData of the Polygon
  37395. */
  37396. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37397. var faceUV = fUV || new Array(3);
  37398. var faceColors = fColors;
  37399. var colors = [];
  37400. // default face colors and UV if undefined
  37401. for (var f = 0; f < 3; f++) {
  37402. if (faceUV[f] === undefined) {
  37403. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37404. }
  37405. if (faceColors && faceColors[f] === undefined) {
  37406. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37407. }
  37408. }
  37409. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37410. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37411. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37412. var indices = polygon.getIndices();
  37413. // set face colours and textures
  37414. var idx = 0;
  37415. var face = 0;
  37416. for (var index = 0; index < normals.length; index += 3) {
  37417. //Edge Face no. 1
  37418. if (Math.abs(normals[index + 1]) < 0.001) {
  37419. face = 1;
  37420. }
  37421. //Top Face no. 0
  37422. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37423. face = 0;
  37424. }
  37425. //Bottom Face no. 2
  37426. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37427. face = 2;
  37428. }
  37429. idx = index / 3;
  37430. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37431. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37432. if (faceColors) {
  37433. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37434. }
  37435. }
  37436. // sides
  37437. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37438. // Result
  37439. var vertexData = new VertexData();
  37440. vertexData.indices = indices;
  37441. vertexData.positions = positions;
  37442. vertexData.normals = normals;
  37443. vertexData.uvs = uvs;
  37444. if (faceColors) {
  37445. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37446. vertexData.colors = totalColors;
  37447. }
  37448. return vertexData;
  37449. };
  37450. /**
  37451. * Creates the VertexData of the IcoSphere
  37452. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37453. * * radius the radius of the IcoSphere, optional default 1
  37454. * * radiusX allows stretching in the x direction, optional, default radius
  37455. * * radiusY allows stretching in the y direction, optional, default radius
  37456. * * radiusZ allows stretching in the z direction, optional, default radius
  37457. * * flat when true creates a flat shaded mesh, optional, default true
  37458. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37459. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37460. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37461. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37462. * @returns the VertexData of the IcoSphere
  37463. */
  37464. VertexData.CreateIcoSphere = function (options) {
  37465. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37466. var radius = options.radius || 1;
  37467. var flat = (options.flat === undefined) ? true : options.flat;
  37468. var subdivisions = options.subdivisions || 4;
  37469. var radiusX = options.radiusX || radius;
  37470. var radiusY = options.radiusY || radius;
  37471. var radiusZ = options.radiusZ || radius;
  37472. var t = (1 + Math.sqrt(5)) / 2;
  37473. // 12 vertex x,y,z
  37474. var ico_vertices = [
  37475. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37476. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37477. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37478. ];
  37479. // index of 3 vertex makes a face of icopshere
  37480. var ico_indices = [
  37481. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37482. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37483. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37484. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37485. ];
  37486. // vertex for uv have aliased position, not for UV
  37487. var vertices_unalias_id = [
  37488. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37489. // vertex alias
  37490. 0,
  37491. 2,
  37492. 3,
  37493. 3,
  37494. 3,
  37495. 4,
  37496. 7,
  37497. 8,
  37498. 9,
  37499. 9,
  37500. 10,
  37501. 11 // 23: B + 12
  37502. ];
  37503. // uv as integer step (not pixels !)
  37504. var ico_vertexuv = [
  37505. 5, 1, 3, 1, 6, 4, 0, 0,
  37506. 5, 3, 4, 2, 2, 2, 4, 0,
  37507. 2, 0, 1, 1, 6, 0, 6, 2,
  37508. // vertex alias (for same vertex on different faces)
  37509. 0, 4,
  37510. 3, 3,
  37511. 4, 4,
  37512. 3, 1,
  37513. 4, 2,
  37514. 4, 4,
  37515. 0, 2,
  37516. 1, 1,
  37517. 2, 2,
  37518. 3, 3,
  37519. 1, 3,
  37520. 2, 4 // 23: B + 12
  37521. ];
  37522. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37523. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37524. // First island of uv mapping
  37525. // v = 4h 3+ 2
  37526. // v = 3h 9+ 4
  37527. // v = 2h 9+ 5 B
  37528. // v = 1h 9 1 0
  37529. // v = 0h 3 8 7 A
  37530. // u = 0 1 2 3 4 5 6 *a
  37531. // Second island of uv mapping
  37532. // v = 4h 0+ B+ 4+
  37533. // v = 3h A+ 2+
  37534. // v = 2h 7+ 6 3+
  37535. // v = 1h 8+ 3+
  37536. // v = 0h
  37537. // u = 0 1 2 3 4 5 6 *a
  37538. // Face layout on texture UV mapping
  37539. // ============
  37540. // \ 4 /\ 16 / ======
  37541. // \ / \ / /\ 11 /
  37542. // \/ 7 \/ / \ /
  37543. // ======= / 10 \/
  37544. // /\ 17 /\ =======
  37545. // / \ / \ \ 15 /\
  37546. // / 8 \/ 12 \ \ / \
  37547. // ============ \/ 6 \
  37548. // \ 18 /\ ============
  37549. // \ / \ \ 5 /\ 0 /
  37550. // \/ 13 \ \ / \ /
  37551. // ======= \/ 1 \/
  37552. // =============
  37553. // /\ 19 /\ 2 /\
  37554. // / \ / \ / \
  37555. // / 14 \/ 9 \/ 3 \
  37556. // ===================
  37557. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37558. var ustep = 138 / 1024;
  37559. var vstep = 239 / 1024;
  37560. var uoffset = 60 / 1024;
  37561. var voffset = 26 / 1024;
  37562. // Second island should have margin, not to touch the first island
  37563. // avoid any borderline artefact in pixel rounding
  37564. var island_u_offset = -40 / 1024;
  37565. var island_v_offset = +20 / 1024;
  37566. // face is either island 0 or 1 :
  37567. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37568. var island = [
  37569. 0, 0, 0, 0, 1,
  37570. 0, 0, 1, 1, 0,
  37571. 0, 0, 1, 1, 0,
  37572. 0, 1, 1, 1, 0 // 15 - 19
  37573. ];
  37574. var indices = new Array();
  37575. var positions = new Array();
  37576. var normals = new Array();
  37577. var uvs = new Array();
  37578. var current_indice = 0;
  37579. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37580. var face_vertex_pos = new Array(3);
  37581. var face_vertex_uv = new Array(3);
  37582. var v012;
  37583. for (v012 = 0; v012 < 3; v012++) {
  37584. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37585. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37586. }
  37587. // create all with normals
  37588. for (var face = 0; face < 20; face++) {
  37589. // 3 vertex per face
  37590. for (v012 = 0; v012 < 3; v012++) {
  37591. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37592. var v_id = ico_indices[3 * face + v012];
  37593. // vertex have 3D position (x,y,z)
  37594. 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]);
  37595. // Normalize to get normal, then scale to radius
  37596. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37597. // uv Coordinates from vertex ID
  37598. 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);
  37599. }
  37600. // Subdivide the face (interpolate pos, norm, uv)
  37601. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37602. // - norm is linear interpolation of vertex corner normal
  37603. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37604. // - uv is linear interpolation
  37605. //
  37606. // Topology is as below for sub-divide by 2
  37607. // vertex shown as v0,v1,v2
  37608. // interp index is i1 to progress in range [v0,v1[
  37609. // interp index is i2 to progress in range [v0,v2[
  37610. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37611. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37612. //
  37613. //
  37614. // i2 v2
  37615. // ^ ^
  37616. // / / \
  37617. // / / \
  37618. // / / \
  37619. // / / (0,1) \
  37620. // / #---------\
  37621. // / / \ (0,0)'/ \
  37622. // / / \ / \
  37623. // / / \ / \
  37624. // / / (0,0) \ / (1,0) \
  37625. // / #---------#---------\
  37626. // v0 v1
  37627. //
  37628. // --------------------> i1
  37629. //
  37630. // interp of (i1,i2):
  37631. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37632. // along i1 : lerp(x0,x1, i1/(S-i2))
  37633. //
  37634. // centroid of triangle is needed to get help normal computation
  37635. // (c1,c2) are used for centroid location
  37636. var interp_vertex = function (i1, i2, c1, c2) {
  37637. // vertex is interpolated from
  37638. // - face_vertex_pos[0..2]
  37639. // - face_vertex_uv[0..2]
  37640. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37641. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37642. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37643. pos_interp.normalize();
  37644. var vertex_normal;
  37645. if (flat) {
  37646. // in flat mode, recalculate normal as face centroid normal
  37647. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37648. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37649. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37650. }
  37651. else {
  37652. // in smooth mode, recalculate normal from each single vertex position
  37653. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37654. }
  37655. // Vertex normal need correction due to X,Y,Z radius scaling
  37656. vertex_normal.x /= radiusX;
  37657. vertex_normal.y /= radiusY;
  37658. vertex_normal.z /= radiusZ;
  37659. vertex_normal.normalize();
  37660. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37661. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37662. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37663. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37664. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37665. uvs.push(uv_interp.x, uv_interp.y);
  37666. // push each vertex has member of a face
  37667. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37668. indices.push(current_indice);
  37669. current_indice++;
  37670. };
  37671. for (var i2 = 0; i2 < subdivisions; i2++) {
  37672. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37673. // face : (i1,i2) for /\ :
  37674. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37675. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37676. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37677. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37678. if (i1 + i2 + 1 < subdivisions) {
  37679. // face : (i1,i2)' for \/ :
  37680. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37681. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37682. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37683. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37684. }
  37685. }
  37686. }
  37687. }
  37688. // Sides
  37689. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37690. // Result
  37691. var vertexData = new VertexData();
  37692. vertexData.indices = indices;
  37693. vertexData.positions = positions;
  37694. vertexData.normals = normals;
  37695. vertexData.uvs = uvs;
  37696. return vertexData;
  37697. };
  37698. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37699. /**
  37700. * Creates the VertexData for a Polyhedron
  37701. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37702. * * type provided types are:
  37703. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37704. * * 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)
  37705. * * size the size of the IcoSphere, optional default 1
  37706. * * sizeX allows stretching in the x direction, optional, default size
  37707. * * sizeY allows stretching in the y direction, optional, default size
  37708. * * sizeZ allows stretching in the z direction, optional, default size
  37709. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  37710. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37711. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37712. * * flat when true creates a flat shaded mesh, optional, default true
  37713. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37714. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37715. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37716. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37717. * @returns the VertexData of the Polyhedron
  37718. */
  37719. VertexData.CreatePolyhedron = function (options) {
  37720. // provided polyhedron types :
  37721. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37722. // 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)
  37723. var polyhedra = [];
  37724. 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]] };
  37725. 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]] };
  37726. polyhedra[2] = {
  37727. 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]],
  37728. 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]]
  37729. };
  37730. polyhedra[3] = {
  37731. 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]],
  37732. 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]]
  37733. };
  37734. polyhedra[4] = {
  37735. 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]],
  37736. 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]]
  37737. };
  37738. 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]] };
  37739. 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]] };
  37740. 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]] };
  37741. 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]] };
  37742. 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]] };
  37743. 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]] };
  37744. 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]] };
  37745. 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]] };
  37746. 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]] };
  37747. polyhedra[14] = {
  37748. 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]],
  37749. 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]]
  37750. };
  37751. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37752. var size = options.size;
  37753. var sizeX = options.sizeX || size || 1;
  37754. var sizeY = options.sizeY || size || 1;
  37755. var sizeZ = options.sizeZ || size || 1;
  37756. var data = options.custom || polyhedra[type];
  37757. var nbfaces = data.face.length;
  37758. var faceUV = options.faceUV || new Array(nbfaces);
  37759. var faceColors = options.faceColors;
  37760. var flat = (options.flat === undefined) ? true : options.flat;
  37761. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37762. var positions = new Array();
  37763. var indices = new Array();
  37764. var normals = new Array();
  37765. var uvs = new Array();
  37766. var colors = new Array();
  37767. var index = 0;
  37768. var faceIdx = 0; // face cursor in the array "indexes"
  37769. var indexes = new Array();
  37770. var i = 0;
  37771. var f = 0;
  37772. var u, v, ang, x, y, tmp;
  37773. // default face colors and UV if undefined
  37774. if (flat) {
  37775. for (f = 0; f < nbfaces; f++) {
  37776. if (faceColors && faceColors[f] === undefined) {
  37777. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37778. }
  37779. if (faceUV && faceUV[f] === undefined) {
  37780. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37781. }
  37782. }
  37783. }
  37784. if (!flat) {
  37785. for (i = 0; i < data.vertex.length; i++) {
  37786. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37787. uvs.push(0, 0);
  37788. }
  37789. for (f = 0; f < nbfaces; f++) {
  37790. for (i = 0; i < data.face[f].length - 2; i++) {
  37791. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37792. }
  37793. }
  37794. }
  37795. else {
  37796. for (f = 0; f < nbfaces; f++) {
  37797. var fl = data.face[f].length; // number of vertices of the current face
  37798. ang = 2 * Math.PI / fl;
  37799. x = 0.5 * Math.tan(ang / 2);
  37800. y = 0.5;
  37801. // positions, uvs, colors
  37802. for (i = 0; i < fl; i++) {
  37803. // positions
  37804. 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);
  37805. indexes.push(index);
  37806. index++;
  37807. // uvs
  37808. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37809. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37810. uvs.push(u, v);
  37811. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37812. y = x * Math.sin(ang) + y * Math.cos(ang);
  37813. x = tmp;
  37814. // colors
  37815. if (faceColors) {
  37816. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37817. }
  37818. }
  37819. // indices from indexes
  37820. for (i = 0; i < fl - 2; i++) {
  37821. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37822. }
  37823. faceIdx += fl;
  37824. }
  37825. }
  37826. VertexData.ComputeNormals(positions, indices, normals);
  37827. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37828. var vertexData = new VertexData();
  37829. vertexData.positions = positions;
  37830. vertexData.indices = indices;
  37831. vertexData.normals = normals;
  37832. vertexData.uvs = uvs;
  37833. if (faceColors && flat) {
  37834. vertexData.colors = colors;
  37835. }
  37836. return vertexData;
  37837. };
  37838. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37839. /**
  37840. * Creates the VertexData for a TorusKnot
  37841. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37842. * * radius the radius of the torus knot, optional, default 2
  37843. * * tube the thickness of the tube, optional, default 0.5
  37844. * * radialSegments the number of sides on each tube segments, optional, default 32
  37845. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37846. * * p the number of windings around the z axis, optional, default 2
  37847. * * q the number of windings around the x axis, optional, default 3
  37848. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37849. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37850. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37851. * @returns the VertexData of the Torus Knot
  37852. */
  37853. VertexData.CreateTorusKnot = function (options) {
  37854. var indices = new Array();
  37855. var positions = new Array();
  37856. var normals = new Array();
  37857. var uvs = new Array();
  37858. var radius = options.radius || 2;
  37859. var tube = options.tube || 0.5;
  37860. var radialSegments = options.radialSegments || 32;
  37861. var tubularSegments = options.tubularSegments || 32;
  37862. var p = options.p || 2;
  37863. var q = options.q || 3;
  37864. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37865. // Helper
  37866. var getPos = function (angle) {
  37867. var cu = Math.cos(angle);
  37868. var su = Math.sin(angle);
  37869. var quOverP = q / p * angle;
  37870. var cs = Math.cos(quOverP);
  37871. var tx = radius * (2 + cs) * 0.5 * cu;
  37872. var ty = radius * (2 + cs) * su * 0.5;
  37873. var tz = radius * Math.sin(quOverP) * 0.5;
  37874. return new BABYLON.Vector3(tx, ty, tz);
  37875. };
  37876. // Vertices
  37877. var i;
  37878. var j;
  37879. for (i = 0; i <= radialSegments; i++) {
  37880. var modI = i % radialSegments;
  37881. var u = modI / radialSegments * 2 * p * Math.PI;
  37882. var p1 = getPos(u);
  37883. var p2 = getPos(u + 0.01);
  37884. var tang = p2.subtract(p1);
  37885. var n = p2.add(p1);
  37886. var bitan = BABYLON.Vector3.Cross(tang, n);
  37887. n = BABYLON.Vector3.Cross(bitan, tang);
  37888. bitan.normalize();
  37889. n.normalize();
  37890. for (j = 0; j < tubularSegments; j++) {
  37891. var modJ = j % tubularSegments;
  37892. var v = modJ / tubularSegments * 2 * Math.PI;
  37893. var cx = -tube * Math.cos(v);
  37894. var cy = tube * Math.sin(v);
  37895. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37896. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37897. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37898. uvs.push(i / radialSegments);
  37899. uvs.push(j / tubularSegments);
  37900. }
  37901. }
  37902. for (i = 0; i < radialSegments; i++) {
  37903. for (j = 0; j < tubularSegments; j++) {
  37904. var jNext = (j + 1) % tubularSegments;
  37905. var a = i * tubularSegments + j;
  37906. var b = (i + 1) * tubularSegments + j;
  37907. var c = (i + 1) * tubularSegments + jNext;
  37908. var d = i * tubularSegments + jNext;
  37909. indices.push(d);
  37910. indices.push(b);
  37911. indices.push(a);
  37912. indices.push(d);
  37913. indices.push(c);
  37914. indices.push(b);
  37915. }
  37916. }
  37917. // Normals
  37918. VertexData.ComputeNormals(positions, indices, normals);
  37919. // Sides
  37920. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37921. // Result
  37922. var vertexData = new VertexData();
  37923. vertexData.indices = indices;
  37924. vertexData.positions = positions;
  37925. vertexData.normals = normals;
  37926. vertexData.uvs = uvs;
  37927. return vertexData;
  37928. };
  37929. // Tools
  37930. /**
  37931. * Compute normals for given positions and indices
  37932. * @param positions an array of vertex positions, [...., x, y, z, ......]
  37933. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  37934. * @param normals an array of vertex normals, [...., x, y, z, ......]
  37935. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  37936. * * facetNormals : optional array of facet normals (vector3)
  37937. * * facetPositions : optional array of facet positions (vector3)
  37938. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37939. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37940. * * bInfo : optional bounding info, required for facetPartitioning computation
  37941. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  37942. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37943. * * useRightHandedSystem: optional boolean to for right handed system computation
  37944. * * depthSort : optional boolean to enable the facet depth sort computation
  37945. * * distanceTo : optional Vector3 to compute the facet depth from this location
  37946. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  37947. */
  37948. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37949. // temporary scalar variables
  37950. var index = 0; // facet index
  37951. var p1p2x = 0.0; // p1p2 vector x coordinate
  37952. var p1p2y = 0.0; // p1p2 vector y coordinate
  37953. var p1p2z = 0.0; // p1p2 vector z coordinate
  37954. var p3p2x = 0.0; // p3p2 vector x coordinate
  37955. var p3p2y = 0.0; // p3p2 vector y coordinate
  37956. var p3p2z = 0.0; // p3p2 vector z coordinate
  37957. var faceNormalx = 0.0; // facet normal x coordinate
  37958. var faceNormaly = 0.0; // facet normal y coordinate
  37959. var faceNormalz = 0.0; // facet normal z coordinate
  37960. var length = 0.0; // facet normal length before normalization
  37961. var v1x = 0; // vector1 x index in the positions array
  37962. var v1y = 0; // vector1 y index in the positions array
  37963. var v1z = 0; // vector1 z index in the positions array
  37964. var v2x = 0; // vector2 x index in the positions array
  37965. var v2y = 0; // vector2 y index in the positions array
  37966. var v2z = 0; // vector2 z index in the positions array
  37967. var v3x = 0; // vector3 x index in the positions array
  37968. var v3y = 0; // vector3 y index in the positions array
  37969. var v3z = 0; // vector3 z index in the positions array
  37970. var computeFacetNormals = false;
  37971. var computeFacetPositions = false;
  37972. var computeFacetPartitioning = false;
  37973. var computeDepthSort = false;
  37974. var faceNormalSign = 1;
  37975. var ratio = 0;
  37976. var distanceTo = null;
  37977. if (options) {
  37978. computeFacetNormals = (options.facetNormals) ? true : false;
  37979. computeFacetPositions = (options.facetPositions) ? true : false;
  37980. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37981. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  37982. ratio = options.ratio || 0;
  37983. computeDepthSort = (options.depthSort) ? true : false;
  37984. distanceTo = (options.distanceTo);
  37985. if (computeDepthSort) {
  37986. if (distanceTo === undefined) {
  37987. distanceTo = BABYLON.Vector3.Zero();
  37988. }
  37989. var depthSortedFacets = options.depthSortedFacets;
  37990. }
  37991. }
  37992. // facetPartitioning reinit if needed
  37993. var xSubRatio = 0;
  37994. var ySubRatio = 0;
  37995. var zSubRatio = 0;
  37996. var subSq = 0;
  37997. if (computeFacetPartitioning && options && options.bbSize) {
  37998. var ox = 0; // X partitioning index for facet position
  37999. var oy = 0; // Y partinioning index for facet position
  38000. var oz = 0; // Z partinioning index for facet position
  38001. var b1x = 0; // X partitioning index for facet v1 vertex
  38002. var b1y = 0; // Y partitioning index for facet v1 vertex
  38003. var b1z = 0; // z partitioning index for facet v1 vertex
  38004. var b2x = 0; // X partitioning index for facet v2 vertex
  38005. var b2y = 0; // Y partitioning index for facet v2 vertex
  38006. var b2z = 0; // Z partitioning index for facet v2 vertex
  38007. var b3x = 0; // X partitioning index for facet v3 vertex
  38008. var b3y = 0; // Y partitioning index for facet v3 vertex
  38009. var b3z = 0; // Z partitioning index for facet v3 vertex
  38010. var block_idx_o = 0; // facet barycenter block index
  38011. var block_idx_v1 = 0; // v1 vertex block index
  38012. var block_idx_v2 = 0; // v2 vertex block index
  38013. var block_idx_v3 = 0; // v3 vertex block index
  38014. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38015. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38016. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38017. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38018. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38019. subSq = options.subDiv.max * options.subDiv.max;
  38020. options.facetPartitioning.length = 0;
  38021. }
  38022. // reset the normals
  38023. for (index = 0; index < positions.length; index++) {
  38024. normals[index] = 0.0;
  38025. }
  38026. // Loop : 1 indice triplet = 1 facet
  38027. var nbFaces = (indices.length / 3) | 0;
  38028. for (index = 0; index < nbFaces; index++) {
  38029. // get the indexes of the coordinates of each vertex of the facet
  38030. v1x = indices[index * 3] * 3;
  38031. v1y = v1x + 1;
  38032. v1z = v1x + 2;
  38033. v2x = indices[index * 3 + 1] * 3;
  38034. v2y = v2x + 1;
  38035. v2z = v2x + 2;
  38036. v3x = indices[index * 3 + 2] * 3;
  38037. v3y = v3x + 1;
  38038. v3z = v3x + 2;
  38039. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38040. p1p2y = positions[v1y] - positions[v2y];
  38041. p1p2z = positions[v1z] - positions[v2z];
  38042. p3p2x = positions[v3x] - positions[v2x];
  38043. p3p2y = positions[v3y] - positions[v2y];
  38044. p3p2z = positions[v3z] - positions[v2z];
  38045. // compute the face normal with the cross product
  38046. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38047. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38048. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38049. // normalize this normal and store it in the array facetData
  38050. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38051. length = (length === 0) ? 1.0 : length;
  38052. faceNormalx /= length;
  38053. faceNormaly /= length;
  38054. faceNormalz /= length;
  38055. if (computeFacetNormals && options) {
  38056. options.facetNormals[index].x = faceNormalx;
  38057. options.facetNormals[index].y = faceNormaly;
  38058. options.facetNormals[index].z = faceNormalz;
  38059. }
  38060. if (computeFacetPositions && options) {
  38061. // compute and the facet barycenter coordinates in the array facetPositions
  38062. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38063. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38064. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38065. }
  38066. if (computeFacetPartitioning && options) {
  38067. // store the facet indexes in arrays in the main facetPartitioning array :
  38068. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38069. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38070. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38071. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38072. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38073. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38074. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38075. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38076. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38077. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38078. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38079. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38080. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38081. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38082. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38083. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38084. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38085. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38086. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38087. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38088. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38089. // push each facet index in each block containing the vertex
  38090. options.facetPartitioning[block_idx_v1].push(index);
  38091. if (block_idx_v2 != block_idx_v1) {
  38092. options.facetPartitioning[block_idx_v2].push(index);
  38093. }
  38094. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38095. options.facetPartitioning[block_idx_v3].push(index);
  38096. }
  38097. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38098. options.facetPartitioning[block_idx_o].push(index);
  38099. }
  38100. }
  38101. if (computeDepthSort && options && options.facetPositions) {
  38102. var dsf = depthSortedFacets[index];
  38103. dsf.ind = index * 3;
  38104. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38105. }
  38106. // compute the normals anyway
  38107. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38108. normals[v1y] += faceNormaly;
  38109. normals[v1z] += faceNormalz;
  38110. normals[v2x] += faceNormalx;
  38111. normals[v2y] += faceNormaly;
  38112. normals[v2z] += faceNormalz;
  38113. normals[v3x] += faceNormalx;
  38114. normals[v3y] += faceNormaly;
  38115. normals[v3z] += faceNormalz;
  38116. }
  38117. // last normalization of each normal
  38118. for (index = 0; index < normals.length / 3; index++) {
  38119. faceNormalx = normals[index * 3];
  38120. faceNormaly = normals[index * 3 + 1];
  38121. faceNormalz = normals[index * 3 + 2];
  38122. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38123. length = (length === 0) ? 1.0 : length;
  38124. faceNormalx /= length;
  38125. faceNormaly /= length;
  38126. faceNormalz /= length;
  38127. normals[index * 3] = faceNormalx;
  38128. normals[index * 3 + 1] = faceNormaly;
  38129. normals[index * 3 + 2] = faceNormalz;
  38130. }
  38131. };
  38132. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38133. var li = indices.length;
  38134. var ln = normals.length;
  38135. var i;
  38136. var n;
  38137. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38138. switch (sideOrientation) {
  38139. case BABYLON.Mesh.FRONTSIDE:
  38140. // nothing changed
  38141. break;
  38142. case BABYLON.Mesh.BACKSIDE:
  38143. var tmp;
  38144. // indices
  38145. for (i = 0; i < li; i += 3) {
  38146. tmp = indices[i];
  38147. indices[i] = indices[i + 2];
  38148. indices[i + 2] = tmp;
  38149. }
  38150. // normals
  38151. for (n = 0; n < ln; n++) {
  38152. normals[n] = -normals[n];
  38153. }
  38154. break;
  38155. case BABYLON.Mesh.DOUBLESIDE:
  38156. // positions
  38157. var lp = positions.length;
  38158. var l = lp / 3;
  38159. for (var p = 0; p < lp; p++) {
  38160. positions[lp + p] = positions[p];
  38161. }
  38162. // indices
  38163. for (i = 0; i < li; i += 3) {
  38164. indices[i + li] = indices[i + 2] + l;
  38165. indices[i + 1 + li] = indices[i + 1] + l;
  38166. indices[i + 2 + li] = indices[i] + l;
  38167. }
  38168. // normals
  38169. for (n = 0; n < ln; n++) {
  38170. normals[ln + n] = -normals[n];
  38171. }
  38172. // uvs
  38173. var lu = uvs.length;
  38174. var u = 0;
  38175. for (u = 0; u < lu; u++) {
  38176. uvs[u + lu] = uvs[u];
  38177. }
  38178. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38179. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38180. u = 0;
  38181. for (i = 0; i < lu / 2; i++) {
  38182. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38183. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38184. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38185. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38186. u += 2;
  38187. }
  38188. break;
  38189. }
  38190. };
  38191. /**
  38192. * Applies VertexData created from the imported parameters to the geometry
  38193. * @param parsedVertexData the parsed data from an imported file
  38194. * @param geometry the geometry to apply the VertexData to
  38195. */
  38196. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38197. var vertexData = new VertexData();
  38198. // positions
  38199. var positions = parsedVertexData.positions;
  38200. if (positions) {
  38201. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38202. }
  38203. // normals
  38204. var normals = parsedVertexData.normals;
  38205. if (normals) {
  38206. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38207. }
  38208. // tangents
  38209. var tangents = parsedVertexData.tangents;
  38210. if (tangents) {
  38211. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38212. }
  38213. // uvs
  38214. var uvs = parsedVertexData.uvs;
  38215. if (uvs) {
  38216. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38217. }
  38218. // uv2s
  38219. var uv2s = parsedVertexData.uv2s;
  38220. if (uv2s) {
  38221. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38222. }
  38223. // uv3s
  38224. var uv3s = parsedVertexData.uv3s;
  38225. if (uv3s) {
  38226. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38227. }
  38228. // uv4s
  38229. var uv4s = parsedVertexData.uv4s;
  38230. if (uv4s) {
  38231. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38232. }
  38233. // uv5s
  38234. var uv5s = parsedVertexData.uv5s;
  38235. if (uv5s) {
  38236. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38237. }
  38238. // uv6s
  38239. var uv6s = parsedVertexData.uv6s;
  38240. if (uv6s) {
  38241. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38242. }
  38243. // colors
  38244. var colors = parsedVertexData.colors;
  38245. if (colors) {
  38246. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38247. }
  38248. // matricesIndices
  38249. var matricesIndices = parsedVertexData.matricesIndices;
  38250. if (matricesIndices) {
  38251. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38252. }
  38253. // matricesWeights
  38254. var matricesWeights = parsedVertexData.matricesWeights;
  38255. if (matricesWeights) {
  38256. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38257. }
  38258. // indices
  38259. var indices = parsedVertexData.indices;
  38260. if (indices) {
  38261. vertexData.indices = indices;
  38262. }
  38263. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38264. };
  38265. return VertexData;
  38266. }());
  38267. BABYLON.VertexData = VertexData;
  38268. })(BABYLON || (BABYLON = {}));
  38269. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38270. var BABYLON;
  38271. (function (BABYLON) {
  38272. /**
  38273. * Class used to store geometry data (vertex buffers + index buffer)
  38274. */
  38275. var Geometry = /** @class */ (function () {
  38276. /**
  38277. * Creates a new geometry
  38278. * @param id defines the unique ID
  38279. * @param scene defines the hosting scene
  38280. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38281. * @param updatable defines if geometry must be updatable (false by default)
  38282. * @param mesh defines the mesh that will be associated with the geometry
  38283. */
  38284. function Geometry(id, scene, vertexData, updatable, mesh) {
  38285. if (updatable === void 0) { updatable = false; }
  38286. if (mesh === void 0) { mesh = null; }
  38287. /**
  38288. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38289. */
  38290. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38291. this._totalVertices = 0;
  38292. this._isDisposed = false;
  38293. this._indexBufferIsUpdatable = false;
  38294. this.id = id;
  38295. this._engine = scene.getEngine();
  38296. this._meshes = [];
  38297. this._scene = scene;
  38298. //Init vertex buffer cache
  38299. this._vertexBuffers = {};
  38300. this._indices = [];
  38301. this._updatable = updatable;
  38302. // vertexData
  38303. if (vertexData) {
  38304. this.setAllVerticesData(vertexData, updatable);
  38305. }
  38306. else {
  38307. this._totalVertices = 0;
  38308. this._indices = [];
  38309. }
  38310. if (this._engine.getCaps().vertexArrayObject) {
  38311. this._vertexArrayObjects = {};
  38312. }
  38313. // applyToMesh
  38314. if (mesh) {
  38315. if (mesh.getClassName() === "LinesMesh") {
  38316. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38317. this._updateExtend();
  38318. }
  38319. this.applyToMesh(mesh);
  38320. mesh.computeWorldMatrix(true);
  38321. }
  38322. }
  38323. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38324. /**
  38325. * 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
  38326. */
  38327. get: function () {
  38328. return this._boundingBias;
  38329. },
  38330. /**
  38331. * 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
  38332. */
  38333. set: function (value) {
  38334. if (this._boundingBias && this._boundingBias.equals(value)) {
  38335. return;
  38336. }
  38337. this._boundingBias = value.clone();
  38338. this._updateBoundingInfo(true, null);
  38339. },
  38340. enumerable: true,
  38341. configurable: true
  38342. });
  38343. /**
  38344. * Static function used to attach a new empty geometry to a mesh
  38345. * @param mesh defines the mesh to attach the geometry to
  38346. * @returns the new {BABYLON.Geometry}
  38347. */
  38348. Geometry.CreateGeometryForMesh = function (mesh) {
  38349. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38350. geometry.applyToMesh(mesh);
  38351. return geometry;
  38352. };
  38353. Object.defineProperty(Geometry.prototype, "extend", {
  38354. /**
  38355. * Gets the current extend of the geometry
  38356. */
  38357. get: function () {
  38358. return this._extend;
  38359. },
  38360. enumerable: true,
  38361. configurable: true
  38362. });
  38363. /**
  38364. * Gets the hosting scene
  38365. * @returns the hosting {BABYLON.Scene}
  38366. */
  38367. Geometry.prototype.getScene = function () {
  38368. return this._scene;
  38369. };
  38370. /**
  38371. * Gets the hosting engine
  38372. * @returns the hosting {BABYLON.Engine}
  38373. */
  38374. Geometry.prototype.getEngine = function () {
  38375. return this._engine;
  38376. };
  38377. /**
  38378. * Defines if the geometry is ready to use
  38379. * @returns true if the geometry is ready to be used
  38380. */
  38381. Geometry.prototype.isReady = function () {
  38382. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38383. };
  38384. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38385. /**
  38386. * Gets a value indicating that the geometry should not be serialized
  38387. */
  38388. get: function () {
  38389. for (var index = 0; index < this._meshes.length; index++) {
  38390. if (!this._meshes[index].doNotSerialize) {
  38391. return false;
  38392. }
  38393. }
  38394. return true;
  38395. },
  38396. enumerable: true,
  38397. configurable: true
  38398. });
  38399. /** @hidden */
  38400. Geometry.prototype._rebuild = function () {
  38401. if (this._vertexArrayObjects) {
  38402. this._vertexArrayObjects = {};
  38403. }
  38404. // Index buffer
  38405. if (this._meshes.length !== 0 && this._indices) {
  38406. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38407. }
  38408. // Vertex buffers
  38409. for (var key in this._vertexBuffers) {
  38410. var vertexBuffer = this._vertexBuffers[key];
  38411. vertexBuffer._rebuild();
  38412. }
  38413. };
  38414. /**
  38415. * Affects all geometry data in one call
  38416. * @param vertexData defines the geometry data
  38417. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38418. */
  38419. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38420. vertexData.applyToGeometry(this, updatable);
  38421. this.notifyUpdate();
  38422. };
  38423. /**
  38424. * Set specific vertex data
  38425. * @param kind defines the data kind (Position, normal, etc...)
  38426. * @param data defines the vertex data to use
  38427. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38428. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38429. */
  38430. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38431. if (updatable === void 0) { updatable = false; }
  38432. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38433. this.setVerticesBuffer(buffer);
  38434. };
  38435. /**
  38436. * Removes a specific vertex data
  38437. * @param kind defines the data kind (Position, normal, etc...)
  38438. */
  38439. Geometry.prototype.removeVerticesData = function (kind) {
  38440. if (this._vertexBuffers[kind]) {
  38441. this._vertexBuffers[kind].dispose();
  38442. delete this._vertexBuffers[kind];
  38443. }
  38444. };
  38445. /**
  38446. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38447. * @param buffer defines the vertex buffer to use
  38448. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38449. */
  38450. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38451. if (totalVertices === void 0) { totalVertices = null; }
  38452. var kind = buffer.getKind();
  38453. if (this._vertexBuffers[kind]) {
  38454. this._vertexBuffers[kind].dispose();
  38455. }
  38456. this._vertexBuffers[kind] = buffer;
  38457. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38458. var data = buffer.getData();
  38459. if (totalVertices != null) {
  38460. this._totalVertices = totalVertices;
  38461. }
  38462. else {
  38463. if (data != null) {
  38464. this._totalVertices = data.length / (buffer.byteStride / 4);
  38465. }
  38466. }
  38467. this._updateExtend(data);
  38468. this._resetPointsArrayCache();
  38469. var meshes = this._meshes;
  38470. var numOfMeshes = meshes.length;
  38471. for (var index = 0; index < numOfMeshes; index++) {
  38472. var mesh = meshes[index];
  38473. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38474. mesh._createGlobalSubMesh(false);
  38475. mesh.computeWorldMatrix(true);
  38476. }
  38477. }
  38478. this.notifyUpdate(kind);
  38479. if (this._vertexArrayObjects) {
  38480. this._disposeVertexArrayObjects();
  38481. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38482. }
  38483. };
  38484. /**
  38485. * Update a specific vertex buffer
  38486. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38487. * It will do nothing if the buffer is not updatable
  38488. * @param kind defines the data kind (Position, normal, etc...)
  38489. * @param data defines the data to use
  38490. * @param offset defines the offset in the target buffer where to store the data
  38491. * @param useBytes set to true if the offset is in bytes
  38492. */
  38493. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38494. if (useBytes === void 0) { useBytes = false; }
  38495. var vertexBuffer = this.getVertexBuffer(kind);
  38496. if (!vertexBuffer) {
  38497. return;
  38498. }
  38499. vertexBuffer.updateDirectly(data, offset, useBytes);
  38500. this.notifyUpdate(kind);
  38501. };
  38502. /**
  38503. * Update a specific vertex buffer
  38504. * This function will create a new buffer if the current one is not updatable
  38505. * @param kind defines the data kind (Position, normal, etc...)
  38506. * @param data defines the data to use
  38507. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38508. */
  38509. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38510. if (updateExtends === void 0) { updateExtends = false; }
  38511. var vertexBuffer = this.getVertexBuffer(kind);
  38512. if (!vertexBuffer) {
  38513. return;
  38514. }
  38515. vertexBuffer.update(data);
  38516. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38517. this._updateBoundingInfo(updateExtends, data);
  38518. }
  38519. this.notifyUpdate(kind);
  38520. };
  38521. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38522. if (updateExtends) {
  38523. this._updateExtend(data);
  38524. }
  38525. var meshes = this._meshes;
  38526. var numOfMeshes = meshes.length;
  38527. this._resetPointsArrayCache();
  38528. for (var index = 0; index < numOfMeshes; index++) {
  38529. var mesh = meshes[index];
  38530. if (updateExtends) {
  38531. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38532. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38533. var subMesh = mesh.subMeshes[subIndex];
  38534. subMesh.refreshBoundingInfo();
  38535. }
  38536. }
  38537. }
  38538. };
  38539. /** @hidden */
  38540. Geometry.prototype._bind = function (effect, indexToBind) {
  38541. if (!effect) {
  38542. return;
  38543. }
  38544. if (indexToBind === undefined) {
  38545. indexToBind = this._indexBuffer;
  38546. }
  38547. var vbs = this.getVertexBuffers();
  38548. if (!vbs) {
  38549. return;
  38550. }
  38551. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38552. this._engine.bindBuffers(vbs, indexToBind, effect);
  38553. return;
  38554. }
  38555. // Using VAO
  38556. if (!this._vertexArrayObjects[effect.key]) {
  38557. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38558. }
  38559. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38560. };
  38561. /**
  38562. * Gets total number of vertices
  38563. * @returns the total number of vertices
  38564. */
  38565. Geometry.prototype.getTotalVertices = function () {
  38566. if (!this.isReady()) {
  38567. return 0;
  38568. }
  38569. return this._totalVertices;
  38570. };
  38571. /**
  38572. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38573. * @param kind defines the data kind (Position, normal, etc...)
  38574. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38575. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38576. * @returns a float array containing vertex data
  38577. */
  38578. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38579. var vertexBuffer = this.getVertexBuffer(kind);
  38580. if (!vertexBuffer) {
  38581. return null;
  38582. }
  38583. var data = vertexBuffer.getData();
  38584. if (!data) {
  38585. return null;
  38586. }
  38587. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38588. var count = this._totalVertices * vertexBuffer.getSize();
  38589. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38590. var copy_1 = new Array(count);
  38591. vertexBuffer.forEach(count, function (value, index) {
  38592. copy_1[index] = value;
  38593. });
  38594. return copy_1;
  38595. }
  38596. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38597. if (data instanceof Array) {
  38598. var offset = vertexBuffer.byteOffset / 4;
  38599. return BABYLON.Tools.Slice(data, offset, offset + count);
  38600. }
  38601. else if (data instanceof ArrayBuffer) {
  38602. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38603. }
  38604. else {
  38605. var offset = data.byteOffset + vertexBuffer.byteOffset;
  38606. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38607. var result = new Float32Array(count);
  38608. var source = new Float32Array(data.buffer, offset, count);
  38609. result.set(source);
  38610. return result;
  38611. }
  38612. return new Float32Array(data.buffer, offset, count);
  38613. }
  38614. }
  38615. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38616. return BABYLON.Tools.Slice(data);
  38617. }
  38618. return data;
  38619. };
  38620. /**
  38621. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38622. * @param kind defines the data kind (Position, normal, etc...)
  38623. * @returns true if the vertex buffer with the specified kind is updatable
  38624. */
  38625. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38626. var vb = this._vertexBuffers[kind];
  38627. if (!vb) {
  38628. return false;
  38629. }
  38630. return vb.isUpdatable();
  38631. };
  38632. /**
  38633. * Gets a specific vertex buffer
  38634. * @param kind defines the data kind (Position, normal, etc...)
  38635. * @returns a {BABYLON.VertexBuffer}
  38636. */
  38637. Geometry.prototype.getVertexBuffer = function (kind) {
  38638. if (!this.isReady()) {
  38639. return null;
  38640. }
  38641. return this._vertexBuffers[kind];
  38642. };
  38643. /**
  38644. * Returns all vertex buffers
  38645. * @return an object holding all vertex buffers indexed by kind
  38646. */
  38647. Geometry.prototype.getVertexBuffers = function () {
  38648. if (!this.isReady()) {
  38649. return null;
  38650. }
  38651. return this._vertexBuffers;
  38652. };
  38653. /**
  38654. * Gets a boolean indicating if specific vertex buffer is present
  38655. * @param kind defines the data kind (Position, normal, etc...)
  38656. * @returns true if data is present
  38657. */
  38658. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38659. if (!this._vertexBuffers) {
  38660. if (this._delayInfo) {
  38661. return this._delayInfo.indexOf(kind) !== -1;
  38662. }
  38663. return false;
  38664. }
  38665. return this._vertexBuffers[kind] !== undefined;
  38666. };
  38667. /**
  38668. * Gets a list of all attached data kinds (Position, normal, etc...)
  38669. * @returns a list of string containing all kinds
  38670. */
  38671. Geometry.prototype.getVerticesDataKinds = function () {
  38672. var result = [];
  38673. var kind;
  38674. if (!this._vertexBuffers && this._delayInfo) {
  38675. for (kind in this._delayInfo) {
  38676. result.push(kind);
  38677. }
  38678. }
  38679. else {
  38680. for (kind in this._vertexBuffers) {
  38681. result.push(kind);
  38682. }
  38683. }
  38684. return result;
  38685. };
  38686. /**
  38687. * Update index buffer
  38688. * @param indices defines the indices to store in the index buffer
  38689. * @param offset defines the offset in the target buffer where to store the data
  38690. */
  38691. Geometry.prototype.updateIndices = function (indices, offset) {
  38692. if (!this._indexBuffer) {
  38693. return;
  38694. }
  38695. if (!this._indexBufferIsUpdatable) {
  38696. this.setIndices(indices, null, true);
  38697. }
  38698. else {
  38699. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38700. }
  38701. };
  38702. /**
  38703. * Creates a new index buffer
  38704. * @param indices defines the indices to store in the index buffer
  38705. * @param totalVertices defines the total number of vertices (could be null)
  38706. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38707. */
  38708. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38709. if (totalVertices === void 0) { totalVertices = null; }
  38710. if (updatable === void 0) { updatable = false; }
  38711. if (this._indexBuffer) {
  38712. this._engine._releaseBuffer(this._indexBuffer);
  38713. }
  38714. this._disposeVertexArrayObjects();
  38715. this._indices = indices;
  38716. this._indexBufferIsUpdatable = updatable;
  38717. if (this._meshes.length !== 0 && this._indices) {
  38718. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38719. }
  38720. if (totalVertices != undefined) { // including null and undefined
  38721. this._totalVertices = totalVertices;
  38722. }
  38723. var meshes = this._meshes;
  38724. var numOfMeshes = meshes.length;
  38725. for (var index = 0; index < numOfMeshes; index++) {
  38726. meshes[index]._createGlobalSubMesh(true);
  38727. }
  38728. this.notifyUpdate();
  38729. };
  38730. /**
  38731. * Return the total number of indices
  38732. * @returns the total number of indices
  38733. */
  38734. Geometry.prototype.getTotalIndices = function () {
  38735. if (!this.isReady()) {
  38736. return 0;
  38737. }
  38738. return this._indices.length;
  38739. };
  38740. /**
  38741. * Gets the index buffer array
  38742. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38743. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38744. * @returns the index buffer array
  38745. */
  38746. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  38747. if (!this.isReady()) {
  38748. return null;
  38749. }
  38750. var orig = this._indices;
  38751. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  38752. return orig;
  38753. }
  38754. else {
  38755. var len = orig.length;
  38756. var copy = [];
  38757. for (var i = 0; i < len; i++) {
  38758. copy.push(orig[i]);
  38759. }
  38760. return copy;
  38761. }
  38762. };
  38763. /**
  38764. * Gets the index buffer
  38765. * @return the index buffer
  38766. */
  38767. Geometry.prototype.getIndexBuffer = function () {
  38768. if (!this.isReady()) {
  38769. return null;
  38770. }
  38771. return this._indexBuffer;
  38772. };
  38773. /** @hidden */
  38774. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38775. if (effect === void 0) { effect = null; }
  38776. if (!effect || !this._vertexArrayObjects) {
  38777. return;
  38778. }
  38779. if (this._vertexArrayObjects[effect.key]) {
  38780. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38781. delete this._vertexArrayObjects[effect.key];
  38782. }
  38783. };
  38784. /**
  38785. * Release the associated resources for a specific mesh
  38786. * @param mesh defines the source mesh
  38787. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38788. */
  38789. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38790. var meshes = this._meshes;
  38791. var index = meshes.indexOf(mesh);
  38792. if (index === -1) {
  38793. return;
  38794. }
  38795. meshes.splice(index, 1);
  38796. mesh._geometry = null;
  38797. if (meshes.length === 0 && shouldDispose) {
  38798. this.dispose();
  38799. }
  38800. };
  38801. /**
  38802. * Apply current geometry to a given mesh
  38803. * @param mesh defines the mesh to apply geometry to
  38804. */
  38805. Geometry.prototype.applyToMesh = function (mesh) {
  38806. if (mesh._geometry === this) {
  38807. return;
  38808. }
  38809. var previousGeometry = mesh._geometry;
  38810. if (previousGeometry) {
  38811. previousGeometry.releaseForMesh(mesh);
  38812. }
  38813. var meshes = this._meshes;
  38814. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38815. mesh._geometry = this;
  38816. this._scene.pushGeometry(this);
  38817. meshes.push(mesh);
  38818. if (this.isReady()) {
  38819. this._applyToMesh(mesh);
  38820. }
  38821. else {
  38822. mesh._boundingInfo = this._boundingInfo;
  38823. }
  38824. };
  38825. Geometry.prototype._updateExtend = function (data) {
  38826. if (data === void 0) { data = null; }
  38827. if (!data) {
  38828. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38829. }
  38830. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38831. };
  38832. Geometry.prototype._applyToMesh = function (mesh) {
  38833. var numOfMeshes = this._meshes.length;
  38834. // vertexBuffers
  38835. for (var kind in this._vertexBuffers) {
  38836. if (numOfMeshes === 1) {
  38837. this._vertexBuffers[kind].create();
  38838. }
  38839. var buffer = this._vertexBuffers[kind].getBuffer();
  38840. if (buffer)
  38841. buffer.references = numOfMeshes;
  38842. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38843. if (!this._extend) {
  38844. this._updateExtend();
  38845. }
  38846. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38847. mesh._createGlobalSubMesh(false);
  38848. //bounding info was just created again, world matrix should be applied again.
  38849. mesh._updateBoundingInfo();
  38850. }
  38851. }
  38852. // indexBuffer
  38853. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38854. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38855. }
  38856. if (this._indexBuffer) {
  38857. this._indexBuffer.references = numOfMeshes;
  38858. }
  38859. };
  38860. Geometry.prototype.notifyUpdate = function (kind) {
  38861. if (this.onGeometryUpdated) {
  38862. this.onGeometryUpdated(this, kind);
  38863. }
  38864. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38865. var mesh = _a[_i];
  38866. mesh._markSubMeshesAsAttributesDirty();
  38867. }
  38868. };
  38869. /**
  38870. * Load the geometry if it was flagged as delay loaded
  38871. * @param scene defines the hosting scene
  38872. * @param onLoaded defines a callback called when the geometry is loaded
  38873. */
  38874. Geometry.prototype.load = function (scene, onLoaded) {
  38875. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38876. return;
  38877. }
  38878. if (this.isReady()) {
  38879. if (onLoaded) {
  38880. onLoaded();
  38881. }
  38882. return;
  38883. }
  38884. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38885. this._queueLoad(scene, onLoaded);
  38886. };
  38887. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38888. var _this = this;
  38889. if (!this.delayLoadingFile) {
  38890. return;
  38891. }
  38892. scene._addPendingData(this);
  38893. scene._loadFile(this.delayLoadingFile, function (data) {
  38894. if (!_this._delayLoadingFunction) {
  38895. return;
  38896. }
  38897. _this._delayLoadingFunction(JSON.parse(data), _this);
  38898. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38899. _this._delayInfo = [];
  38900. scene._removePendingData(_this);
  38901. var meshes = _this._meshes;
  38902. var numOfMeshes = meshes.length;
  38903. for (var index = 0; index < numOfMeshes; index++) {
  38904. _this._applyToMesh(meshes[index]);
  38905. }
  38906. if (onLoaded) {
  38907. onLoaded();
  38908. }
  38909. }, undefined, true);
  38910. };
  38911. /**
  38912. * Invert the geometry to move from a right handed system to a left handed one.
  38913. */
  38914. Geometry.prototype.toLeftHanded = function () {
  38915. // Flip faces
  38916. var tIndices = this.getIndices(false);
  38917. if (tIndices != null && tIndices.length > 0) {
  38918. for (var i = 0; i < tIndices.length; i += 3) {
  38919. var tTemp = tIndices[i + 0];
  38920. tIndices[i + 0] = tIndices[i + 2];
  38921. tIndices[i + 2] = tTemp;
  38922. }
  38923. this.setIndices(tIndices);
  38924. }
  38925. // Negate position.z
  38926. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  38927. if (tPositions != null && tPositions.length > 0) {
  38928. for (var i = 0; i < tPositions.length; i += 3) {
  38929. tPositions[i + 2] = -tPositions[i + 2];
  38930. }
  38931. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  38932. }
  38933. // Negate normal.z
  38934. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  38935. if (tNormals != null && tNormals.length > 0) {
  38936. for (var i = 0; i < tNormals.length; i += 3) {
  38937. tNormals[i + 2] = -tNormals[i + 2];
  38938. }
  38939. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  38940. }
  38941. };
  38942. // Cache
  38943. /** @hidden */
  38944. Geometry.prototype._resetPointsArrayCache = function () {
  38945. this._positions = null;
  38946. };
  38947. /** @hidden */
  38948. Geometry.prototype._generatePointsArray = function () {
  38949. if (this._positions)
  38950. return true;
  38951. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38952. if (!data || data.length === 0) {
  38953. return false;
  38954. }
  38955. this._positions = [];
  38956. for (var index = 0; index < data.length; index += 3) {
  38957. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  38958. }
  38959. return true;
  38960. };
  38961. /**
  38962. * Gets a value indicating if the geometry is disposed
  38963. * @returns true if the geometry was disposed
  38964. */
  38965. Geometry.prototype.isDisposed = function () {
  38966. return this._isDisposed;
  38967. };
  38968. Geometry.prototype._disposeVertexArrayObjects = function () {
  38969. if (this._vertexArrayObjects) {
  38970. for (var kind in this._vertexArrayObjects) {
  38971. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  38972. }
  38973. this._vertexArrayObjects = {};
  38974. }
  38975. };
  38976. /**
  38977. * Free all associated resources
  38978. */
  38979. Geometry.prototype.dispose = function () {
  38980. var meshes = this._meshes;
  38981. var numOfMeshes = meshes.length;
  38982. var index;
  38983. for (index = 0; index < numOfMeshes; index++) {
  38984. this.releaseForMesh(meshes[index]);
  38985. }
  38986. this._meshes = [];
  38987. this._disposeVertexArrayObjects();
  38988. for (var kind in this._vertexBuffers) {
  38989. this._vertexBuffers[kind].dispose();
  38990. }
  38991. this._vertexBuffers = {};
  38992. this._totalVertices = 0;
  38993. if (this._indexBuffer) {
  38994. this._engine._releaseBuffer(this._indexBuffer);
  38995. }
  38996. this._indexBuffer = null;
  38997. this._indices = [];
  38998. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38999. this.delayLoadingFile = null;
  39000. this._delayLoadingFunction = null;
  39001. this._delayInfo = [];
  39002. this._boundingInfo = null;
  39003. this._scene.removeGeometry(this);
  39004. this._isDisposed = true;
  39005. };
  39006. /**
  39007. * Clone the current geometry into a new geometry
  39008. * @param id defines the unique ID of the new geometry
  39009. * @returns a new geometry object
  39010. */
  39011. Geometry.prototype.copy = function (id) {
  39012. var vertexData = new BABYLON.VertexData();
  39013. vertexData.indices = [];
  39014. var indices = this.getIndices();
  39015. if (indices) {
  39016. for (var index = 0; index < indices.length; index++) {
  39017. vertexData.indices.push(indices[index]);
  39018. }
  39019. }
  39020. var updatable = false;
  39021. var stopChecking = false;
  39022. var kind;
  39023. for (kind in this._vertexBuffers) {
  39024. // using slice() to make a copy of the array and not just reference it
  39025. var data = this.getVerticesData(kind);
  39026. if (data instanceof Float32Array) {
  39027. vertexData.set(new Float32Array(data), kind);
  39028. }
  39029. else {
  39030. vertexData.set(data.slice(0), kind);
  39031. }
  39032. if (!stopChecking) {
  39033. var vb = this.getVertexBuffer(kind);
  39034. if (vb) {
  39035. updatable = vb.isUpdatable();
  39036. stopChecking = !updatable;
  39037. }
  39038. }
  39039. }
  39040. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39041. geometry.delayLoadState = this.delayLoadState;
  39042. geometry.delayLoadingFile = this.delayLoadingFile;
  39043. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39044. for (kind in this._delayInfo) {
  39045. geometry._delayInfo = geometry._delayInfo || [];
  39046. geometry._delayInfo.push(kind);
  39047. }
  39048. // Bounding info
  39049. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39050. return geometry;
  39051. };
  39052. /**
  39053. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39054. * @return a JSON representation of the current geometry data (without the vertices data)
  39055. */
  39056. Geometry.prototype.serialize = function () {
  39057. var serializationObject = {};
  39058. serializationObject.id = this.id;
  39059. serializationObject.updatable = this._updatable;
  39060. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39061. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39062. }
  39063. return serializationObject;
  39064. };
  39065. Geometry.prototype.toNumberArray = function (origin) {
  39066. if (Array.isArray(origin)) {
  39067. return origin;
  39068. }
  39069. else {
  39070. return Array.prototype.slice.call(origin);
  39071. }
  39072. };
  39073. /**
  39074. * Serialize all vertices data into a JSON oject
  39075. * @returns a JSON representation of the current geometry data
  39076. */
  39077. Geometry.prototype.serializeVerticeData = function () {
  39078. var serializationObject = this.serialize();
  39079. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39080. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39081. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39082. serializationObject.positions._updatable = true;
  39083. }
  39084. }
  39085. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39086. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39087. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39088. serializationObject.normals._updatable = true;
  39089. }
  39090. }
  39091. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39092. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39093. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39094. serializationObject.tangets._updatable = true;
  39095. }
  39096. }
  39097. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39098. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39099. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39100. serializationObject.uvs._updatable = true;
  39101. }
  39102. }
  39103. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39104. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39105. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39106. serializationObject.uv2s._updatable = true;
  39107. }
  39108. }
  39109. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39110. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39111. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39112. serializationObject.uv3s._updatable = true;
  39113. }
  39114. }
  39115. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39116. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39117. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39118. serializationObject.uv4s._updatable = true;
  39119. }
  39120. }
  39121. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39122. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39123. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39124. serializationObject.uv5s._updatable = true;
  39125. }
  39126. }
  39127. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39128. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39129. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39130. serializationObject.uv6s._updatable = true;
  39131. }
  39132. }
  39133. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39134. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39135. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39136. serializationObject.colors._updatable = true;
  39137. }
  39138. }
  39139. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39140. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39141. serializationObject.matricesIndices._isExpanded = true;
  39142. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39143. serializationObject.matricesIndices._updatable = true;
  39144. }
  39145. }
  39146. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39147. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39148. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39149. serializationObject.matricesWeights._updatable = true;
  39150. }
  39151. }
  39152. serializationObject.indices = this.toNumberArray(this.getIndices());
  39153. return serializationObject;
  39154. };
  39155. // Statics
  39156. /**
  39157. * Extracts a clone of a mesh geometry
  39158. * @param mesh defines the source mesh
  39159. * @param id defines the unique ID of the new geometry object
  39160. * @returns the new geometry object
  39161. */
  39162. Geometry.ExtractFromMesh = function (mesh, id) {
  39163. var geometry = mesh._geometry;
  39164. if (!geometry) {
  39165. return null;
  39166. }
  39167. return geometry.copy(id);
  39168. };
  39169. /**
  39170. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39171. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39172. * Be aware Math.random() could cause collisions, but:
  39173. * "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"
  39174. * @returns a string containing a new GUID
  39175. */
  39176. Geometry.RandomId = function () {
  39177. return BABYLON.Tools.RandomId();
  39178. };
  39179. /** @hidden */
  39180. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39181. var scene = mesh.getScene();
  39182. // Geometry
  39183. var geometryId = parsedGeometry.geometryId;
  39184. if (geometryId) {
  39185. var geometry = scene.getGeometryByID(geometryId);
  39186. if (geometry) {
  39187. geometry.applyToMesh(mesh);
  39188. }
  39189. }
  39190. else if (parsedGeometry instanceof ArrayBuffer) {
  39191. var binaryInfo = mesh._binaryInfo;
  39192. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39193. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39194. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39195. }
  39196. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39197. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39198. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39199. }
  39200. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39201. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39202. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39203. }
  39204. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39205. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39206. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39207. }
  39208. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39209. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39210. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39211. }
  39212. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39213. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39214. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39215. }
  39216. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39217. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39218. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39219. }
  39220. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39221. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39222. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39223. }
  39224. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39225. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39226. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39227. }
  39228. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39229. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39230. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39231. }
  39232. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39233. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39234. var floatIndices = [];
  39235. for (var i = 0; i < matricesIndicesData.length; i++) {
  39236. var index = matricesIndicesData[i];
  39237. floatIndices.push(index & 0x000000FF);
  39238. floatIndices.push((index & 0x0000FF00) >> 8);
  39239. floatIndices.push((index & 0x00FF0000) >> 16);
  39240. floatIndices.push(index >> 24);
  39241. }
  39242. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39243. }
  39244. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39245. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39246. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39247. }
  39248. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39249. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39250. mesh.setIndices(indicesData, null);
  39251. }
  39252. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39253. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39254. mesh.subMeshes = [];
  39255. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39256. var materialIndex = subMeshesData[(i * 5) + 0];
  39257. var verticesStart = subMeshesData[(i * 5) + 1];
  39258. var verticesCount = subMeshesData[(i * 5) + 2];
  39259. var indexStart = subMeshesData[(i * 5) + 3];
  39260. var indexCount = subMeshesData[(i * 5) + 4];
  39261. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39262. }
  39263. }
  39264. }
  39265. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39266. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39267. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39268. if (parsedGeometry.tangents) {
  39269. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39270. }
  39271. if (parsedGeometry.uvs) {
  39272. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39273. }
  39274. if (parsedGeometry.uvs2) {
  39275. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39276. }
  39277. if (parsedGeometry.uvs3) {
  39278. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39279. }
  39280. if (parsedGeometry.uvs4) {
  39281. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39282. }
  39283. if (parsedGeometry.uvs5) {
  39284. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39285. }
  39286. if (parsedGeometry.uvs6) {
  39287. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39288. }
  39289. if (parsedGeometry.colors) {
  39290. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39291. }
  39292. if (parsedGeometry.matricesIndices) {
  39293. if (!parsedGeometry.matricesIndices._isExpanded) {
  39294. var floatIndices = [];
  39295. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39296. var matricesIndex = parsedGeometry.matricesIndices[i];
  39297. floatIndices.push(matricesIndex & 0x000000FF);
  39298. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39299. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39300. floatIndices.push(matricesIndex >> 24);
  39301. }
  39302. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39303. }
  39304. else {
  39305. delete parsedGeometry.matricesIndices._isExpanded;
  39306. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39307. }
  39308. }
  39309. if (parsedGeometry.matricesIndicesExtra) {
  39310. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39311. var floatIndices = [];
  39312. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39313. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39314. floatIndices.push(matricesIndex & 0x000000FF);
  39315. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39316. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39317. floatIndices.push(matricesIndex >> 24);
  39318. }
  39319. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39320. }
  39321. else {
  39322. delete parsedGeometry.matricesIndices._isExpanded;
  39323. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39324. }
  39325. }
  39326. if (parsedGeometry.matricesWeights) {
  39327. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39328. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39329. }
  39330. if (parsedGeometry.matricesWeightsExtra) {
  39331. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39332. }
  39333. mesh.setIndices(parsedGeometry.indices, null);
  39334. }
  39335. // SubMeshes
  39336. if (parsedGeometry.subMeshes) {
  39337. mesh.subMeshes = [];
  39338. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39339. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39340. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39341. }
  39342. }
  39343. // Flat shading
  39344. if (mesh._shouldGenerateFlatShading) {
  39345. mesh.convertToFlatShadedMesh();
  39346. delete mesh._shouldGenerateFlatShading;
  39347. }
  39348. // Update
  39349. mesh.computeWorldMatrix(true);
  39350. scene.onMeshImportedObservable.notifyObservers(mesh);
  39351. };
  39352. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39353. var epsilon = 1e-3;
  39354. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39355. return;
  39356. }
  39357. var noInfluenceBoneIndex = 0.0;
  39358. if (parsedGeometry.skeletonId > -1) {
  39359. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39360. if (!skeleton) {
  39361. return;
  39362. }
  39363. noInfluenceBoneIndex = skeleton.bones.length;
  39364. }
  39365. else {
  39366. return;
  39367. }
  39368. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39369. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39370. var matricesWeights = parsedGeometry.matricesWeights;
  39371. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39372. var influencers = parsedGeometry.numBoneInfluencer;
  39373. var size = matricesWeights.length;
  39374. for (var i = 0; i < size; i += 4) {
  39375. var weight = 0.0;
  39376. var firstZeroWeight = -1;
  39377. for (var j = 0; j < 4; j++) {
  39378. var w = matricesWeights[i + j];
  39379. weight += w;
  39380. if (w < epsilon && firstZeroWeight < 0) {
  39381. firstZeroWeight = j;
  39382. }
  39383. }
  39384. if (matricesWeightsExtra) {
  39385. for (var j = 0; j < 4; j++) {
  39386. var w = matricesWeightsExtra[i + j];
  39387. weight += w;
  39388. if (w < epsilon && firstZeroWeight < 0) {
  39389. firstZeroWeight = j + 4;
  39390. }
  39391. }
  39392. }
  39393. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39394. firstZeroWeight = influencers - 1;
  39395. }
  39396. if (weight > epsilon) {
  39397. var mweight = 1.0 / weight;
  39398. for (var j = 0; j < 4; j++) {
  39399. matricesWeights[i + j] *= mweight;
  39400. }
  39401. if (matricesWeightsExtra) {
  39402. for (var j = 0; j < 4; j++) {
  39403. matricesWeightsExtra[i + j] *= mweight;
  39404. }
  39405. }
  39406. }
  39407. else {
  39408. if (firstZeroWeight >= 4) {
  39409. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39410. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39411. }
  39412. else {
  39413. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39414. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39415. }
  39416. }
  39417. }
  39418. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39419. if (parsedGeometry.matricesWeightsExtra) {
  39420. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39421. }
  39422. };
  39423. /**
  39424. * Create a new geometry from persisted data (Using .babylon file format)
  39425. * @param parsedVertexData defines the persisted data
  39426. * @param scene defines the hosting scene
  39427. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39428. * @returns the new geometry object
  39429. */
  39430. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39431. if (scene.getGeometryByID(parsedVertexData.id)) {
  39432. return null; // null since geometry could be something else than a box...
  39433. }
  39434. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39435. if (BABYLON.Tags) {
  39436. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39437. }
  39438. if (parsedVertexData.delayLoadingFile) {
  39439. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39440. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39441. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39442. geometry._delayInfo = [];
  39443. if (parsedVertexData.hasUVs) {
  39444. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39445. }
  39446. if (parsedVertexData.hasUVs2) {
  39447. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39448. }
  39449. if (parsedVertexData.hasUVs3) {
  39450. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39451. }
  39452. if (parsedVertexData.hasUVs4) {
  39453. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39454. }
  39455. if (parsedVertexData.hasUVs5) {
  39456. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39457. }
  39458. if (parsedVertexData.hasUVs6) {
  39459. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39460. }
  39461. if (parsedVertexData.hasColors) {
  39462. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39463. }
  39464. if (parsedVertexData.hasMatricesIndices) {
  39465. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39466. }
  39467. if (parsedVertexData.hasMatricesWeights) {
  39468. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39469. }
  39470. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39471. }
  39472. else {
  39473. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39474. }
  39475. scene.pushGeometry(geometry, true);
  39476. return geometry;
  39477. };
  39478. return Geometry;
  39479. }());
  39480. BABYLON.Geometry = Geometry;
  39481. // Primitives
  39482. /// Abstract class
  39483. /**
  39484. * Abstract class used to provide common services for all typed geometries
  39485. * @hidden
  39486. */
  39487. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39488. __extends(_PrimitiveGeometry, _super);
  39489. /**
  39490. * Creates a new typed geometry
  39491. * @param id defines the unique ID of the geometry
  39492. * @param scene defines the hosting scene
  39493. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39494. * @param mesh defines the hosting mesh (can be null)
  39495. */
  39496. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39497. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39498. if (mesh === void 0) { mesh = null; }
  39499. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39500. _this._canBeRegenerated = _canBeRegenerated;
  39501. _this._beingRegenerated = true;
  39502. _this.regenerate();
  39503. _this._beingRegenerated = false;
  39504. return _this;
  39505. }
  39506. /**
  39507. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39508. * @returns true if the geometry can be regenerated
  39509. */
  39510. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39511. return this._canBeRegenerated;
  39512. };
  39513. /**
  39514. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39515. */
  39516. _PrimitiveGeometry.prototype.regenerate = function () {
  39517. if (!this._canBeRegenerated) {
  39518. return;
  39519. }
  39520. this._beingRegenerated = true;
  39521. this.setAllVerticesData(this._regenerateVertexData(), false);
  39522. this._beingRegenerated = false;
  39523. };
  39524. /**
  39525. * Clone the geometry
  39526. * @param id defines the unique ID of the new geometry
  39527. * @returns the new geometry
  39528. */
  39529. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39530. return _super.prototype.copy.call(this, id);
  39531. };
  39532. // overrides
  39533. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39534. if (!this._beingRegenerated) {
  39535. return;
  39536. }
  39537. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39538. };
  39539. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39540. if (!this._beingRegenerated) {
  39541. return;
  39542. }
  39543. _super.prototype.setVerticesData.call(this, kind, data, false);
  39544. };
  39545. // to override
  39546. /** @hidden */
  39547. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39548. throw new Error("Abstract method");
  39549. };
  39550. _PrimitiveGeometry.prototype.copy = function (id) {
  39551. throw new Error("Must be overriden in sub-classes.");
  39552. };
  39553. _PrimitiveGeometry.prototype.serialize = function () {
  39554. var serializationObject = _super.prototype.serialize.call(this);
  39555. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39556. return serializationObject;
  39557. };
  39558. return _PrimitiveGeometry;
  39559. }(Geometry));
  39560. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39561. /**
  39562. * Creates a ribbon geometry
  39563. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39564. */
  39565. var RibbonGeometry = /** @class */ (function (_super) {
  39566. __extends(RibbonGeometry, _super);
  39567. /**
  39568. * Creates a ribbon geometry
  39569. * @param id defines the unique ID of the geometry
  39570. * @param scene defines the hosting scene
  39571. * @param pathArray defines the array of paths to use
  39572. * @param closeArray defines if the last path and the first path must be joined
  39573. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39574. * @param offset defines the offset between points
  39575. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39576. * @param mesh defines the hosting mesh (can be null)
  39577. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39578. */
  39579. function RibbonGeometry(id, scene,
  39580. /**
  39581. * Defines the array of paths to use
  39582. */
  39583. pathArray,
  39584. /**
  39585. * Defines if the last and first points of each path in your pathArray must be joined
  39586. */
  39587. closeArray,
  39588. /**
  39589. * Defines if the last and first points of each path in your pathArray must be joined
  39590. */
  39591. closePath,
  39592. /**
  39593. * Defines the offset between points
  39594. */
  39595. offset, canBeRegenerated, mesh,
  39596. /**
  39597. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39598. */
  39599. side) {
  39600. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39601. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39602. _this.pathArray = pathArray;
  39603. _this.closeArray = closeArray;
  39604. _this.closePath = closePath;
  39605. _this.offset = offset;
  39606. _this.side = side;
  39607. return _this;
  39608. }
  39609. /** @hidden */
  39610. RibbonGeometry.prototype._regenerateVertexData = function () {
  39611. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39612. };
  39613. RibbonGeometry.prototype.copy = function (id) {
  39614. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39615. };
  39616. return RibbonGeometry;
  39617. }(_PrimitiveGeometry));
  39618. BABYLON.RibbonGeometry = RibbonGeometry;
  39619. /**
  39620. * Creates a box geometry
  39621. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39622. */
  39623. var BoxGeometry = /** @class */ (function (_super) {
  39624. __extends(BoxGeometry, _super);
  39625. /**
  39626. * Creates a box geometry
  39627. * @param id defines the unique ID of the geometry
  39628. * @param scene defines the hosting scene
  39629. * @param size defines the zise of the box (width, height and depth are the same)
  39630. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39631. * @param mesh defines the hosting mesh (can be null)
  39632. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39633. */
  39634. function BoxGeometry(id, scene,
  39635. /**
  39636. * Defines the zise of the box (width, height and depth are the same)
  39637. */
  39638. size, canBeRegenerated, mesh,
  39639. /**
  39640. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39641. */
  39642. side) {
  39643. if (mesh === void 0) { mesh = null; }
  39644. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39645. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39646. _this.size = size;
  39647. _this.side = side;
  39648. return _this;
  39649. }
  39650. /** @hidden */
  39651. BoxGeometry.prototype._regenerateVertexData = function () {
  39652. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39653. };
  39654. BoxGeometry.prototype.copy = function (id) {
  39655. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39656. };
  39657. BoxGeometry.prototype.serialize = function () {
  39658. var serializationObject = _super.prototype.serialize.call(this);
  39659. serializationObject.size = this.size;
  39660. return serializationObject;
  39661. };
  39662. BoxGeometry.Parse = function (parsedBox, scene) {
  39663. if (scene.getGeometryByID(parsedBox.id)) {
  39664. return null; // null since geometry could be something else than a box...
  39665. }
  39666. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39667. if (BABYLON.Tags) {
  39668. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39669. }
  39670. scene.pushGeometry(box, true);
  39671. return box;
  39672. };
  39673. return BoxGeometry;
  39674. }(_PrimitiveGeometry));
  39675. BABYLON.BoxGeometry = BoxGeometry;
  39676. /**
  39677. * Creates a sphere geometry
  39678. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39679. */
  39680. var SphereGeometry = /** @class */ (function (_super) {
  39681. __extends(SphereGeometry, _super);
  39682. /**
  39683. * Create a new sphere geometry
  39684. * @param id defines the unique ID of the geometry
  39685. * @param scene defines the hosting scene
  39686. * @param segments defines the number of segments to use to create the sphere
  39687. * @param diameter defines the diameter of the sphere
  39688. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39689. * @param mesh defines the hosting mesh (can be null)
  39690. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39691. */
  39692. function SphereGeometry(id, scene,
  39693. /**
  39694. * Defines the number of segments to use to create the sphere
  39695. */
  39696. segments,
  39697. /**
  39698. * Defines the diameter of the sphere
  39699. */
  39700. diameter, canBeRegenerated, mesh,
  39701. /**
  39702. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39703. */
  39704. side) {
  39705. if (mesh === void 0) { mesh = null; }
  39706. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39707. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39708. _this.segments = segments;
  39709. _this.diameter = diameter;
  39710. _this.side = side;
  39711. return _this;
  39712. }
  39713. /** @hidden */
  39714. SphereGeometry.prototype._regenerateVertexData = function () {
  39715. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39716. };
  39717. SphereGeometry.prototype.copy = function (id) {
  39718. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39719. };
  39720. SphereGeometry.prototype.serialize = function () {
  39721. var serializationObject = _super.prototype.serialize.call(this);
  39722. serializationObject.segments = this.segments;
  39723. serializationObject.diameter = this.diameter;
  39724. return serializationObject;
  39725. };
  39726. SphereGeometry.Parse = function (parsedSphere, scene) {
  39727. if (scene.getGeometryByID(parsedSphere.id)) {
  39728. return null; // null since geometry could be something else than a sphere...
  39729. }
  39730. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39731. if (BABYLON.Tags) {
  39732. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39733. }
  39734. scene.pushGeometry(sphere, true);
  39735. return sphere;
  39736. };
  39737. return SphereGeometry;
  39738. }(_PrimitiveGeometry));
  39739. BABYLON.SphereGeometry = SphereGeometry;
  39740. /**
  39741. * Creates a disc geometry
  39742. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39743. */
  39744. var DiscGeometry = /** @class */ (function (_super) {
  39745. __extends(DiscGeometry, _super);
  39746. /**
  39747. * Creates a new disc geometry
  39748. * @param id defines the unique ID of the geometry
  39749. * @param scene defines the hosting scene
  39750. * @param radius defines the radius of the disc
  39751. * @param tessellation defines the tesselation factor to apply to the disc
  39752. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39753. * @param mesh defines the hosting mesh (can be null)
  39754. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39755. */
  39756. function DiscGeometry(id, scene,
  39757. /**
  39758. * Defines the radius of the disc
  39759. */
  39760. radius,
  39761. /**
  39762. * Defines the tesselation factor to apply to the disc
  39763. */
  39764. tessellation, canBeRegenerated, mesh,
  39765. /**
  39766. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39767. */
  39768. side) {
  39769. if (mesh === void 0) { mesh = null; }
  39770. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39771. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39772. _this.radius = radius;
  39773. _this.tessellation = tessellation;
  39774. _this.side = side;
  39775. return _this;
  39776. }
  39777. /** @hidden */
  39778. DiscGeometry.prototype._regenerateVertexData = function () {
  39779. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39780. };
  39781. DiscGeometry.prototype.copy = function (id) {
  39782. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39783. };
  39784. return DiscGeometry;
  39785. }(_PrimitiveGeometry));
  39786. BABYLON.DiscGeometry = DiscGeometry;
  39787. /**
  39788. * Creates a new cylinder geometry
  39789. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39790. */
  39791. var CylinderGeometry = /** @class */ (function (_super) {
  39792. __extends(CylinderGeometry, _super);
  39793. /**
  39794. * Creates a new cylinder geometry
  39795. * @param id defines the unique ID of the geometry
  39796. * @param scene defines the hosting scene
  39797. * @param height defines the height of the cylinder
  39798. * @param diameterTop defines the diameter of the cylinder's top cap
  39799. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39800. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39801. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39802. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39803. * @param mesh defines the hosting mesh (can be null)
  39804. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39805. */
  39806. function CylinderGeometry(id, scene,
  39807. /**
  39808. * Defines the height of the cylinder
  39809. */
  39810. height,
  39811. /**
  39812. * Defines the diameter of the cylinder's top cap
  39813. */
  39814. diameterTop,
  39815. /**
  39816. * Defines the diameter of the cylinder's bottom cap
  39817. */
  39818. diameterBottom,
  39819. /**
  39820. * Defines the tessellation factor to apply to the cylinder
  39821. */
  39822. tessellation,
  39823. /**
  39824. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39825. */
  39826. subdivisions, canBeRegenerated, mesh,
  39827. /**
  39828. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39829. */
  39830. side) {
  39831. if (subdivisions === void 0) { subdivisions = 1; }
  39832. if (mesh === void 0) { mesh = null; }
  39833. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39834. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39835. _this.height = height;
  39836. _this.diameterTop = diameterTop;
  39837. _this.diameterBottom = diameterBottom;
  39838. _this.tessellation = tessellation;
  39839. _this.subdivisions = subdivisions;
  39840. _this.side = side;
  39841. return _this;
  39842. }
  39843. /** @hidden */
  39844. CylinderGeometry.prototype._regenerateVertexData = function () {
  39845. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39846. };
  39847. CylinderGeometry.prototype.copy = function (id) {
  39848. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39849. };
  39850. CylinderGeometry.prototype.serialize = function () {
  39851. var serializationObject = _super.prototype.serialize.call(this);
  39852. serializationObject.height = this.height;
  39853. serializationObject.diameterTop = this.diameterTop;
  39854. serializationObject.diameterBottom = this.diameterBottom;
  39855. serializationObject.tessellation = this.tessellation;
  39856. return serializationObject;
  39857. };
  39858. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39859. if (scene.getGeometryByID(parsedCylinder.id)) {
  39860. return null; // null since geometry could be something else than a cylinder...
  39861. }
  39862. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39863. if (BABYLON.Tags) {
  39864. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39865. }
  39866. scene.pushGeometry(cylinder, true);
  39867. return cylinder;
  39868. };
  39869. return CylinderGeometry;
  39870. }(_PrimitiveGeometry));
  39871. BABYLON.CylinderGeometry = CylinderGeometry;
  39872. /**
  39873. * Creates a new torus geometry
  39874. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39875. */
  39876. var TorusGeometry = /** @class */ (function (_super) {
  39877. __extends(TorusGeometry, _super);
  39878. /**
  39879. * Creates a new torus geometry
  39880. * @param id defines the unique ID of the geometry
  39881. * @param scene defines the hosting scene
  39882. * @param diameter defines the diameter of the torus
  39883. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39884. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39885. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39886. * @param mesh defines the hosting mesh (can be null)
  39887. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39888. */
  39889. function TorusGeometry(id, scene,
  39890. /**
  39891. * Defines the diameter of the torus
  39892. */
  39893. diameter,
  39894. /**
  39895. * Defines the thickness of the torus (ie. internal diameter)
  39896. */
  39897. thickness,
  39898. /**
  39899. * Defines the tesselation factor to apply to the torus
  39900. */
  39901. tessellation, canBeRegenerated, mesh,
  39902. /**
  39903. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39904. */
  39905. side) {
  39906. if (mesh === void 0) { mesh = null; }
  39907. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39908. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39909. _this.diameter = diameter;
  39910. _this.thickness = thickness;
  39911. _this.tessellation = tessellation;
  39912. _this.side = side;
  39913. return _this;
  39914. }
  39915. /** @hidden */
  39916. TorusGeometry.prototype._regenerateVertexData = function () {
  39917. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39918. };
  39919. TorusGeometry.prototype.copy = function (id) {
  39920. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39921. };
  39922. TorusGeometry.prototype.serialize = function () {
  39923. var serializationObject = _super.prototype.serialize.call(this);
  39924. serializationObject.diameter = this.diameter;
  39925. serializationObject.thickness = this.thickness;
  39926. serializationObject.tessellation = this.tessellation;
  39927. return serializationObject;
  39928. };
  39929. TorusGeometry.Parse = function (parsedTorus, scene) {
  39930. if (scene.getGeometryByID(parsedTorus.id)) {
  39931. return null; // null since geometry could be something else than a torus...
  39932. }
  39933. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  39934. if (BABYLON.Tags) {
  39935. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  39936. }
  39937. scene.pushGeometry(torus, true);
  39938. return torus;
  39939. };
  39940. return TorusGeometry;
  39941. }(_PrimitiveGeometry));
  39942. BABYLON.TorusGeometry = TorusGeometry;
  39943. /**
  39944. * Creates a new ground geometry
  39945. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  39946. */
  39947. var GroundGeometry = /** @class */ (function (_super) {
  39948. __extends(GroundGeometry, _super);
  39949. /**
  39950. * Creates a new ground geometry
  39951. * @param id defines the unique ID of the geometry
  39952. * @param scene defines the hosting scene
  39953. * @param width defines the width of the ground
  39954. * @param height defines the height of the ground
  39955. * @param subdivisions defines the subdivisions to apply to the ground
  39956. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39957. * @param mesh defines the hosting mesh (can be null)
  39958. */
  39959. function GroundGeometry(id, scene,
  39960. /**
  39961. * Defines the width of the ground
  39962. */
  39963. width,
  39964. /**
  39965. * Defines the height of the ground
  39966. */
  39967. height,
  39968. /**
  39969. * Defines the subdivisions to apply to the ground
  39970. */
  39971. subdivisions, canBeRegenerated, mesh) {
  39972. if (mesh === void 0) { mesh = null; }
  39973. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39974. _this.width = width;
  39975. _this.height = height;
  39976. _this.subdivisions = subdivisions;
  39977. return _this;
  39978. }
  39979. /** @hidden */
  39980. GroundGeometry.prototype._regenerateVertexData = function () {
  39981. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  39982. };
  39983. GroundGeometry.prototype.copy = function (id) {
  39984. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  39985. };
  39986. GroundGeometry.prototype.serialize = function () {
  39987. var serializationObject = _super.prototype.serialize.call(this);
  39988. serializationObject.width = this.width;
  39989. serializationObject.height = this.height;
  39990. serializationObject.subdivisions = this.subdivisions;
  39991. return serializationObject;
  39992. };
  39993. GroundGeometry.Parse = function (parsedGround, scene) {
  39994. if (scene.getGeometryByID(parsedGround.id)) {
  39995. return null; // null since geometry could be something else than a ground...
  39996. }
  39997. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  39998. if (BABYLON.Tags) {
  39999. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40000. }
  40001. scene.pushGeometry(ground, true);
  40002. return ground;
  40003. };
  40004. return GroundGeometry;
  40005. }(_PrimitiveGeometry));
  40006. BABYLON.GroundGeometry = GroundGeometry;
  40007. /**
  40008. * Creates a tiled ground geometry
  40009. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40010. */
  40011. var TiledGroundGeometry = /** @class */ (function (_super) {
  40012. __extends(TiledGroundGeometry, _super);
  40013. /**
  40014. * Creates a tiled ground geometry
  40015. * @param id defines the unique ID of the geometry
  40016. * @param scene defines the hosting scene
  40017. * @param xmin defines the minimum value on X axis
  40018. * @param zmin defines the minimum value on Z axis
  40019. * @param xmax defines the maximum value on X axis
  40020. * @param zmax defines the maximum value on Z axis
  40021. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40022. * @param precision defines the precision to use when computing the tiles
  40023. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40024. * @param mesh defines the hosting mesh (can be null)
  40025. */
  40026. function TiledGroundGeometry(id, scene,
  40027. /**
  40028. * Defines the minimum value on X axis
  40029. */
  40030. xmin,
  40031. /**
  40032. * Defines the minimum value on Z axis
  40033. */
  40034. zmin,
  40035. /**
  40036. * Defines the maximum value on X axis
  40037. */
  40038. xmax,
  40039. /**
  40040. * Defines the maximum value on Z axis
  40041. */
  40042. zmax,
  40043. /**
  40044. * Defines the subdivisions to apply to the ground
  40045. */
  40046. subdivisions,
  40047. /**
  40048. * Defines the precision to use when computing the tiles
  40049. */
  40050. precision, canBeRegenerated, mesh) {
  40051. if (mesh === void 0) { mesh = null; }
  40052. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40053. _this.xmin = xmin;
  40054. _this.zmin = zmin;
  40055. _this.xmax = xmax;
  40056. _this.zmax = zmax;
  40057. _this.subdivisions = subdivisions;
  40058. _this.precision = precision;
  40059. return _this;
  40060. }
  40061. /** @hidden */
  40062. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40063. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40064. };
  40065. TiledGroundGeometry.prototype.copy = function (id) {
  40066. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40067. };
  40068. return TiledGroundGeometry;
  40069. }(_PrimitiveGeometry));
  40070. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40071. /**
  40072. * Creates a plane geometry
  40073. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40074. */
  40075. var PlaneGeometry = /** @class */ (function (_super) {
  40076. __extends(PlaneGeometry, _super);
  40077. /**
  40078. * Creates a plane geometry
  40079. * @param id defines the unique ID of the geometry
  40080. * @param scene defines the hosting scene
  40081. * @param size defines the size of the plane (width === height)
  40082. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40083. * @param mesh defines the hosting mesh (can be null)
  40084. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40085. */
  40086. function PlaneGeometry(id, scene,
  40087. /**
  40088. * Defines the size of the plane (width === height)
  40089. */
  40090. size, canBeRegenerated, mesh,
  40091. /**
  40092. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40093. */
  40094. side) {
  40095. if (mesh === void 0) { mesh = null; }
  40096. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40097. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40098. _this.size = size;
  40099. _this.side = side;
  40100. return _this;
  40101. }
  40102. /** @hidden */
  40103. PlaneGeometry.prototype._regenerateVertexData = function () {
  40104. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40105. };
  40106. PlaneGeometry.prototype.copy = function (id) {
  40107. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40108. };
  40109. PlaneGeometry.prototype.serialize = function () {
  40110. var serializationObject = _super.prototype.serialize.call(this);
  40111. serializationObject.size = this.size;
  40112. return serializationObject;
  40113. };
  40114. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40115. if (scene.getGeometryByID(parsedPlane.id)) {
  40116. return null; // null since geometry could be something else than a ground...
  40117. }
  40118. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40119. if (BABYLON.Tags) {
  40120. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40121. }
  40122. scene.pushGeometry(plane, true);
  40123. return plane;
  40124. };
  40125. return PlaneGeometry;
  40126. }(_PrimitiveGeometry));
  40127. BABYLON.PlaneGeometry = PlaneGeometry;
  40128. /**
  40129. * Creates a torus knot geometry
  40130. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40131. */
  40132. var TorusKnotGeometry = /** @class */ (function (_super) {
  40133. __extends(TorusKnotGeometry, _super);
  40134. /**
  40135. * Creates a torus knot geometry
  40136. * @param id defines the unique ID of the geometry
  40137. * @param scene defines the hosting scene
  40138. * @param radius defines the radius of the torus knot
  40139. * @param tube defines the thickness of the torus knot tube
  40140. * @param radialSegments defines the number of radial segments
  40141. * @param tubularSegments defines the number of tubular segments
  40142. * @param p defines the first number of windings
  40143. * @param q defines the second number of windings
  40144. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40145. * @param mesh defines the hosting mesh (can be null)
  40146. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40147. */
  40148. function TorusKnotGeometry(id, scene,
  40149. /**
  40150. * Defines the radius of the torus knot
  40151. */
  40152. radius,
  40153. /**
  40154. * Defines the thickness of the torus knot tube
  40155. */
  40156. tube,
  40157. /**
  40158. * Defines the number of radial segments
  40159. */
  40160. radialSegments,
  40161. /**
  40162. * Defines the number of tubular segments
  40163. */
  40164. tubularSegments,
  40165. /**
  40166. * Defines the first number of windings
  40167. */
  40168. p,
  40169. /**
  40170. * Defines the second number of windings
  40171. */
  40172. q, canBeRegenerated, mesh,
  40173. /**
  40174. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40175. */
  40176. side) {
  40177. if (mesh === void 0) { mesh = null; }
  40178. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40179. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40180. _this.radius = radius;
  40181. _this.tube = tube;
  40182. _this.radialSegments = radialSegments;
  40183. _this.tubularSegments = tubularSegments;
  40184. _this.p = p;
  40185. _this.q = q;
  40186. _this.side = side;
  40187. return _this;
  40188. }
  40189. /** @hidden */
  40190. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40191. 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 });
  40192. };
  40193. TorusKnotGeometry.prototype.copy = function (id) {
  40194. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40195. };
  40196. TorusKnotGeometry.prototype.serialize = function () {
  40197. var serializationObject = _super.prototype.serialize.call(this);
  40198. serializationObject.radius = this.radius;
  40199. serializationObject.tube = this.tube;
  40200. serializationObject.radialSegments = this.radialSegments;
  40201. serializationObject.tubularSegments = this.tubularSegments;
  40202. serializationObject.p = this.p;
  40203. serializationObject.q = this.q;
  40204. return serializationObject;
  40205. };
  40206. ;
  40207. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40208. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40209. return null; // null since geometry could be something else than a ground...
  40210. }
  40211. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40212. if (BABYLON.Tags) {
  40213. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40214. }
  40215. scene.pushGeometry(torusKnot, true);
  40216. return torusKnot;
  40217. };
  40218. return TorusKnotGeometry;
  40219. }(_PrimitiveGeometry));
  40220. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40221. //}
  40222. })(BABYLON || (BABYLON = {}));
  40223. //# sourceMappingURL=babylon.geometry.js.map
  40224. var BABYLON;
  40225. (function (BABYLON) {
  40226. /**
  40227. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40228. */
  40229. var PerformanceMonitor = /** @class */ (function () {
  40230. /**
  40231. * constructor
  40232. * @param frameSampleSize The number of samples required to saturate the sliding window
  40233. */
  40234. function PerformanceMonitor(frameSampleSize) {
  40235. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40236. this._enabled = true;
  40237. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40238. }
  40239. /**
  40240. * Samples current frame
  40241. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40242. */
  40243. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40244. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40245. if (!this._enabled)
  40246. return;
  40247. if (this._lastFrameTimeMs != null) {
  40248. var dt = timeMs - this._lastFrameTimeMs;
  40249. this._rollingFrameTime.add(dt);
  40250. }
  40251. this._lastFrameTimeMs = timeMs;
  40252. };
  40253. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40254. /**
  40255. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40256. * @return Average frame time in milliseconds
  40257. */
  40258. get: function () {
  40259. return this._rollingFrameTime.average;
  40260. },
  40261. enumerable: true,
  40262. configurable: true
  40263. });
  40264. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40265. /**
  40266. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40267. * @return Frame time variance in milliseconds squared
  40268. */
  40269. get: function () {
  40270. return this._rollingFrameTime.variance;
  40271. },
  40272. enumerable: true,
  40273. configurable: true
  40274. });
  40275. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40276. /**
  40277. * Returns the frame time of the most recent frame
  40278. * @return Frame time in milliseconds
  40279. */
  40280. get: function () {
  40281. return this._rollingFrameTime.history(0);
  40282. },
  40283. enumerable: true,
  40284. configurable: true
  40285. });
  40286. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40287. /**
  40288. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40289. * @return Framerate in frames per second
  40290. */
  40291. get: function () {
  40292. return 1000.0 / this._rollingFrameTime.average;
  40293. },
  40294. enumerable: true,
  40295. configurable: true
  40296. });
  40297. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40298. /**
  40299. * Returns the average framerate in frames per second using the most recent frame time
  40300. * @return Framerate in frames per second
  40301. */
  40302. get: function () {
  40303. var history = this._rollingFrameTime.history(0);
  40304. if (history === 0) {
  40305. return 0;
  40306. }
  40307. return 1000.0 / history;
  40308. },
  40309. enumerable: true,
  40310. configurable: true
  40311. });
  40312. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40313. /**
  40314. * Returns true if enough samples have been taken to completely fill the sliding window
  40315. * @return true if saturated
  40316. */
  40317. get: function () {
  40318. return this._rollingFrameTime.isSaturated();
  40319. },
  40320. enumerable: true,
  40321. configurable: true
  40322. });
  40323. /**
  40324. * Enables contributions to the sliding window sample set
  40325. */
  40326. PerformanceMonitor.prototype.enable = function () {
  40327. this._enabled = true;
  40328. };
  40329. /**
  40330. * Disables contributions to the sliding window sample set
  40331. * Samples will not be interpolated over the disabled period
  40332. */
  40333. PerformanceMonitor.prototype.disable = function () {
  40334. this._enabled = false;
  40335. //clear last sample to avoid interpolating over the disabled period when next enabled
  40336. this._lastFrameTimeMs = null;
  40337. };
  40338. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40339. /**
  40340. * Returns true if sampling is enabled
  40341. * @return true if enabled
  40342. */
  40343. get: function () {
  40344. return this._enabled;
  40345. },
  40346. enumerable: true,
  40347. configurable: true
  40348. });
  40349. /**
  40350. * Resets performance monitor
  40351. */
  40352. PerformanceMonitor.prototype.reset = function () {
  40353. //clear last sample to avoid interpolating over the disabled period when next enabled
  40354. this._lastFrameTimeMs = null;
  40355. //wipe record
  40356. this._rollingFrameTime.reset();
  40357. };
  40358. return PerformanceMonitor;
  40359. }());
  40360. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40361. /**
  40362. * RollingAverage
  40363. *
  40364. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40365. */
  40366. var RollingAverage = /** @class */ (function () {
  40367. /**
  40368. * constructor
  40369. * @param length The number of samples required to saturate the sliding window
  40370. */
  40371. function RollingAverage(length) {
  40372. this._samples = new Array(length);
  40373. this.reset();
  40374. }
  40375. /**
  40376. * Adds a sample to the sample set
  40377. * @param v The sample value
  40378. */
  40379. RollingAverage.prototype.add = function (v) {
  40380. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40381. var delta;
  40382. //we need to check if we've already wrapped round
  40383. if (this.isSaturated()) {
  40384. //remove bottom of stack from mean
  40385. var bottomValue = this._samples[this._pos];
  40386. delta = bottomValue - this.average;
  40387. this.average -= delta / (this._sampleCount - 1);
  40388. this._m2 -= delta * (bottomValue - this.average);
  40389. }
  40390. else {
  40391. this._sampleCount++;
  40392. }
  40393. //add new value to mean
  40394. delta = v - this.average;
  40395. this.average += delta / (this._sampleCount);
  40396. this._m2 += delta * (v - this.average);
  40397. //set the new variance
  40398. this.variance = this._m2 / (this._sampleCount - 1);
  40399. this._samples[this._pos] = v;
  40400. this._pos++;
  40401. this._pos %= this._samples.length; //positive wrap around
  40402. };
  40403. /**
  40404. * Returns previously added values or null if outside of history or outside the sliding window domain
  40405. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40406. * @return Value previously recorded with add() or null if outside of range
  40407. */
  40408. RollingAverage.prototype.history = function (i) {
  40409. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40410. return 0;
  40411. }
  40412. var i0 = this._wrapPosition(this._pos - 1.0);
  40413. return this._samples[this._wrapPosition(i0 - i)];
  40414. };
  40415. /**
  40416. * Returns true if enough samples have been taken to completely fill the sliding window
  40417. * @return true if sample-set saturated
  40418. */
  40419. RollingAverage.prototype.isSaturated = function () {
  40420. return this._sampleCount >= this._samples.length;
  40421. };
  40422. /**
  40423. * Resets the rolling average (equivalent to 0 samples taken so far)
  40424. */
  40425. RollingAverage.prototype.reset = function () {
  40426. this.average = 0;
  40427. this.variance = 0;
  40428. this._sampleCount = 0;
  40429. this._pos = 0;
  40430. this._m2 = 0;
  40431. };
  40432. /**
  40433. * Wraps a value around the sample range boundaries
  40434. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40435. * @return Wrapped position in sample range
  40436. */
  40437. RollingAverage.prototype._wrapPosition = function (i) {
  40438. var max = this._samples.length;
  40439. return ((i % max) + max) % max;
  40440. };
  40441. return RollingAverage;
  40442. }());
  40443. BABYLON.RollingAverage = RollingAverage;
  40444. })(BABYLON || (BABYLON = {}));
  40445. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40446. var BABYLON;
  40447. (function (BABYLON) {
  40448. /**
  40449. * "Static Class" containing the most commonly used helper while dealing with material for
  40450. * rendering purpose.
  40451. *
  40452. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40453. *
  40454. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40455. */
  40456. var MaterialHelper = /** @class */ (function () {
  40457. function MaterialHelper() {
  40458. }
  40459. /**
  40460. * Bind the current view position to an effect.
  40461. * @param effect The effect to be bound
  40462. * @param scene The scene the eyes position is used from
  40463. */
  40464. MaterialHelper.BindEyePosition = function (effect, scene) {
  40465. if (scene._forcedViewPosition) {
  40466. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40467. return;
  40468. }
  40469. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40470. };
  40471. /**
  40472. * Helps preparing the defines values about the UVs in used in the effect.
  40473. * UVs are shared as much as we can accross chanels in the shaders.
  40474. * @param texture The texture we are preparing the UVs for
  40475. * @param defines The defines to update
  40476. * @param key The chanel key "diffuse", "specular"... used in the shader
  40477. */
  40478. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40479. defines._needUVs = true;
  40480. defines[key] = true;
  40481. if (texture.getTextureMatrix().isIdentity(true)) {
  40482. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40483. if (texture.coordinatesIndex === 0) {
  40484. defines["MAINUV1"] = true;
  40485. }
  40486. else {
  40487. defines["MAINUV2"] = true;
  40488. }
  40489. }
  40490. else {
  40491. defines[key + "DIRECTUV"] = 0;
  40492. }
  40493. };
  40494. /**
  40495. * Binds a texture matrix value to its corrsponding uniform
  40496. * @param texture The texture to bind the matrix for
  40497. * @param uniformBuffer The uniform buffer receivin the data
  40498. * @param key The chanel key "diffuse", "specular"... used in the shader
  40499. */
  40500. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40501. var matrix = texture.getTextureMatrix();
  40502. if (!matrix.isIdentity(true)) {
  40503. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40504. }
  40505. };
  40506. /**
  40507. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40508. * @param mesh defines the current mesh
  40509. * @param scene defines the current scene
  40510. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40511. * @param pointsCloud defines if point cloud rendering has to be turned on
  40512. * @param fogEnabled defines if fog has to be turned on
  40513. * @param alphaTest defines if alpha testing has to be turned on
  40514. * @param defines defines the current list of defines
  40515. */
  40516. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40517. if (defines._areMiscDirty) {
  40518. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40519. defines["POINTSIZE"] = pointsCloud;
  40520. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40521. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40522. defines["ALPHATEST"] = alphaTest;
  40523. }
  40524. };
  40525. /**
  40526. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40527. * @param scene defines the current scene
  40528. * @param engine defines the current engine
  40529. * @param defines specifies the list of active defines
  40530. * @param useInstances defines if instances have to be turned on
  40531. * @param useClipPlane defines if clip plane have to be turned on
  40532. */
  40533. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40534. if (useClipPlane === void 0) { useClipPlane = null; }
  40535. var changed = false;
  40536. var useClipPlane1 = false;
  40537. var useClipPlane2 = false;
  40538. var useClipPlane3 = false;
  40539. var useClipPlane4 = false;
  40540. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  40541. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  40542. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  40543. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  40544. if (defines["CLIPPLANE"] !== useClipPlane1) {
  40545. defines["CLIPPLANE"] = useClipPlane1;
  40546. changed = true;
  40547. }
  40548. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  40549. defines["CLIPPLANE2"] = useClipPlane2;
  40550. changed = true;
  40551. }
  40552. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  40553. defines["CLIPPLANE3"] = useClipPlane3;
  40554. changed = true;
  40555. }
  40556. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  40557. defines["CLIPPLANE4"] = useClipPlane4;
  40558. changed = true;
  40559. }
  40560. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40561. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40562. changed = true;
  40563. }
  40564. if (defines["INSTANCES"] !== useInstances) {
  40565. defines["INSTANCES"] = useInstances;
  40566. changed = true;
  40567. }
  40568. if (changed) {
  40569. defines.markAsUnprocessed();
  40570. }
  40571. };
  40572. /**
  40573. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40574. * @param mesh The mesh containing the geometry data we will draw
  40575. * @param defines The defines to update
  40576. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40577. * @param useBones Precise whether bones should be used or not (override mesh info)
  40578. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40579. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40580. * @returns false if defines are considered not dirty and have not been checked
  40581. */
  40582. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40583. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40584. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40585. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40586. return false;
  40587. }
  40588. defines._normals = defines._needNormals;
  40589. defines._uvs = defines._needUVs;
  40590. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40591. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40592. defines["TANGENT"] = true;
  40593. }
  40594. if (defines._needUVs) {
  40595. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40596. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40597. }
  40598. else {
  40599. defines["UV1"] = false;
  40600. defines["UV2"] = false;
  40601. }
  40602. if (useVertexColor) {
  40603. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40604. defines["VERTEXCOLOR"] = hasVertexColors;
  40605. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40606. }
  40607. if (useBones) {
  40608. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40609. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40610. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40611. }
  40612. else {
  40613. defines["NUM_BONE_INFLUENCERS"] = 0;
  40614. defines["BonesPerMesh"] = 0;
  40615. }
  40616. }
  40617. if (useMorphTargets) {
  40618. var manager = mesh.morphTargetManager;
  40619. if (manager) {
  40620. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40621. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40622. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40623. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40624. }
  40625. else {
  40626. defines["MORPHTARGETS_TANGENT"] = false;
  40627. defines["MORPHTARGETS_NORMAL"] = false;
  40628. defines["MORPHTARGETS"] = false;
  40629. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40630. }
  40631. }
  40632. return true;
  40633. };
  40634. /**
  40635. * Prepares the defines related to the light information passed in parameter
  40636. * @param scene The scene we are intending to draw
  40637. * @param mesh The mesh the effect is compiling for
  40638. * @param defines The defines to update
  40639. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40640. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40641. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40642. * @returns true if normals will be required for the rest of the effect
  40643. */
  40644. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40645. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40646. if (disableLighting === void 0) { disableLighting = false; }
  40647. if (!defines._areLightsDirty) {
  40648. return defines._needNormals;
  40649. }
  40650. var lightIndex = 0;
  40651. var needNormals = false;
  40652. var needRebuild = false;
  40653. var lightmapMode = false;
  40654. var shadowEnabled = false;
  40655. var specularEnabled = false;
  40656. if (scene.lightsEnabled && !disableLighting) {
  40657. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40658. var light = _a[_i];
  40659. needNormals = true;
  40660. if (defines["LIGHT" + lightIndex] === undefined) {
  40661. needRebuild = true;
  40662. }
  40663. defines["LIGHT" + lightIndex] = true;
  40664. defines["SPOTLIGHT" + lightIndex] = false;
  40665. defines["HEMILIGHT" + lightIndex] = false;
  40666. defines["POINTLIGHT" + lightIndex] = false;
  40667. defines["DIRLIGHT" + lightIndex] = false;
  40668. light.prepareLightSpecificDefines(defines, lightIndex);
  40669. // FallOff.
  40670. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  40671. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  40672. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  40673. switch (light.falloffType) {
  40674. case BABYLON.Light.FALLOFF_GLTF:
  40675. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  40676. break;
  40677. case BABYLON.Light.FALLOFF_PHYSICAL:
  40678. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  40679. break;
  40680. case BABYLON.Light.FALLOFF_STANDARD:
  40681. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  40682. break;
  40683. }
  40684. // Specular
  40685. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40686. specularEnabled = true;
  40687. }
  40688. // Shadows
  40689. defines["SHADOW" + lightIndex] = false;
  40690. defines["SHADOWPCF" + lightIndex] = false;
  40691. defines["SHADOWPCSS" + lightIndex] = false;
  40692. defines["SHADOWPOISSON" + lightIndex] = false;
  40693. defines["SHADOWESM" + lightIndex] = false;
  40694. defines["SHADOWCUBE" + lightIndex] = false;
  40695. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40696. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40697. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40698. var shadowGenerator = light.getShadowGenerator();
  40699. if (shadowGenerator) {
  40700. var shadowMap = shadowGenerator.getShadowMap();
  40701. if (shadowMap) {
  40702. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40703. shadowEnabled = true;
  40704. shadowGenerator.prepareDefines(defines, lightIndex);
  40705. }
  40706. }
  40707. }
  40708. }
  40709. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40710. lightmapMode = true;
  40711. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40712. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40713. }
  40714. else {
  40715. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40716. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40717. }
  40718. lightIndex++;
  40719. if (lightIndex === maxSimultaneousLights)
  40720. break;
  40721. }
  40722. }
  40723. defines["SPECULARTERM"] = specularEnabled;
  40724. defines["SHADOWS"] = shadowEnabled;
  40725. // Resetting all other lights if any
  40726. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  40727. if (defines["LIGHT" + index] !== undefined) {
  40728. defines["LIGHT" + index] = false;
  40729. defines["HEMILIGHT" + lightIndex] = false;
  40730. defines["POINTLIGHT" + lightIndex] = false;
  40731. defines["DIRLIGHT" + lightIndex] = false;
  40732. defines["SPOTLIGHT" + lightIndex] = false;
  40733. defines["SHADOW" + lightIndex] = false;
  40734. }
  40735. }
  40736. var caps = scene.getEngine().getCaps();
  40737. if (defines["SHADOWFLOAT"] === undefined) {
  40738. needRebuild = true;
  40739. }
  40740. defines["SHADOWFLOAT"] = shadowEnabled &&
  40741. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  40742. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  40743. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  40744. if (needRebuild) {
  40745. defines.rebuild();
  40746. }
  40747. return needNormals;
  40748. };
  40749. /**
  40750. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  40751. * that won t be acctive due to defines being turned off.
  40752. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  40753. * @param samplersList The samplers list
  40754. * @param defines The defines helping in the list generation
  40755. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  40756. */
  40757. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  40758. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40759. var uniformsList;
  40760. var uniformBuffersList = null;
  40761. if (uniformsListOrOptions.uniformsNames) {
  40762. var options = uniformsListOrOptions;
  40763. uniformsList = options.uniformsNames;
  40764. uniformBuffersList = options.uniformBuffersNames;
  40765. samplersList = options.samplers;
  40766. defines = options.defines;
  40767. maxSimultaneousLights = options.maxSimultaneousLights;
  40768. }
  40769. else {
  40770. uniformsList = uniformsListOrOptions;
  40771. if (!samplersList) {
  40772. samplersList = [];
  40773. }
  40774. }
  40775. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40776. if (!defines["LIGHT" + lightIndex]) {
  40777. break;
  40778. }
  40779. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  40780. if (uniformBuffersList) {
  40781. uniformBuffersList.push("Light" + lightIndex);
  40782. }
  40783. samplersList.push("shadowSampler" + lightIndex);
  40784. samplersList.push("depthSampler" + lightIndex);
  40785. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  40786. samplersList.push("projectionLightSampler" + lightIndex);
  40787. uniformsList.push("textureProjectionMatrix" + lightIndex);
  40788. }
  40789. }
  40790. if (defines["NUM_MORPH_INFLUENCERS"]) {
  40791. uniformsList.push("morphTargetInfluences");
  40792. }
  40793. };
  40794. /**
  40795. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  40796. * @param defines The defines to update while falling back
  40797. * @param fallbacks The authorized effect fallbacks
  40798. * @param maxSimultaneousLights The maximum number of lights allowed
  40799. * @param rank the current rank of the Effect
  40800. * @returns The newly affected rank
  40801. */
  40802. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  40803. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40804. if (rank === void 0) { rank = 0; }
  40805. var lightFallbackRank = 0;
  40806. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40807. if (!defines["LIGHT" + lightIndex]) {
  40808. break;
  40809. }
  40810. if (lightIndex > 0) {
  40811. lightFallbackRank = rank + lightIndex;
  40812. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  40813. }
  40814. if (!defines["SHADOWS"]) {
  40815. if (defines["SHADOW" + lightIndex]) {
  40816. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  40817. }
  40818. if (defines["SHADOWPCF" + lightIndex]) {
  40819. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  40820. }
  40821. if (defines["SHADOWPCSS" + lightIndex]) {
  40822. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  40823. }
  40824. if (defines["SHADOWPOISSON" + lightIndex]) {
  40825. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  40826. }
  40827. if (defines["SHADOWESM" + lightIndex]) {
  40828. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  40829. }
  40830. }
  40831. }
  40832. return lightFallbackRank++;
  40833. };
  40834. /**
  40835. * Prepares the list of attributes required for morph targets according to the effect defines.
  40836. * @param attribs The current list of supported attribs
  40837. * @param mesh The mesh to prepare the morph targets attributes for
  40838. * @param defines The current Defines of the effect
  40839. */
  40840. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  40841. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  40842. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  40843. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  40844. var manager = mesh.morphTargetManager;
  40845. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  40846. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  40847. for (var index = 0; index < influencers; index++) {
  40848. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  40849. if (normal) {
  40850. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  40851. }
  40852. if (tangent) {
  40853. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  40854. }
  40855. if (attribs.length > maxAttributesCount) {
  40856. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  40857. }
  40858. }
  40859. }
  40860. };
  40861. /**
  40862. * Prepares the list of attributes required for bones according to the effect defines.
  40863. * @param attribs The current list of supported attribs
  40864. * @param mesh The mesh to prepare the bones attributes for
  40865. * @param defines The current Defines of the effect
  40866. * @param fallbacks The current efffect fallback strategy
  40867. */
  40868. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  40869. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  40870. fallbacks.addCPUSkinningFallback(0, mesh);
  40871. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40872. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40873. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  40874. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40875. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  40876. }
  40877. }
  40878. };
  40879. /**
  40880. * Prepares the list of attributes required for instances according to the effect defines.
  40881. * @param attribs The current list of supported attribs
  40882. * @param defines The current Defines of the effect
  40883. */
  40884. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  40885. if (defines["INSTANCES"]) {
  40886. attribs.push("world0");
  40887. attribs.push("world1");
  40888. attribs.push("world2");
  40889. attribs.push("world3");
  40890. }
  40891. };
  40892. /**
  40893. * Binds the light shadow information to the effect for the given mesh.
  40894. * @param light The light containing the generator
  40895. * @param scene The scene the lights belongs to
  40896. * @param mesh The mesh we are binding the information to render
  40897. * @param lightIndex The light index in the effect used to render the mesh
  40898. * @param effect The effect we are binding the data to
  40899. */
  40900. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  40901. if (light.shadowEnabled && mesh.receiveShadows) {
  40902. var shadowGenerator = light.getShadowGenerator();
  40903. if (shadowGenerator) {
  40904. shadowGenerator.bindShadowLight(lightIndex, effect);
  40905. }
  40906. }
  40907. };
  40908. /**
  40909. * Binds the light information to the effect.
  40910. * @param light The light containing the generator
  40911. * @param effect The effect we are binding the data to
  40912. * @param lightIndex The light index in the effect used to render
  40913. */
  40914. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  40915. light.transferToEffect(effect, lightIndex + "");
  40916. };
  40917. /**
  40918. * Binds the lights information from the scene to the effect for the given mesh.
  40919. * @param scene The scene the lights belongs to
  40920. * @param mesh The mesh we are binding the information to render
  40921. * @param effect The effect we are binding the data to
  40922. * @param defines The generated defines for the effect
  40923. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  40924. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  40925. */
  40926. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  40927. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40928. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  40929. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  40930. for (var i = 0; i < len; i++) {
  40931. var light = mesh._lightSources[i];
  40932. var iAsString = i.toString();
  40933. var scaledIntensity = light.getScaledIntensity();
  40934. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  40935. MaterialHelper.BindLightProperties(light, effect, i);
  40936. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  40937. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  40938. if (defines["SPECULARTERM"]) {
  40939. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  40940. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  40941. }
  40942. // Shadows
  40943. if (scene.shadowsEnabled) {
  40944. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  40945. }
  40946. light._uniformBuffer.update();
  40947. }
  40948. };
  40949. /**
  40950. * Binds the fog information from the scene to the effect for the given mesh.
  40951. * @param scene The scene the lights belongs to
  40952. * @param mesh The mesh we are binding the information to render
  40953. * @param effect The effect we are binding the data to
  40954. */
  40955. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  40956. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  40957. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  40958. effect.setColor3("vFogColor", scene.fogColor);
  40959. }
  40960. };
  40961. /**
  40962. * Binds the bones information from the mesh to the effect.
  40963. * @param mesh The mesh we are binding the information to render
  40964. * @param effect The effect we are binding the data to
  40965. */
  40966. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  40967. if (!effect || !mesh) {
  40968. return;
  40969. }
  40970. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  40971. mesh.computeBonesUsingShaders = false;
  40972. }
  40973. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40974. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  40975. if (matrices) {
  40976. effect.setMatrices("mBones", matrices);
  40977. }
  40978. }
  40979. };
  40980. /**
  40981. * Binds the morph targets information from the mesh to the effect.
  40982. * @param abstractMesh The mesh we are binding the information to render
  40983. * @param effect The effect we are binding the data to
  40984. */
  40985. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  40986. var manager = abstractMesh.morphTargetManager;
  40987. if (!abstractMesh || !manager) {
  40988. return;
  40989. }
  40990. effect.setFloatArray("morphTargetInfluences", manager.influences);
  40991. };
  40992. /**
  40993. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  40994. * @param defines The generated defines used in the effect
  40995. * @param effect The effect we are binding the data to
  40996. * @param scene The scene we are willing to render with logarithmic scale for
  40997. */
  40998. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  40999. if (defines["LOGARITHMICDEPTH"]) {
  41000. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41001. }
  41002. };
  41003. /**
  41004. * Binds the clip plane information from the scene to the effect.
  41005. * @param scene The scene the clip plane information are extracted from
  41006. * @param effect The effect we are binding the data to
  41007. */
  41008. MaterialHelper.BindClipPlane = function (effect, scene) {
  41009. if (scene.clipPlane) {
  41010. var clipPlane = scene.clipPlane;
  41011. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41012. }
  41013. if (scene.clipPlane2) {
  41014. var clipPlane = scene.clipPlane2;
  41015. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41016. }
  41017. if (scene.clipPlane3) {
  41018. var clipPlane = scene.clipPlane3;
  41019. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41020. }
  41021. if (scene.clipPlane4) {
  41022. var clipPlane = scene.clipPlane4;
  41023. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41024. }
  41025. };
  41026. return MaterialHelper;
  41027. }());
  41028. BABYLON.MaterialHelper = MaterialHelper;
  41029. })(BABYLON || (BABYLON = {}));
  41030. //# sourceMappingURL=babylon.materialHelper.js.map
  41031. var BABYLON;
  41032. (function (BABYLON) {
  41033. var PushMaterial = /** @class */ (function (_super) {
  41034. __extends(PushMaterial, _super);
  41035. function PushMaterial(name, scene) {
  41036. var _this = _super.call(this, name, scene) || this;
  41037. _this._normalMatrix = new BABYLON.Matrix();
  41038. _this.storeEffectOnSubMeshes = true;
  41039. return _this;
  41040. }
  41041. PushMaterial.prototype.getEffect = function () {
  41042. return this._activeEffect;
  41043. };
  41044. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41045. if (!mesh) {
  41046. return false;
  41047. }
  41048. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41049. return true;
  41050. }
  41051. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41052. };
  41053. /**
  41054. * Binds the given world matrix to the active effect
  41055. *
  41056. * @param world the matrix to bind
  41057. */
  41058. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41059. this._activeEffect.setMatrix("world", world);
  41060. };
  41061. /**
  41062. * Binds the given normal matrix to the active effect
  41063. *
  41064. * @param normalMatrix the matrix to bind
  41065. */
  41066. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41067. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41068. };
  41069. PushMaterial.prototype.bind = function (world, mesh) {
  41070. if (!mesh) {
  41071. return;
  41072. }
  41073. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41074. };
  41075. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41076. if (effect === void 0) { effect = null; }
  41077. _super.prototype._afterBind.call(this, mesh);
  41078. this.getScene()._cachedEffect = effect;
  41079. };
  41080. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41081. if (visibility === void 0) { visibility = 1; }
  41082. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41083. };
  41084. return PushMaterial;
  41085. }(BABYLON.Material));
  41086. BABYLON.PushMaterial = PushMaterial;
  41087. })(BABYLON || (BABYLON = {}));
  41088. //# sourceMappingURL=babylon.pushMaterial.js.map
  41089. var BABYLON;
  41090. (function (BABYLON) {
  41091. /** @hidden */
  41092. var StandardMaterialDefines = /** @class */ (function (_super) {
  41093. __extends(StandardMaterialDefines, _super);
  41094. function StandardMaterialDefines() {
  41095. var _this = _super.call(this) || this;
  41096. _this.MAINUV1 = false;
  41097. _this.MAINUV2 = false;
  41098. _this.DIFFUSE = false;
  41099. _this.DIFFUSEDIRECTUV = 0;
  41100. _this.AMBIENT = false;
  41101. _this.AMBIENTDIRECTUV = 0;
  41102. _this.OPACITY = false;
  41103. _this.OPACITYDIRECTUV = 0;
  41104. _this.OPACITYRGB = false;
  41105. _this.REFLECTION = false;
  41106. _this.EMISSIVE = false;
  41107. _this.EMISSIVEDIRECTUV = 0;
  41108. _this.SPECULAR = false;
  41109. _this.SPECULARDIRECTUV = 0;
  41110. _this.BUMP = false;
  41111. _this.BUMPDIRECTUV = 0;
  41112. _this.PARALLAX = false;
  41113. _this.PARALLAXOCCLUSION = false;
  41114. _this.SPECULAROVERALPHA = false;
  41115. _this.CLIPPLANE = false;
  41116. _this.CLIPPLANE2 = false;
  41117. _this.CLIPPLANE3 = false;
  41118. _this.CLIPPLANE4 = false;
  41119. _this.ALPHATEST = false;
  41120. _this.DEPTHPREPASS = false;
  41121. _this.ALPHAFROMDIFFUSE = false;
  41122. _this.POINTSIZE = false;
  41123. _this.FOG = false;
  41124. _this.SPECULARTERM = false;
  41125. _this.DIFFUSEFRESNEL = false;
  41126. _this.OPACITYFRESNEL = false;
  41127. _this.REFLECTIONFRESNEL = false;
  41128. _this.REFRACTIONFRESNEL = false;
  41129. _this.EMISSIVEFRESNEL = false;
  41130. _this.FRESNEL = false;
  41131. _this.NORMAL = false;
  41132. _this.UV1 = false;
  41133. _this.UV2 = false;
  41134. _this.VERTEXCOLOR = false;
  41135. _this.VERTEXALPHA = false;
  41136. _this.NUM_BONE_INFLUENCERS = 0;
  41137. _this.BonesPerMesh = 0;
  41138. _this.INSTANCES = false;
  41139. _this.GLOSSINESS = false;
  41140. _this.ROUGHNESS = false;
  41141. _this.EMISSIVEASILLUMINATION = false;
  41142. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41143. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41144. _this.LIGHTMAP = false;
  41145. _this.LIGHTMAPDIRECTUV = 0;
  41146. _this.OBJECTSPACE_NORMALMAP = false;
  41147. _this.USELIGHTMAPASSHADOWMAP = false;
  41148. _this.REFLECTIONMAP_3D = false;
  41149. _this.REFLECTIONMAP_SPHERICAL = false;
  41150. _this.REFLECTIONMAP_PLANAR = false;
  41151. _this.REFLECTIONMAP_CUBIC = false;
  41152. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41153. _this.REFLECTIONMAP_PROJECTION = false;
  41154. _this.REFLECTIONMAP_SKYBOX = false;
  41155. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41156. _this.REFLECTIONMAP_EXPLICIT = false;
  41157. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41158. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41159. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41160. _this.INVERTCUBICMAP = false;
  41161. _this.LOGARITHMICDEPTH = false;
  41162. _this.REFRACTION = false;
  41163. _this.REFRACTIONMAP_3D = false;
  41164. _this.REFLECTIONOVERALPHA = false;
  41165. _this.TWOSIDEDLIGHTING = false;
  41166. _this.SHADOWFLOAT = false;
  41167. _this.MORPHTARGETS = false;
  41168. _this.MORPHTARGETS_NORMAL = false;
  41169. _this.MORPHTARGETS_TANGENT = false;
  41170. _this.NUM_MORPH_INFLUENCERS = 0;
  41171. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41172. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41173. _this.IMAGEPROCESSING = false;
  41174. _this.VIGNETTE = false;
  41175. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41176. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41177. _this.TONEMAPPING = false;
  41178. _this.TONEMAPPING_ACES = false;
  41179. _this.CONTRAST = false;
  41180. _this.COLORCURVES = false;
  41181. _this.COLORGRADING = false;
  41182. _this.COLORGRADING3D = false;
  41183. _this.SAMPLER3DGREENDEPTH = false;
  41184. _this.SAMPLER3DBGRMAP = false;
  41185. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41186. /**
  41187. * If the reflection texture on this material is in linear color space
  41188. * @hidden
  41189. */
  41190. _this.IS_REFLECTION_LINEAR = false;
  41191. /**
  41192. * If the refraction texture on this material is in linear color space
  41193. * @hidden
  41194. */
  41195. _this.IS_REFRACTION_LINEAR = false;
  41196. _this.EXPOSURE = false;
  41197. _this.rebuild();
  41198. return _this;
  41199. }
  41200. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41201. var modes = [
  41202. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41203. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41204. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41205. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41206. ];
  41207. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41208. var mode = modes_1[_i];
  41209. this[mode] = (mode === modeToEnable);
  41210. }
  41211. };
  41212. return StandardMaterialDefines;
  41213. }(BABYLON.MaterialDefines));
  41214. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41215. var StandardMaterial = /** @class */ (function (_super) {
  41216. __extends(StandardMaterial, _super);
  41217. function StandardMaterial(name, scene) {
  41218. var _this = _super.call(this, name, scene) || this;
  41219. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41220. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41221. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41222. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41223. _this.specularPower = 64;
  41224. _this._useAlphaFromDiffuseTexture = false;
  41225. _this._useEmissiveAsIllumination = false;
  41226. _this._linkEmissiveWithDiffuse = false;
  41227. _this._useSpecularOverAlpha = false;
  41228. _this._useReflectionOverAlpha = false;
  41229. _this._disableLighting = false;
  41230. _this._useObjectSpaceNormalMap = false;
  41231. _this._useParallax = false;
  41232. _this._useParallaxOcclusion = false;
  41233. _this.parallaxScaleBias = 0.05;
  41234. _this._roughness = 0;
  41235. _this.indexOfRefraction = 0.98;
  41236. _this.invertRefractionY = true;
  41237. /**
  41238. * Defines the alpha limits in alpha test mode
  41239. */
  41240. _this.alphaCutOff = 0.4;
  41241. _this._useLightmapAsShadowmap = false;
  41242. _this._useReflectionFresnelFromSpecular = false;
  41243. _this._useGlossinessFromSpecularMapAlpha = false;
  41244. _this._maxSimultaneousLights = 4;
  41245. /**
  41246. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41247. */
  41248. _this._invertNormalMapX = false;
  41249. /**
  41250. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41251. */
  41252. _this._invertNormalMapY = false;
  41253. /**
  41254. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41255. */
  41256. _this._twoSidedLighting = false;
  41257. _this._renderTargets = new BABYLON.SmartArray(16);
  41258. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41259. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41260. // Setup the default processing configuration to the scene.
  41261. _this._attachImageProcessingConfiguration(null);
  41262. _this.getRenderTargetTextures = function () {
  41263. _this._renderTargets.reset();
  41264. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41265. _this._renderTargets.push(_this._reflectionTexture);
  41266. }
  41267. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41268. _this._renderTargets.push(_this._refractionTexture);
  41269. }
  41270. return _this._renderTargets;
  41271. };
  41272. return _this;
  41273. }
  41274. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41275. /**
  41276. * Gets the image processing configuration used either in this material.
  41277. */
  41278. get: function () {
  41279. return this._imageProcessingConfiguration;
  41280. },
  41281. /**
  41282. * Sets the Default image processing configuration used either in the this material.
  41283. *
  41284. * If sets to null, the scene one is in use.
  41285. */
  41286. set: function (value) {
  41287. this._attachImageProcessingConfiguration(value);
  41288. // Ensure the effect will be rebuilt.
  41289. this._markAllSubMeshesAsTexturesDirty();
  41290. },
  41291. enumerable: true,
  41292. configurable: true
  41293. });
  41294. /**
  41295. * Attaches a new image processing configuration to the Standard Material.
  41296. * @param configuration
  41297. */
  41298. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41299. var _this = this;
  41300. if (configuration === this._imageProcessingConfiguration) {
  41301. return;
  41302. }
  41303. // Detaches observer.
  41304. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41305. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41306. }
  41307. // Pick the scene configuration if needed.
  41308. if (!configuration) {
  41309. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41310. }
  41311. else {
  41312. this._imageProcessingConfiguration = configuration;
  41313. }
  41314. // Attaches observer.
  41315. if (this._imageProcessingConfiguration) {
  41316. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41317. _this._markAllSubMeshesAsImageProcessingDirty();
  41318. });
  41319. }
  41320. };
  41321. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41322. /**
  41323. * Gets wether the color curves effect is enabled.
  41324. */
  41325. get: function () {
  41326. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41327. },
  41328. /**
  41329. * Sets wether the color curves effect is enabled.
  41330. */
  41331. set: function (value) {
  41332. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41333. },
  41334. enumerable: true,
  41335. configurable: true
  41336. });
  41337. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41338. /**
  41339. * Gets wether the color grading effect is enabled.
  41340. */
  41341. get: function () {
  41342. return this.imageProcessingConfiguration.colorGradingEnabled;
  41343. },
  41344. /**
  41345. * Gets wether the color grading effect is enabled.
  41346. */
  41347. set: function (value) {
  41348. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41349. },
  41350. enumerable: true,
  41351. configurable: true
  41352. });
  41353. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41354. /**
  41355. * Gets wether tonemapping is enabled or not.
  41356. */
  41357. get: function () {
  41358. return this._imageProcessingConfiguration.toneMappingEnabled;
  41359. },
  41360. /**
  41361. * Sets wether tonemapping is enabled or not
  41362. */
  41363. set: function (value) {
  41364. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41365. },
  41366. enumerable: true,
  41367. configurable: true
  41368. });
  41369. ;
  41370. ;
  41371. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41372. /**
  41373. * The camera exposure used on this material.
  41374. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41375. * This corresponds to a photographic exposure.
  41376. */
  41377. get: function () {
  41378. return this._imageProcessingConfiguration.exposure;
  41379. },
  41380. /**
  41381. * The camera exposure used on this material.
  41382. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41383. * This corresponds to a photographic exposure.
  41384. */
  41385. set: function (value) {
  41386. this._imageProcessingConfiguration.exposure = value;
  41387. },
  41388. enumerable: true,
  41389. configurable: true
  41390. });
  41391. ;
  41392. ;
  41393. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41394. /**
  41395. * Gets The camera contrast used on this material.
  41396. */
  41397. get: function () {
  41398. return this._imageProcessingConfiguration.contrast;
  41399. },
  41400. /**
  41401. * Sets The camera contrast used on this material.
  41402. */
  41403. set: function (value) {
  41404. this._imageProcessingConfiguration.contrast = value;
  41405. },
  41406. enumerable: true,
  41407. configurable: true
  41408. });
  41409. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41410. /**
  41411. * Gets the Color Grading 2D Lookup Texture.
  41412. */
  41413. get: function () {
  41414. return this._imageProcessingConfiguration.colorGradingTexture;
  41415. },
  41416. /**
  41417. * Sets the Color Grading 2D Lookup Texture.
  41418. */
  41419. set: function (value) {
  41420. this._imageProcessingConfiguration.colorGradingTexture = value;
  41421. },
  41422. enumerable: true,
  41423. configurable: true
  41424. });
  41425. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41426. /**
  41427. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41428. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41429. * 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;
  41430. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41431. */
  41432. get: function () {
  41433. return this._imageProcessingConfiguration.colorCurves;
  41434. },
  41435. /**
  41436. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41437. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41438. * 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;
  41439. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41440. */
  41441. set: function (value) {
  41442. this._imageProcessingConfiguration.colorCurves = value;
  41443. },
  41444. enumerable: true,
  41445. configurable: true
  41446. });
  41447. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  41448. /**
  41449. * Gets a boolean indicating that current material needs to register RTT
  41450. */
  41451. get: function () {
  41452. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41453. return true;
  41454. }
  41455. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41456. return true;
  41457. }
  41458. return false;
  41459. },
  41460. enumerable: true,
  41461. configurable: true
  41462. });
  41463. StandardMaterial.prototype.getClassName = function () {
  41464. return "StandardMaterial";
  41465. };
  41466. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41467. get: function () {
  41468. return this._useLogarithmicDepth;
  41469. },
  41470. set: function (value) {
  41471. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41472. this._markAllSubMeshesAsMiscDirty();
  41473. },
  41474. enumerable: true,
  41475. configurable: true
  41476. });
  41477. StandardMaterial.prototype.needAlphaBlending = function () {
  41478. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41479. };
  41480. StandardMaterial.prototype.needAlphaTesting = function () {
  41481. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41482. };
  41483. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41484. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41485. };
  41486. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41487. return this._diffuseTexture;
  41488. };
  41489. /**
  41490. * Child classes can use it to update shaders
  41491. */
  41492. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41493. if (useInstances === void 0) { useInstances = false; }
  41494. if (subMesh.effect && this.isFrozen) {
  41495. if (this._wasPreviouslyReady) {
  41496. return true;
  41497. }
  41498. }
  41499. if (!subMesh._materialDefines) {
  41500. subMesh._materialDefines = new StandardMaterialDefines();
  41501. }
  41502. var scene = this.getScene();
  41503. var defines = subMesh._materialDefines;
  41504. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41505. if (defines._renderId === scene.getRenderId()) {
  41506. return true;
  41507. }
  41508. }
  41509. var engine = scene.getEngine();
  41510. // Lights
  41511. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41512. // Textures
  41513. if (defines._areTexturesDirty) {
  41514. defines._needUVs = false;
  41515. defines.MAINUV1 = false;
  41516. defines.MAINUV2 = false;
  41517. if (scene.texturesEnabled) {
  41518. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41519. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41520. return false;
  41521. }
  41522. else {
  41523. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41524. }
  41525. }
  41526. else {
  41527. defines.DIFFUSE = false;
  41528. }
  41529. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41530. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41531. return false;
  41532. }
  41533. else {
  41534. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41535. }
  41536. }
  41537. else {
  41538. defines.AMBIENT = false;
  41539. }
  41540. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41541. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41542. return false;
  41543. }
  41544. else {
  41545. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41546. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41547. }
  41548. }
  41549. else {
  41550. defines.OPACITY = false;
  41551. }
  41552. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41553. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41554. return false;
  41555. }
  41556. else {
  41557. defines._needNormals = true;
  41558. defines.REFLECTION = true;
  41559. defines.ROUGHNESS = (this._roughness > 0);
  41560. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41561. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41562. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41563. switch (this._reflectionTexture.coordinatesMode) {
  41564. case BABYLON.Texture.EXPLICIT_MODE:
  41565. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41566. break;
  41567. case BABYLON.Texture.PLANAR_MODE:
  41568. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41569. break;
  41570. case BABYLON.Texture.PROJECTION_MODE:
  41571. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41572. break;
  41573. case BABYLON.Texture.SKYBOX_MODE:
  41574. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41575. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  41576. break;
  41577. case BABYLON.Texture.SPHERICAL_MODE:
  41578. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41579. break;
  41580. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41581. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41582. break;
  41583. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41584. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41585. break;
  41586. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41587. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41588. break;
  41589. case BABYLON.Texture.CUBIC_MODE:
  41590. case BABYLON.Texture.INVCUBIC_MODE:
  41591. default:
  41592. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41593. break;
  41594. }
  41595. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41596. }
  41597. }
  41598. else {
  41599. defines.REFLECTION = false;
  41600. }
  41601. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41602. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41603. return false;
  41604. }
  41605. else {
  41606. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41607. }
  41608. }
  41609. else {
  41610. defines.EMISSIVE = false;
  41611. }
  41612. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41613. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41614. return false;
  41615. }
  41616. else {
  41617. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41618. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41619. }
  41620. }
  41621. else {
  41622. defines.LIGHTMAP = false;
  41623. }
  41624. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41625. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41626. return false;
  41627. }
  41628. else {
  41629. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41630. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41631. }
  41632. }
  41633. else {
  41634. defines.SPECULAR = false;
  41635. }
  41636. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41637. // Bump texure can not be not blocking.
  41638. if (!this._bumpTexture.isReady()) {
  41639. return false;
  41640. }
  41641. else {
  41642. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41643. defines.PARALLAX = this._useParallax;
  41644. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41645. }
  41646. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41647. }
  41648. else {
  41649. defines.BUMP = false;
  41650. }
  41651. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41652. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41653. return false;
  41654. }
  41655. else {
  41656. defines._needUVs = true;
  41657. defines.REFRACTION = true;
  41658. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41659. }
  41660. }
  41661. else {
  41662. defines.REFRACTION = false;
  41663. }
  41664. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41665. }
  41666. else {
  41667. defines.DIFFUSE = false;
  41668. defines.AMBIENT = false;
  41669. defines.OPACITY = false;
  41670. defines.REFLECTION = false;
  41671. defines.EMISSIVE = false;
  41672. defines.LIGHTMAP = false;
  41673. defines.BUMP = false;
  41674. defines.REFRACTION = false;
  41675. }
  41676. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41677. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41678. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41679. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41680. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41681. }
  41682. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41683. if (!this._imageProcessingConfiguration.isReady()) {
  41684. return false;
  41685. }
  41686. this._imageProcessingConfiguration.prepareDefines(defines);
  41687. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41688. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41689. }
  41690. if (defines._areFresnelDirty) {
  41691. if (StandardMaterial.FresnelEnabled) {
  41692. // Fresnel
  41693. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41694. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41695. this._reflectionFresnelParameters) {
  41696. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41697. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41698. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41699. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41700. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41701. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41702. defines._needNormals = true;
  41703. defines.FRESNEL = true;
  41704. }
  41705. }
  41706. else {
  41707. defines.FRESNEL = false;
  41708. }
  41709. }
  41710. // Misc.
  41711. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41712. // Attribs
  41713. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41714. // Values that need to be evaluated on every frame
  41715. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41716. // Get correct effect
  41717. if (defines.isDirty) {
  41718. defines.markAsProcessed();
  41719. scene.resetCachedMaterial();
  41720. // Fallbacks
  41721. var fallbacks = new BABYLON.EffectFallbacks();
  41722. if (defines.REFLECTION) {
  41723. fallbacks.addFallback(0, "REFLECTION");
  41724. }
  41725. if (defines.SPECULAR) {
  41726. fallbacks.addFallback(0, "SPECULAR");
  41727. }
  41728. if (defines.BUMP) {
  41729. fallbacks.addFallback(0, "BUMP");
  41730. }
  41731. if (defines.PARALLAX) {
  41732. fallbacks.addFallback(1, "PARALLAX");
  41733. }
  41734. if (defines.PARALLAXOCCLUSION) {
  41735. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41736. }
  41737. if (defines.SPECULAROVERALPHA) {
  41738. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41739. }
  41740. if (defines.FOG) {
  41741. fallbacks.addFallback(1, "FOG");
  41742. }
  41743. if (defines.POINTSIZE) {
  41744. fallbacks.addFallback(0, "POINTSIZE");
  41745. }
  41746. if (defines.LOGARITHMICDEPTH) {
  41747. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  41748. }
  41749. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  41750. if (defines.SPECULARTERM) {
  41751. fallbacks.addFallback(0, "SPECULARTERM");
  41752. }
  41753. if (defines.DIFFUSEFRESNEL) {
  41754. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  41755. }
  41756. if (defines.OPACITYFRESNEL) {
  41757. fallbacks.addFallback(2, "OPACITYFRESNEL");
  41758. }
  41759. if (defines.REFLECTIONFRESNEL) {
  41760. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  41761. }
  41762. if (defines.EMISSIVEFRESNEL) {
  41763. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  41764. }
  41765. if (defines.FRESNEL) {
  41766. fallbacks.addFallback(4, "FRESNEL");
  41767. }
  41768. //Attributes
  41769. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41770. if (defines.NORMAL) {
  41771. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41772. }
  41773. if (defines.UV1) {
  41774. attribs.push(BABYLON.VertexBuffer.UVKind);
  41775. }
  41776. if (defines.UV2) {
  41777. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41778. }
  41779. if (defines.VERTEXCOLOR) {
  41780. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41781. }
  41782. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41783. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41784. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41785. var shaderName = "default";
  41786. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  41787. "vFogInfos", "vFogColor", "pointSize",
  41788. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41789. "mBones",
  41790. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  41791. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  41792. "vReflectionPosition", "vReflectionSize",
  41793. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  41794. ];
  41795. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  41796. var uniformBuffers = ["Material", "Scene"];
  41797. if (BABYLON.ImageProcessingConfiguration) {
  41798. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41799. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41800. }
  41801. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41802. uniformsNames: uniforms,
  41803. uniformBuffersNames: uniformBuffers,
  41804. samplers: samplers,
  41805. defines: defines,
  41806. maxSimultaneousLights: this._maxSimultaneousLights
  41807. });
  41808. if (this.customShaderNameResolve) {
  41809. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  41810. }
  41811. var join = defines.toString();
  41812. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  41813. attributes: attribs,
  41814. uniformsNames: uniforms,
  41815. uniformBuffersNames: uniformBuffers,
  41816. samplers: samplers,
  41817. defines: join,
  41818. fallbacks: fallbacks,
  41819. onCompiled: this.onCompiled,
  41820. onError: this.onError,
  41821. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41822. }, engine), defines);
  41823. this.buildUniformLayout();
  41824. }
  41825. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41826. return false;
  41827. }
  41828. defines._renderId = scene.getRenderId();
  41829. this._wasPreviouslyReady = true;
  41830. return true;
  41831. };
  41832. StandardMaterial.prototype.buildUniformLayout = function () {
  41833. // Order is important !
  41834. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  41835. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  41836. this._uniformBuffer.addUniform("opacityParts", 4);
  41837. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  41838. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  41839. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  41840. this._uniformBuffer.addUniform("refractionRightColor", 4);
  41841. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  41842. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  41843. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  41844. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  41845. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41846. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41847. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41848. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41849. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41850. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41851. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  41852. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41853. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  41854. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41855. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41856. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41857. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41858. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41859. this._uniformBuffer.addUniform("specularMatrix", 16);
  41860. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41861. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41862. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41863. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41864. this._uniformBuffer.addUniform("vSpecularColor", 4);
  41865. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41866. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  41867. this._uniformBuffer.addUniform("pointSize", 1);
  41868. this._uniformBuffer.create();
  41869. };
  41870. StandardMaterial.prototype.unbind = function () {
  41871. if (this._activeEffect) {
  41872. var needFlag = false;
  41873. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41874. this._activeEffect.setTexture("reflection2DSampler", null);
  41875. needFlag = true;
  41876. }
  41877. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41878. this._activeEffect.setTexture("refraction2DSampler", null);
  41879. needFlag = true;
  41880. }
  41881. if (needFlag) {
  41882. this._markAllSubMeshesAsTexturesDirty();
  41883. }
  41884. }
  41885. _super.prototype.unbind.call(this);
  41886. };
  41887. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41888. var scene = this.getScene();
  41889. var defines = subMesh._materialDefines;
  41890. if (!defines) {
  41891. return;
  41892. }
  41893. var effect = subMesh.effect;
  41894. if (!effect) {
  41895. return;
  41896. }
  41897. this._activeEffect = effect;
  41898. // Matrices
  41899. this.bindOnlyWorldMatrix(world);
  41900. // Normal Matrix
  41901. if (defines.OBJECTSPACE_NORMALMAP) {
  41902. world.toNormalMatrix(this._normalMatrix);
  41903. this.bindOnlyNormalMatrix(this._normalMatrix);
  41904. }
  41905. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41906. // Bones
  41907. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  41908. if (mustRebind) {
  41909. this._uniformBuffer.bindToEffect(effect, "Material");
  41910. this.bindViewProjection(effect);
  41911. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41912. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  41913. // Fresnel
  41914. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  41915. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  41916. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  41917. }
  41918. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  41919. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  41920. }
  41921. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  41922. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  41923. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  41924. }
  41925. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  41926. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  41927. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  41928. }
  41929. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  41930. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  41931. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  41932. }
  41933. }
  41934. // Textures
  41935. if (scene.texturesEnabled) {
  41936. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41937. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  41938. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  41939. if (this._diffuseTexture.hasAlpha) {
  41940. effect.setFloat("alphaCutOff", this.alphaCutOff);
  41941. }
  41942. }
  41943. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41944. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  41945. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41946. }
  41947. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41948. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41949. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41950. }
  41951. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41952. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  41953. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  41954. if (this._reflectionTexture.boundingBoxSize) {
  41955. var cubeTexture = this._reflectionTexture;
  41956. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41957. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41958. }
  41959. }
  41960. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41961. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41962. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41963. }
  41964. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41965. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41966. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41967. }
  41968. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41969. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  41970. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  41971. }
  41972. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  41973. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  41974. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41975. if (scene._mirroredCameraPosition) {
  41976. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41977. }
  41978. else {
  41979. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41980. }
  41981. }
  41982. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41983. var depth = 1.0;
  41984. if (!this._refractionTexture.isCube) {
  41985. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  41986. if (this._refractionTexture.depth) {
  41987. depth = this._refractionTexture.depth;
  41988. }
  41989. }
  41990. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  41991. }
  41992. }
  41993. // Point size
  41994. if (this.pointsCloud) {
  41995. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41996. }
  41997. if (defines.SPECULARTERM) {
  41998. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  41999. }
  42000. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42001. // Diffuse
  42002. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42003. }
  42004. // Textures
  42005. if (scene.texturesEnabled) {
  42006. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42007. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42008. }
  42009. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42010. effect.setTexture("ambientSampler", this._ambientTexture);
  42011. }
  42012. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42013. effect.setTexture("opacitySampler", this._opacityTexture);
  42014. }
  42015. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42016. if (this._reflectionTexture.isCube) {
  42017. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42018. }
  42019. else {
  42020. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42021. }
  42022. }
  42023. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42024. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42025. }
  42026. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42027. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42028. }
  42029. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42030. effect.setTexture("specularSampler", this._specularTexture);
  42031. }
  42032. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42033. effect.setTexture("bumpSampler", this._bumpTexture);
  42034. }
  42035. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42036. var depth = 1.0;
  42037. if (this._refractionTexture.isCube) {
  42038. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42039. }
  42040. else {
  42041. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42042. }
  42043. }
  42044. }
  42045. // Clip plane
  42046. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42047. // Colors
  42048. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42049. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42050. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42051. }
  42052. if (mustRebind || !this.isFrozen) {
  42053. // Lights
  42054. if (scene.lightsEnabled && !this._disableLighting) {
  42055. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42056. }
  42057. // View
  42058. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42059. this.bindView(effect);
  42060. }
  42061. // Fog
  42062. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42063. // Morph targets
  42064. if (defines.NUM_MORPH_INFLUENCERS) {
  42065. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42066. }
  42067. // Log. depth
  42068. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42069. // image processing
  42070. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42071. this._imageProcessingConfiguration.bind(this._activeEffect);
  42072. }
  42073. }
  42074. this._uniformBuffer.update();
  42075. this._afterBind(mesh, this._activeEffect);
  42076. };
  42077. StandardMaterial.prototype.getAnimatables = function () {
  42078. var results = [];
  42079. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42080. results.push(this._diffuseTexture);
  42081. }
  42082. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42083. results.push(this._ambientTexture);
  42084. }
  42085. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42086. results.push(this._opacityTexture);
  42087. }
  42088. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42089. results.push(this._reflectionTexture);
  42090. }
  42091. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42092. results.push(this._emissiveTexture);
  42093. }
  42094. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42095. results.push(this._specularTexture);
  42096. }
  42097. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42098. results.push(this._bumpTexture);
  42099. }
  42100. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42101. results.push(this._lightmapTexture);
  42102. }
  42103. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42104. results.push(this._refractionTexture);
  42105. }
  42106. return results;
  42107. };
  42108. StandardMaterial.prototype.getActiveTextures = function () {
  42109. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42110. if (this._diffuseTexture) {
  42111. activeTextures.push(this._diffuseTexture);
  42112. }
  42113. if (this._ambientTexture) {
  42114. activeTextures.push(this._ambientTexture);
  42115. }
  42116. if (this._opacityTexture) {
  42117. activeTextures.push(this._opacityTexture);
  42118. }
  42119. if (this._reflectionTexture) {
  42120. activeTextures.push(this._reflectionTexture);
  42121. }
  42122. if (this._emissiveTexture) {
  42123. activeTextures.push(this._emissiveTexture);
  42124. }
  42125. if (this._specularTexture) {
  42126. activeTextures.push(this._specularTexture);
  42127. }
  42128. if (this._bumpTexture) {
  42129. activeTextures.push(this._bumpTexture);
  42130. }
  42131. if (this._lightmapTexture) {
  42132. activeTextures.push(this._lightmapTexture);
  42133. }
  42134. if (this._refractionTexture) {
  42135. activeTextures.push(this._refractionTexture);
  42136. }
  42137. return activeTextures;
  42138. };
  42139. StandardMaterial.prototype.hasTexture = function (texture) {
  42140. if (_super.prototype.hasTexture.call(this, texture)) {
  42141. return true;
  42142. }
  42143. if (this._diffuseTexture === texture) {
  42144. return true;
  42145. }
  42146. if (this._ambientTexture === texture) {
  42147. return true;
  42148. }
  42149. if (this._opacityTexture === texture) {
  42150. return true;
  42151. }
  42152. if (this._reflectionTexture === texture) {
  42153. return true;
  42154. }
  42155. if (this._emissiveTexture === texture) {
  42156. return true;
  42157. }
  42158. if (this._specularTexture === texture) {
  42159. return true;
  42160. }
  42161. if (this._bumpTexture === texture) {
  42162. return true;
  42163. }
  42164. if (this._lightmapTexture === texture) {
  42165. return true;
  42166. }
  42167. if (this._refractionTexture === texture) {
  42168. return true;
  42169. }
  42170. return false;
  42171. };
  42172. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42173. if (forceDisposeTextures) {
  42174. if (this._diffuseTexture) {
  42175. this._diffuseTexture.dispose();
  42176. }
  42177. if (this._ambientTexture) {
  42178. this._ambientTexture.dispose();
  42179. }
  42180. if (this._opacityTexture) {
  42181. this._opacityTexture.dispose();
  42182. }
  42183. if (this._reflectionTexture) {
  42184. this._reflectionTexture.dispose();
  42185. }
  42186. if (this._emissiveTexture) {
  42187. this._emissiveTexture.dispose();
  42188. }
  42189. if (this._specularTexture) {
  42190. this._specularTexture.dispose();
  42191. }
  42192. if (this._bumpTexture) {
  42193. this._bumpTexture.dispose();
  42194. }
  42195. if (this._lightmapTexture) {
  42196. this._lightmapTexture.dispose();
  42197. }
  42198. if (this._refractionTexture) {
  42199. this._refractionTexture.dispose();
  42200. }
  42201. }
  42202. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42203. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42204. }
  42205. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42206. };
  42207. StandardMaterial.prototype.clone = function (name) {
  42208. var _this = this;
  42209. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42210. result.name = name;
  42211. result.id = name;
  42212. return result;
  42213. };
  42214. StandardMaterial.prototype.serialize = function () {
  42215. return BABYLON.SerializationHelper.Serialize(this);
  42216. };
  42217. // Statics
  42218. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42219. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42220. };
  42221. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42222. get: function () {
  42223. return StandardMaterial._DiffuseTextureEnabled;
  42224. },
  42225. set: function (value) {
  42226. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42227. return;
  42228. }
  42229. StandardMaterial._DiffuseTextureEnabled = value;
  42230. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42231. },
  42232. enumerable: true,
  42233. configurable: true
  42234. });
  42235. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42236. get: function () {
  42237. return StandardMaterial._AmbientTextureEnabled;
  42238. },
  42239. set: function (value) {
  42240. if (StandardMaterial._AmbientTextureEnabled === value) {
  42241. return;
  42242. }
  42243. StandardMaterial._AmbientTextureEnabled = value;
  42244. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42245. },
  42246. enumerable: true,
  42247. configurable: true
  42248. });
  42249. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42250. get: function () {
  42251. return StandardMaterial._OpacityTextureEnabled;
  42252. },
  42253. set: function (value) {
  42254. if (StandardMaterial._OpacityTextureEnabled === value) {
  42255. return;
  42256. }
  42257. StandardMaterial._OpacityTextureEnabled = value;
  42258. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42259. },
  42260. enumerable: true,
  42261. configurable: true
  42262. });
  42263. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42264. get: function () {
  42265. return StandardMaterial._ReflectionTextureEnabled;
  42266. },
  42267. set: function (value) {
  42268. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42269. return;
  42270. }
  42271. StandardMaterial._ReflectionTextureEnabled = value;
  42272. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42273. },
  42274. enumerable: true,
  42275. configurable: true
  42276. });
  42277. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42278. get: function () {
  42279. return StandardMaterial._EmissiveTextureEnabled;
  42280. },
  42281. set: function (value) {
  42282. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42283. return;
  42284. }
  42285. StandardMaterial._EmissiveTextureEnabled = value;
  42286. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42287. },
  42288. enumerable: true,
  42289. configurable: true
  42290. });
  42291. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42292. get: function () {
  42293. return StandardMaterial._SpecularTextureEnabled;
  42294. },
  42295. set: function (value) {
  42296. if (StandardMaterial._SpecularTextureEnabled === value) {
  42297. return;
  42298. }
  42299. StandardMaterial._SpecularTextureEnabled = value;
  42300. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42301. },
  42302. enumerable: true,
  42303. configurable: true
  42304. });
  42305. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42306. get: function () {
  42307. return StandardMaterial._BumpTextureEnabled;
  42308. },
  42309. set: function (value) {
  42310. if (StandardMaterial._BumpTextureEnabled === value) {
  42311. return;
  42312. }
  42313. StandardMaterial._BumpTextureEnabled = value;
  42314. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42315. },
  42316. enumerable: true,
  42317. configurable: true
  42318. });
  42319. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42320. get: function () {
  42321. return StandardMaterial._LightmapTextureEnabled;
  42322. },
  42323. set: function (value) {
  42324. if (StandardMaterial._LightmapTextureEnabled === value) {
  42325. return;
  42326. }
  42327. StandardMaterial._LightmapTextureEnabled = value;
  42328. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42329. },
  42330. enumerable: true,
  42331. configurable: true
  42332. });
  42333. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42334. get: function () {
  42335. return StandardMaterial._RefractionTextureEnabled;
  42336. },
  42337. set: function (value) {
  42338. if (StandardMaterial._RefractionTextureEnabled === value) {
  42339. return;
  42340. }
  42341. StandardMaterial._RefractionTextureEnabled = value;
  42342. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42343. },
  42344. enumerable: true,
  42345. configurable: true
  42346. });
  42347. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42348. get: function () {
  42349. return StandardMaterial._ColorGradingTextureEnabled;
  42350. },
  42351. set: function (value) {
  42352. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42353. return;
  42354. }
  42355. StandardMaterial._ColorGradingTextureEnabled = value;
  42356. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42357. },
  42358. enumerable: true,
  42359. configurable: true
  42360. });
  42361. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42362. get: function () {
  42363. return StandardMaterial._FresnelEnabled;
  42364. },
  42365. set: function (value) {
  42366. if (StandardMaterial._FresnelEnabled === value) {
  42367. return;
  42368. }
  42369. StandardMaterial._FresnelEnabled = value;
  42370. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42371. },
  42372. enumerable: true,
  42373. configurable: true
  42374. });
  42375. // Flags used to enable or disable a type of texture for all Standard Materials
  42376. StandardMaterial._DiffuseTextureEnabled = true;
  42377. StandardMaterial._AmbientTextureEnabled = true;
  42378. StandardMaterial._OpacityTextureEnabled = true;
  42379. StandardMaterial._ReflectionTextureEnabled = true;
  42380. StandardMaterial._EmissiveTextureEnabled = true;
  42381. StandardMaterial._SpecularTextureEnabled = true;
  42382. StandardMaterial._BumpTextureEnabled = true;
  42383. StandardMaterial._LightmapTextureEnabled = true;
  42384. StandardMaterial._RefractionTextureEnabled = true;
  42385. StandardMaterial._ColorGradingTextureEnabled = true;
  42386. StandardMaterial._FresnelEnabled = true;
  42387. __decorate([
  42388. BABYLON.serializeAsTexture("diffuseTexture")
  42389. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42390. __decorate([
  42391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42392. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42393. __decorate([
  42394. BABYLON.serializeAsTexture("ambientTexture")
  42395. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42396. __decorate([
  42397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42398. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42399. __decorate([
  42400. BABYLON.serializeAsTexture("opacityTexture")
  42401. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42402. __decorate([
  42403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42404. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42405. __decorate([
  42406. BABYLON.serializeAsTexture("reflectionTexture")
  42407. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42408. __decorate([
  42409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42410. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42411. __decorate([
  42412. BABYLON.serializeAsTexture("emissiveTexture")
  42413. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42414. __decorate([
  42415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42416. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42417. __decorate([
  42418. BABYLON.serializeAsTexture("specularTexture")
  42419. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42420. __decorate([
  42421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42422. ], StandardMaterial.prototype, "specularTexture", void 0);
  42423. __decorate([
  42424. BABYLON.serializeAsTexture("bumpTexture")
  42425. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42426. __decorate([
  42427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42428. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42429. __decorate([
  42430. BABYLON.serializeAsTexture("lightmapTexture")
  42431. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42432. __decorate([
  42433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42434. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42435. __decorate([
  42436. BABYLON.serializeAsTexture("refractionTexture")
  42437. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42438. __decorate([
  42439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42440. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42441. __decorate([
  42442. BABYLON.serializeAsColor3("ambient")
  42443. ], StandardMaterial.prototype, "ambientColor", void 0);
  42444. __decorate([
  42445. BABYLON.serializeAsColor3("diffuse")
  42446. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42447. __decorate([
  42448. BABYLON.serializeAsColor3("specular")
  42449. ], StandardMaterial.prototype, "specularColor", void 0);
  42450. __decorate([
  42451. BABYLON.serializeAsColor3("emissive")
  42452. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42453. __decorate([
  42454. BABYLON.serialize()
  42455. ], StandardMaterial.prototype, "specularPower", void 0);
  42456. __decorate([
  42457. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42458. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42459. __decorate([
  42460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42461. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42462. __decorate([
  42463. BABYLON.serialize("useEmissiveAsIllumination")
  42464. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42465. __decorate([
  42466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42467. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42468. __decorate([
  42469. BABYLON.serialize("linkEmissiveWithDiffuse")
  42470. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42471. __decorate([
  42472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42473. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42474. __decorate([
  42475. BABYLON.serialize("useSpecularOverAlpha")
  42476. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42477. __decorate([
  42478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42479. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42480. __decorate([
  42481. BABYLON.serialize("useReflectionOverAlpha")
  42482. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42483. __decorate([
  42484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42485. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42486. __decorate([
  42487. BABYLON.serialize("disableLighting")
  42488. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42489. __decorate([
  42490. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42491. ], StandardMaterial.prototype, "disableLighting", void 0);
  42492. __decorate([
  42493. BABYLON.serialize("useObjectSpaceNormalMap")
  42494. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42495. __decorate([
  42496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42497. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42498. __decorate([
  42499. BABYLON.serialize("useParallax")
  42500. ], StandardMaterial.prototype, "_useParallax", void 0);
  42501. __decorate([
  42502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42503. ], StandardMaterial.prototype, "useParallax", void 0);
  42504. __decorate([
  42505. BABYLON.serialize("useParallaxOcclusion")
  42506. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42507. __decorate([
  42508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42509. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42510. __decorate([
  42511. BABYLON.serialize()
  42512. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42513. __decorate([
  42514. BABYLON.serialize("roughness")
  42515. ], StandardMaterial.prototype, "_roughness", void 0);
  42516. __decorate([
  42517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42518. ], StandardMaterial.prototype, "roughness", void 0);
  42519. __decorate([
  42520. BABYLON.serialize()
  42521. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42522. __decorate([
  42523. BABYLON.serialize()
  42524. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42525. __decorate([
  42526. BABYLON.serialize()
  42527. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42528. __decorate([
  42529. BABYLON.serialize("useLightmapAsShadowmap")
  42530. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42531. __decorate([
  42532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42533. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42534. __decorate([
  42535. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42536. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42537. __decorate([
  42538. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42539. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42540. __decorate([
  42541. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42542. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42543. __decorate([
  42544. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42545. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42546. __decorate([
  42547. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42548. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42549. __decorate([
  42550. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42551. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42552. __decorate([
  42553. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42554. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42555. __decorate([
  42556. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42557. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42558. __decorate([
  42559. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42560. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42561. __decorate([
  42562. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42563. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42564. __decorate([
  42565. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42566. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42567. __decorate([
  42568. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42569. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42570. __decorate([
  42571. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42572. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42573. __decorate([
  42574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42575. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42576. __decorate([
  42577. BABYLON.serialize("maxSimultaneousLights")
  42578. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42579. __decorate([
  42580. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42581. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42582. __decorate([
  42583. BABYLON.serialize("invertNormalMapX")
  42584. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42585. __decorate([
  42586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42587. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42588. __decorate([
  42589. BABYLON.serialize("invertNormalMapY")
  42590. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42591. __decorate([
  42592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42593. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42594. __decorate([
  42595. BABYLON.serialize("twoSidedLighting")
  42596. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42597. __decorate([
  42598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42599. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42600. __decorate([
  42601. BABYLON.serialize()
  42602. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42603. return StandardMaterial;
  42604. }(BABYLON.PushMaterial));
  42605. BABYLON.StandardMaterial = StandardMaterial;
  42606. })(BABYLON || (BABYLON = {}));
  42607. //# sourceMappingURL=babylon.standardMaterial.js.map
  42608. var BABYLON;
  42609. (function (BABYLON) {
  42610. /**
  42611. * Class representing spherical polynomial coefficients to the 3rd degree
  42612. */
  42613. var SphericalPolynomial = /** @class */ (function () {
  42614. function SphericalPolynomial() {
  42615. /**
  42616. * The x coefficients of the spherical polynomial
  42617. */
  42618. this.x = BABYLON.Vector3.Zero();
  42619. /**
  42620. * The y coefficients of the spherical polynomial
  42621. */
  42622. this.y = BABYLON.Vector3.Zero();
  42623. /**
  42624. * The z coefficients of the spherical polynomial
  42625. */
  42626. this.z = BABYLON.Vector3.Zero();
  42627. /**
  42628. * The xx coefficients of the spherical polynomial
  42629. */
  42630. this.xx = BABYLON.Vector3.Zero();
  42631. /**
  42632. * The yy coefficients of the spherical polynomial
  42633. */
  42634. this.yy = BABYLON.Vector3.Zero();
  42635. /**
  42636. * The zz coefficients of the spherical polynomial
  42637. */
  42638. this.zz = BABYLON.Vector3.Zero();
  42639. /**
  42640. * The xy coefficients of the spherical polynomial
  42641. */
  42642. this.xy = BABYLON.Vector3.Zero();
  42643. /**
  42644. * The yz coefficients of the spherical polynomial
  42645. */
  42646. this.yz = BABYLON.Vector3.Zero();
  42647. /**
  42648. * The zx coefficients of the spherical polynomial
  42649. */
  42650. this.zx = BABYLON.Vector3.Zero();
  42651. }
  42652. /**
  42653. * Adds an ambient color to the spherical polynomial
  42654. * @param color the color to add
  42655. */
  42656. SphericalPolynomial.prototype.addAmbient = function (color) {
  42657. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42658. this.xx = this.xx.add(colorVector);
  42659. this.yy = this.yy.add(colorVector);
  42660. this.zz = this.zz.add(colorVector);
  42661. };
  42662. /**
  42663. * Scales the spherical polynomial by the given amount
  42664. * @param scale the amount to scale
  42665. */
  42666. SphericalPolynomial.prototype.scale = function (scale) {
  42667. this.x = this.x.scale(scale);
  42668. this.y = this.y.scale(scale);
  42669. this.z = this.z.scale(scale);
  42670. this.xx = this.xx.scale(scale);
  42671. this.yy = this.yy.scale(scale);
  42672. this.zz = this.zz.scale(scale);
  42673. this.yz = this.yz.scale(scale);
  42674. this.zx = this.zx.scale(scale);
  42675. this.xy = this.xy.scale(scale);
  42676. };
  42677. /**
  42678. * Gets the spherical polynomial from harmonics
  42679. * @param harmonics the spherical harmonics
  42680. * @returns the spherical polynomial
  42681. */
  42682. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42683. var result = new SphericalPolynomial();
  42684. result.x = harmonics.l11.scale(1.02333);
  42685. result.y = harmonics.l1_1.scale(1.02333);
  42686. result.z = harmonics.l10.scale(1.02333);
  42687. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  42688. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  42689. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  42690. result.yz = harmonics.l2_1.scale(0.858086);
  42691. result.zx = harmonics.l21.scale(0.858086);
  42692. result.xy = harmonics.l2_2.scale(0.858086);
  42693. result.scale(1.0 / Math.PI);
  42694. return result;
  42695. };
  42696. /**
  42697. * Constructs a spherical polynomial from an array.
  42698. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  42699. * @returns the spherical polynomial
  42700. */
  42701. SphericalPolynomial.FromArray = function (data) {
  42702. var sp = new SphericalPolynomial();
  42703. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  42704. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  42705. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  42706. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  42707. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  42708. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  42709. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  42710. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  42711. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  42712. return sp;
  42713. };
  42714. return SphericalPolynomial;
  42715. }());
  42716. BABYLON.SphericalPolynomial = SphericalPolynomial;
  42717. /**
  42718. * Class representing spherical harmonics coefficients to the 3rd degree
  42719. */
  42720. var SphericalHarmonics = /** @class */ (function () {
  42721. function SphericalHarmonics() {
  42722. /**
  42723. * The l0,0 coefficients of the spherical harmonics
  42724. */
  42725. this.l00 = BABYLON.Vector3.Zero();
  42726. /**
  42727. * The l1,-1 coefficients of the spherical harmonics
  42728. */
  42729. this.l1_1 = BABYLON.Vector3.Zero();
  42730. /**
  42731. * The l1,0 coefficients of the spherical harmonics
  42732. */
  42733. this.l10 = BABYLON.Vector3.Zero();
  42734. /**
  42735. * The l1,1 coefficients of the spherical harmonics
  42736. */
  42737. this.l11 = BABYLON.Vector3.Zero();
  42738. /**
  42739. * The l2,-2 coefficients of the spherical harmonics
  42740. */
  42741. this.l2_2 = BABYLON.Vector3.Zero();
  42742. /**
  42743. * The l2,-1 coefficients of the spherical harmonics
  42744. */
  42745. this.l2_1 = BABYLON.Vector3.Zero();
  42746. /**
  42747. * The l2,0 coefficients of the spherical harmonics
  42748. */
  42749. this.l20 = BABYLON.Vector3.Zero();
  42750. /**
  42751. * The l2,1 coefficients of the spherical harmonics
  42752. */
  42753. this.l21 = BABYLON.Vector3.Zero();
  42754. /**
  42755. * The l2,2 coefficients of the spherical harmonics
  42756. */
  42757. this.lL22 = BABYLON.Vector3.Zero();
  42758. }
  42759. /**
  42760. * Adds a light to the spherical harmonics
  42761. * @param direction the direction of the light
  42762. * @param color the color of the light
  42763. * @param deltaSolidAngle the delta solid angle of the light
  42764. */
  42765. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  42766. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42767. var c = colorVector.scale(deltaSolidAngle);
  42768. this.l00 = this.l00.add(c.scale(0.282095));
  42769. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  42770. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  42771. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  42772. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  42773. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  42774. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  42775. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  42776. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  42777. };
  42778. /**
  42779. * Scales the spherical harmonics by the given amount
  42780. * @param scale the amount to scale
  42781. */
  42782. SphericalHarmonics.prototype.scale = function (scale) {
  42783. this.l00 = this.l00.scale(scale);
  42784. this.l1_1 = this.l1_1.scale(scale);
  42785. this.l10 = this.l10.scale(scale);
  42786. this.l11 = this.l11.scale(scale);
  42787. this.l2_2 = this.l2_2.scale(scale);
  42788. this.l2_1 = this.l2_1.scale(scale);
  42789. this.l20 = this.l20.scale(scale);
  42790. this.l21 = this.l21.scale(scale);
  42791. this.lL22 = this.lL22.scale(scale);
  42792. };
  42793. /**
  42794. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  42795. *
  42796. * ```
  42797. * E_lm = A_l * L_lm
  42798. * ```
  42799. *
  42800. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  42801. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  42802. * the scaling factors are given in equation 9.
  42803. */
  42804. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  42805. // Constant (Band 0)
  42806. this.l00 = this.l00.scale(3.141593);
  42807. // Linear (Band 1)
  42808. this.l1_1 = this.l1_1.scale(2.094395);
  42809. this.l10 = this.l10.scale(2.094395);
  42810. this.l11 = this.l11.scale(2.094395);
  42811. // Quadratic (Band 2)
  42812. this.l2_2 = this.l2_2.scale(0.785398);
  42813. this.l2_1 = this.l2_1.scale(0.785398);
  42814. this.l20 = this.l20.scale(0.785398);
  42815. this.l21 = this.l21.scale(0.785398);
  42816. this.lL22 = this.lL22.scale(0.785398);
  42817. };
  42818. /**
  42819. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  42820. *
  42821. * ```
  42822. * L = (1/pi) * E * rho
  42823. * ```
  42824. *
  42825. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  42826. */
  42827. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  42828. this.scale(1.0 / Math.PI);
  42829. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  42830. // (The pixel shader must apply albedo after texture fetches, etc).
  42831. };
  42832. /**
  42833. * Gets the spherical harmonics from polynomial
  42834. * @param polynomial the spherical polynomial
  42835. * @returns the spherical harmonics
  42836. */
  42837. SphericalHarmonics.FromPolynomial = function (polynomial) {
  42838. var result = new SphericalHarmonics();
  42839. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  42840. result.l1_1 = polynomial.y.scale(0.977204);
  42841. result.l10 = polynomial.z.scale(0.977204);
  42842. result.l11 = polynomial.x.scale(0.977204);
  42843. result.l2_2 = polynomial.xy.scale(1.16538);
  42844. result.l2_1 = polynomial.yz.scale(1.16538);
  42845. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  42846. result.l21 = polynomial.zx.scale(1.16538);
  42847. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  42848. result.scale(Math.PI);
  42849. return result;
  42850. };
  42851. /**
  42852. * Constructs a spherical harmonics from an array.
  42853. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  42854. * @returns the spherical harmonics
  42855. */
  42856. SphericalHarmonics.FromArray = function (data) {
  42857. var sh = new SphericalHarmonics();
  42858. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  42859. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  42860. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  42861. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  42862. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  42863. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  42864. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  42865. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  42866. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  42867. return sh;
  42868. };
  42869. return SphericalHarmonics;
  42870. }());
  42871. BABYLON.SphericalHarmonics = SphericalHarmonics;
  42872. })(BABYLON || (BABYLON = {}));
  42873. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  42874. var BABYLON;
  42875. (function (BABYLON) {
  42876. var FileFaceOrientation = /** @class */ (function () {
  42877. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  42878. this.name = name;
  42879. this.worldAxisForNormal = worldAxisForNormal;
  42880. this.worldAxisForFileX = worldAxisForFileX;
  42881. this.worldAxisForFileY = worldAxisForFileY;
  42882. }
  42883. return FileFaceOrientation;
  42884. }());
  42885. ;
  42886. /**
  42887. * Helper class dealing with the extraction of spherical polynomial dataArray
  42888. * from a cube map.
  42889. */
  42890. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  42891. function CubeMapToSphericalPolynomialTools() {
  42892. }
  42893. /**
  42894. * Converts a texture to the according Spherical Polynomial data.
  42895. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42896. *
  42897. * @param texture The texture to extract the information from.
  42898. * @return The Spherical Polynomial data.
  42899. */
  42900. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  42901. if (!texture.isCube) {
  42902. // Only supports cube Textures currently.
  42903. return null;
  42904. }
  42905. var size = texture.getSize().width;
  42906. var right = texture.readPixels(0);
  42907. var left = texture.readPixels(1);
  42908. var up;
  42909. var down;
  42910. if (texture.isRenderTarget) {
  42911. up = texture.readPixels(3);
  42912. down = texture.readPixels(2);
  42913. }
  42914. else {
  42915. up = texture.readPixels(2);
  42916. down = texture.readPixels(3);
  42917. }
  42918. var front = texture.readPixels(4);
  42919. var back = texture.readPixels(5);
  42920. var gammaSpace = texture.gammaSpace;
  42921. // Always read as RGBA.
  42922. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  42923. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  42924. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  42925. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  42926. }
  42927. var cubeInfo = {
  42928. size: size,
  42929. right: right,
  42930. left: left,
  42931. up: up,
  42932. down: down,
  42933. front: front,
  42934. back: back,
  42935. format: format,
  42936. type: type,
  42937. gammaSpace: gammaSpace,
  42938. };
  42939. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  42940. };
  42941. /**
  42942. * Converts a cubemap to the according Spherical Polynomial data.
  42943. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42944. *
  42945. * @param cubeInfo The Cube map to extract the information from.
  42946. * @return The Spherical Polynomial data.
  42947. */
  42948. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  42949. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  42950. var totalSolidAngle = 0.0;
  42951. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  42952. var du = 2.0 / cubeInfo.size;
  42953. var dv = du;
  42954. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  42955. var minUV = du * 0.5 - 1.0;
  42956. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  42957. var fileFace = this.FileFaces[faceIndex];
  42958. var dataArray = cubeInfo[fileFace.name];
  42959. var v = minUV;
  42960. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  42961. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  42962. // Because SP is still linear, so summation is fine in that basis.
  42963. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  42964. for (var y = 0; y < cubeInfo.size; y++) {
  42965. var u = minUV;
  42966. for (var x = 0; x < cubeInfo.size; x++) {
  42967. // World direction (not normalised)
  42968. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  42969. worldDirection.normalize();
  42970. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  42971. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  42972. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  42973. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  42974. // Handle Integer types.
  42975. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  42976. r /= 255;
  42977. g /= 255;
  42978. b /= 255;
  42979. }
  42980. // Handle Gamma space textures.
  42981. if (cubeInfo.gammaSpace) {
  42982. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  42983. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  42984. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  42985. }
  42986. var color = new BABYLON.Color3(r, g, b);
  42987. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  42988. totalSolidAngle += deltaSolidAngle;
  42989. u += du;
  42990. }
  42991. v += dv;
  42992. }
  42993. }
  42994. // Solid angle for entire sphere is 4*pi
  42995. var sphereSolidAngle = 4.0 * Math.PI;
  42996. // Adjust the solid angle to allow for how many faces we processed.
  42997. var facesProcessed = 6.0;
  42998. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  42999. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43000. // This is needed because the numerical integration over the cube uses a
  43001. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43002. // and also to compensate for accumulative error due to float precision in the summation.
  43003. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43004. sphericalHarmonics.scale(correctionFactor);
  43005. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43006. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43007. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43008. };
  43009. CubeMapToSphericalPolynomialTools.FileFaces = [
  43010. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43011. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43012. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43013. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43014. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43015. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43016. ];
  43017. return CubeMapToSphericalPolynomialTools;
  43018. }());
  43019. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43020. })(BABYLON || (BABYLON = {}));
  43021. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43022. var BABYLON;
  43023. (function (BABYLON) {
  43024. /**
  43025. * Manages the defines for the PBR Material.
  43026. * @hiddenChildren
  43027. */
  43028. var PBRMaterialDefines = /** @class */ (function (_super) {
  43029. __extends(PBRMaterialDefines, _super);
  43030. /**
  43031. * Initializes the PBR Material defines.
  43032. */
  43033. function PBRMaterialDefines() {
  43034. var _this = _super.call(this) || this;
  43035. _this.PBR = true;
  43036. _this.MAINUV1 = false;
  43037. _this.MAINUV2 = false;
  43038. _this.UV1 = false;
  43039. _this.UV2 = false;
  43040. _this.ALBEDO = false;
  43041. _this.ALBEDODIRECTUV = 0;
  43042. _this.VERTEXCOLOR = false;
  43043. _this.AMBIENT = false;
  43044. _this.AMBIENTDIRECTUV = 0;
  43045. _this.AMBIENTINGRAYSCALE = false;
  43046. _this.OPACITY = false;
  43047. _this.VERTEXALPHA = false;
  43048. _this.OPACITYDIRECTUV = 0;
  43049. _this.OPACITYRGB = false;
  43050. _this.ALPHATEST = false;
  43051. _this.DEPTHPREPASS = false;
  43052. _this.ALPHABLEND = false;
  43053. _this.ALPHAFROMALBEDO = false;
  43054. _this.ALPHATESTVALUE = "0.5";
  43055. _this.SPECULAROVERALPHA = false;
  43056. _this.RADIANCEOVERALPHA = false;
  43057. _this.ALPHAFRESNEL = false;
  43058. _this.LINEARALPHAFRESNEL = false;
  43059. _this.PREMULTIPLYALPHA = false;
  43060. _this.EMISSIVE = false;
  43061. _this.EMISSIVEDIRECTUV = 0;
  43062. _this.REFLECTIVITY = false;
  43063. _this.REFLECTIVITYDIRECTUV = 0;
  43064. _this.SPECULARTERM = false;
  43065. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43066. _this.MICROSURFACEAUTOMATIC = false;
  43067. _this.LODBASEDMICROSFURACE = false;
  43068. _this.MICROSURFACEMAP = false;
  43069. _this.MICROSURFACEMAPDIRECTUV = 0;
  43070. _this.METALLICWORKFLOW = false;
  43071. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43072. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43073. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43074. _this.AOSTOREINMETALMAPRED = false;
  43075. _this.ENVIRONMENTBRDF = false;
  43076. _this.NORMAL = false;
  43077. _this.TANGENT = false;
  43078. _this.BUMP = false;
  43079. _this.BUMPDIRECTUV = 0;
  43080. _this.OBJECTSPACE_NORMALMAP = false;
  43081. _this.PARALLAX = false;
  43082. _this.PARALLAXOCCLUSION = false;
  43083. _this.NORMALXYSCALE = true;
  43084. _this.LIGHTMAP = false;
  43085. _this.LIGHTMAPDIRECTUV = 0;
  43086. _this.USELIGHTMAPASSHADOWMAP = false;
  43087. _this.GAMMALIGHTMAP = false;
  43088. _this.REFLECTION = false;
  43089. _this.REFLECTIONMAP_3D = false;
  43090. _this.REFLECTIONMAP_SPHERICAL = false;
  43091. _this.REFLECTIONMAP_PLANAR = false;
  43092. _this.REFLECTIONMAP_CUBIC = false;
  43093. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43094. _this.REFLECTIONMAP_PROJECTION = false;
  43095. _this.REFLECTIONMAP_SKYBOX = false;
  43096. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43097. _this.REFLECTIONMAP_EXPLICIT = false;
  43098. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43099. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43100. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43101. _this.INVERTCUBICMAP = false;
  43102. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43103. _this.USESPHERICALINVERTEX = false;
  43104. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43105. _this.LODINREFLECTIONALPHA = false;
  43106. _this.GAMMAREFLECTION = false;
  43107. _this.RGBDREFLECTION = false;
  43108. _this.RADIANCEOCCLUSION = false;
  43109. _this.HORIZONOCCLUSION = false;
  43110. _this.REFRACTION = false;
  43111. _this.REFRACTIONMAP_3D = false;
  43112. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43113. _this.LODINREFRACTIONALPHA = false;
  43114. _this.GAMMAREFRACTION = false;
  43115. _this.RGBDREFRACTION = false;
  43116. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43117. _this.INSTANCES = false;
  43118. _this.NUM_BONE_INFLUENCERS = 0;
  43119. _this.BonesPerMesh = 0;
  43120. _this.NONUNIFORMSCALING = false;
  43121. _this.MORPHTARGETS = false;
  43122. _this.MORPHTARGETS_NORMAL = false;
  43123. _this.MORPHTARGETS_TANGENT = false;
  43124. _this.NUM_MORPH_INFLUENCERS = 0;
  43125. _this.IMAGEPROCESSING = false;
  43126. _this.VIGNETTE = false;
  43127. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43128. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43129. _this.TONEMAPPING = false;
  43130. _this.TONEMAPPING_ACES = false;
  43131. _this.CONTRAST = false;
  43132. _this.COLORCURVES = false;
  43133. _this.COLORGRADING = false;
  43134. _this.COLORGRADING3D = false;
  43135. _this.SAMPLER3DGREENDEPTH = false;
  43136. _this.SAMPLER3DBGRMAP = false;
  43137. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43138. _this.EXPOSURE = false;
  43139. _this.USEPHYSICALLIGHTFALLOFF = false;
  43140. _this.USEGLTFLIGHTFALLOFF = false;
  43141. _this.TWOSIDEDLIGHTING = false;
  43142. _this.SHADOWFLOAT = false;
  43143. _this.CLIPPLANE = false;
  43144. _this.CLIPPLANE2 = false;
  43145. _this.CLIPPLANE3 = false;
  43146. _this.CLIPPLANE4 = false;
  43147. _this.POINTSIZE = false;
  43148. _this.FOG = false;
  43149. _this.LOGARITHMICDEPTH = false;
  43150. _this.FORCENORMALFORWARD = false;
  43151. _this.SPECULARAA = false;
  43152. _this.UNLIT = false;
  43153. _this.rebuild();
  43154. return _this;
  43155. }
  43156. /**
  43157. * Resets the PBR Material defines.
  43158. */
  43159. PBRMaterialDefines.prototype.reset = function () {
  43160. _super.prototype.reset.call(this);
  43161. this.ALPHATESTVALUE = "0.5";
  43162. this.PBR = true;
  43163. };
  43164. return PBRMaterialDefines;
  43165. }(BABYLON.MaterialDefines));
  43166. /**
  43167. * The Physically based material base class of BJS.
  43168. *
  43169. * This offers the main features of a standard PBR material.
  43170. * For more information, please refer to the documentation :
  43171. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43172. */
  43173. var PBRBaseMaterial = /** @class */ (function (_super) {
  43174. __extends(PBRBaseMaterial, _super);
  43175. /**
  43176. * Instantiates a new PBRMaterial instance.
  43177. *
  43178. * @param name The material name
  43179. * @param scene The scene the material will be use in.
  43180. */
  43181. function PBRBaseMaterial(name, scene) {
  43182. var _this = _super.call(this, name, scene) || this;
  43183. /**
  43184. * Intensity of the direct lights e.g. the four lights available in your scene.
  43185. * This impacts both the direct diffuse and specular highlights.
  43186. */
  43187. _this._directIntensity = 1.0;
  43188. /**
  43189. * Intensity of the emissive part of the material.
  43190. * This helps controlling the emissive effect without modifying the emissive color.
  43191. */
  43192. _this._emissiveIntensity = 1.0;
  43193. /**
  43194. * Intensity of the environment e.g. how much the environment will light the object
  43195. * either through harmonics for rough material or through the refelction for shiny ones.
  43196. */
  43197. _this._environmentIntensity = 1.0;
  43198. /**
  43199. * This is a special control allowing the reduction of the specular highlights coming from the
  43200. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43201. */
  43202. _this._specularIntensity = 1.0;
  43203. /**
  43204. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43205. */
  43206. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43207. /**
  43208. * Debug Control allowing disabling the bump map on this material.
  43209. */
  43210. _this._disableBumpMap = false;
  43211. /**
  43212. * AKA Occlusion Texture Intensity in other nomenclature.
  43213. */
  43214. _this._ambientTextureStrength = 1.0;
  43215. /**
  43216. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43217. * 1 means it completely occludes it
  43218. * 0 mean it has no impact
  43219. */
  43220. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43221. /**
  43222. * The color of a material in ambient lighting.
  43223. */
  43224. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43225. /**
  43226. * AKA Diffuse Color in other nomenclature.
  43227. */
  43228. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43229. /**
  43230. * AKA Specular Color in other nomenclature.
  43231. */
  43232. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43233. /**
  43234. * The color applied when light is reflected from a material.
  43235. */
  43236. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43237. /**
  43238. * The color applied when light is emitted from a material.
  43239. */
  43240. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43241. /**
  43242. * AKA Glossiness in other nomenclature.
  43243. */
  43244. _this._microSurface = 0.9;
  43245. /**
  43246. * source material index of refraction (IOR)' / 'destination material IOR.
  43247. */
  43248. _this._indexOfRefraction = 0.66;
  43249. /**
  43250. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43251. */
  43252. _this._invertRefractionY = false;
  43253. /**
  43254. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43255. * Materials half opaque for instance using refraction could benefit from this control.
  43256. */
  43257. _this._linkRefractionWithTransparency = false;
  43258. /**
  43259. * Specifies that the material will use the light map as a show map.
  43260. */
  43261. _this._useLightmapAsShadowmap = false;
  43262. /**
  43263. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43264. * makes the reflect vector face the model (under horizon).
  43265. */
  43266. _this._useHorizonOcclusion = true;
  43267. /**
  43268. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43269. * too much the area relying on ambient texture to define their ambient occlusion.
  43270. */
  43271. _this._useRadianceOcclusion = true;
  43272. /**
  43273. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43274. */
  43275. _this._useAlphaFromAlbedoTexture = false;
  43276. /**
  43277. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43278. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43279. */
  43280. _this._useSpecularOverAlpha = true;
  43281. /**
  43282. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43283. */
  43284. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43285. /**
  43286. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43287. */
  43288. _this._useRoughnessFromMetallicTextureAlpha = true;
  43289. /**
  43290. * Specifies if the metallic texture contains the roughness information in its green channel.
  43291. */
  43292. _this._useRoughnessFromMetallicTextureGreen = false;
  43293. /**
  43294. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43295. */
  43296. _this._useMetallnessFromMetallicTextureBlue = false;
  43297. /**
  43298. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43299. */
  43300. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43301. /**
  43302. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43303. */
  43304. _this._useAmbientInGrayScale = false;
  43305. /**
  43306. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43307. * The material will try to infer what glossiness each pixel should be.
  43308. */
  43309. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43310. /**
  43311. * Defines the falloff type used in this material.
  43312. * It by default is Physical.
  43313. */
  43314. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43315. /**
  43316. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43317. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43318. */
  43319. _this._useRadianceOverAlpha = true;
  43320. /**
  43321. * Allows using an object space normal map (instead of tangent space).
  43322. */
  43323. _this._useObjectSpaceNormalMap = false;
  43324. /**
  43325. * Allows using the bump map in parallax mode.
  43326. */
  43327. _this._useParallax = false;
  43328. /**
  43329. * Allows using the bump map in parallax occlusion mode.
  43330. */
  43331. _this._useParallaxOcclusion = false;
  43332. /**
  43333. * Controls the scale bias of the parallax mode.
  43334. */
  43335. _this._parallaxScaleBias = 0.05;
  43336. /**
  43337. * If sets to true, disables all the lights affecting the material.
  43338. */
  43339. _this._disableLighting = false;
  43340. /**
  43341. * Number of Simultaneous lights allowed on the material.
  43342. */
  43343. _this._maxSimultaneousLights = 4;
  43344. /**
  43345. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43346. */
  43347. _this._invertNormalMapX = false;
  43348. /**
  43349. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43350. */
  43351. _this._invertNormalMapY = false;
  43352. /**
  43353. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43354. */
  43355. _this._twoSidedLighting = false;
  43356. /**
  43357. * Defines the alpha limits in alpha test mode.
  43358. */
  43359. _this._alphaCutOff = 0.4;
  43360. /**
  43361. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43362. */
  43363. _this._forceAlphaTest = false;
  43364. /**
  43365. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43366. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43367. */
  43368. _this._useAlphaFresnel = false;
  43369. /**
  43370. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43371. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43372. */
  43373. _this._useLinearAlphaFresnel = false;
  43374. /**
  43375. * The transparency mode of the material.
  43376. */
  43377. _this._transparencyMode = null;
  43378. /**
  43379. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43380. * from cos thetav and roughness:
  43381. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43382. */
  43383. _this._environmentBRDFTexture = null;
  43384. /**
  43385. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43386. */
  43387. _this._forceIrradianceInFragment = false;
  43388. /**
  43389. * Force normal to face away from face.
  43390. */
  43391. _this._forceNormalForward = false;
  43392. /**
  43393. * Enables specular anti aliasing in the PBR shader.
  43394. * It will both interacts on the Geometry for analytical and IBL lighting.
  43395. * It also prefilter the roughness map based on the bump values.
  43396. */
  43397. _this._enableSpecularAntiAliasing = false;
  43398. /**
  43399. * Stores the available render targets.
  43400. */
  43401. _this._renderTargets = new BABYLON.SmartArray(16);
  43402. /**
  43403. * Sets the global ambient color for the material used in lighting calculations.
  43404. */
  43405. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43406. /**
  43407. * If set to true, no lighting calculations will be applied.
  43408. */
  43409. _this._unlit = false;
  43410. // Setup the default processing configuration to the scene.
  43411. _this._attachImageProcessingConfiguration(null);
  43412. _this.getRenderTargetTextures = function () {
  43413. _this._renderTargets.reset();
  43414. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43415. _this._renderTargets.push(_this._reflectionTexture);
  43416. }
  43417. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43418. _this._renderTargets.push(_this._refractionTexture);
  43419. }
  43420. return _this._renderTargets;
  43421. };
  43422. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43423. return _this;
  43424. }
  43425. /**
  43426. * Attaches a new image processing configuration to the PBR Material.
  43427. * @param configuration
  43428. */
  43429. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43430. var _this = this;
  43431. if (configuration === this._imageProcessingConfiguration) {
  43432. return;
  43433. }
  43434. // Detaches observer.
  43435. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43436. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43437. }
  43438. // Pick the scene configuration if needed.
  43439. if (!configuration) {
  43440. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43441. }
  43442. else {
  43443. this._imageProcessingConfiguration = configuration;
  43444. }
  43445. // Attaches observer.
  43446. if (this._imageProcessingConfiguration) {
  43447. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43448. _this._markAllSubMeshesAsImageProcessingDirty();
  43449. });
  43450. }
  43451. };
  43452. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  43453. /**
  43454. * Gets a boolean indicating that current material needs to register RTT
  43455. */
  43456. get: function () {
  43457. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43458. return true;
  43459. }
  43460. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43461. return true;
  43462. }
  43463. return false;
  43464. },
  43465. enumerable: true,
  43466. configurable: true
  43467. });
  43468. /**
  43469. * Gets the name of the material class.
  43470. */
  43471. PBRBaseMaterial.prototype.getClassName = function () {
  43472. return "PBRBaseMaterial";
  43473. };
  43474. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43475. /**
  43476. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43477. */
  43478. get: function () {
  43479. return this._useLogarithmicDepth;
  43480. },
  43481. /**
  43482. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43483. */
  43484. set: function (value) {
  43485. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43486. },
  43487. enumerable: true,
  43488. configurable: true
  43489. });
  43490. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43491. /**
  43492. * Gets the current transparency mode.
  43493. */
  43494. get: function () {
  43495. return this._transparencyMode;
  43496. },
  43497. /**
  43498. * Sets the transparency mode of the material.
  43499. *
  43500. * | Value | Type | Description |
  43501. * | ----- | ----------------------------------- | ----------- |
  43502. * | 0 | OPAQUE | |
  43503. * | 1 | ALPHATEST | |
  43504. * | 2 | ALPHABLEND | |
  43505. * | 3 | ALPHATESTANDBLEND | |
  43506. *
  43507. */
  43508. set: function (value) {
  43509. if (this._transparencyMode === value) {
  43510. return;
  43511. }
  43512. this._transparencyMode = value;
  43513. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43514. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43515. },
  43516. enumerable: true,
  43517. configurable: true
  43518. });
  43519. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43520. /**
  43521. * Returns true if alpha blending should be disabled.
  43522. */
  43523. get: function () {
  43524. return (this._linkRefractionWithTransparency ||
  43525. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43526. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43527. },
  43528. enumerable: true,
  43529. configurable: true
  43530. });
  43531. /**
  43532. * Specifies whether or not this material should be rendered in alpha blend mode.
  43533. */
  43534. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43535. if (this._disableAlphaBlending) {
  43536. return false;
  43537. }
  43538. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43539. };
  43540. /**
  43541. * Specifies if the mesh will require alpha blending.
  43542. * @param mesh - BJS mesh.
  43543. */
  43544. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43545. if (this._disableAlphaBlending) {
  43546. return false;
  43547. }
  43548. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43549. };
  43550. /**
  43551. * Specifies whether or not this material should be rendered in alpha test mode.
  43552. */
  43553. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43554. if (this._forceAlphaTest) {
  43555. return true;
  43556. }
  43557. if (this._linkRefractionWithTransparency) {
  43558. return false;
  43559. }
  43560. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43561. };
  43562. /**
  43563. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43564. */
  43565. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43566. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43567. };
  43568. /**
  43569. * Gets the texture used for the alpha test.
  43570. */
  43571. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43572. return this._albedoTexture;
  43573. };
  43574. /**
  43575. * Specifies that the submesh is ready to be used.
  43576. * @param mesh - BJS mesh.
  43577. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43578. * @param useInstances - Specifies that instances should be used.
  43579. * @returns - boolean indicating that the submesh is ready or not.
  43580. */
  43581. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43582. if (subMesh.effect && this.isFrozen) {
  43583. if (this._wasPreviouslyReady) {
  43584. return true;
  43585. }
  43586. }
  43587. if (!subMesh._materialDefines) {
  43588. subMesh._materialDefines = new PBRMaterialDefines();
  43589. }
  43590. var defines = subMesh._materialDefines;
  43591. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43592. if (defines._renderId === this.getScene().getRenderId()) {
  43593. return true;
  43594. }
  43595. }
  43596. var scene = this.getScene();
  43597. var engine = scene.getEngine();
  43598. if (defines._areTexturesDirty) {
  43599. if (scene.texturesEnabled) {
  43600. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43601. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43602. return false;
  43603. }
  43604. }
  43605. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43606. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43607. return false;
  43608. }
  43609. }
  43610. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43611. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43612. return false;
  43613. }
  43614. }
  43615. var reflectionTexture = this._getReflectionTexture();
  43616. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43617. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43618. return false;
  43619. }
  43620. }
  43621. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43622. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43623. return false;
  43624. }
  43625. }
  43626. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43627. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43628. return false;
  43629. }
  43630. }
  43631. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43632. if (this._metallicTexture) {
  43633. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43634. return false;
  43635. }
  43636. }
  43637. else if (this._reflectivityTexture) {
  43638. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43639. return false;
  43640. }
  43641. }
  43642. if (this._microSurfaceTexture) {
  43643. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43644. return false;
  43645. }
  43646. }
  43647. }
  43648. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43649. // Bump texture cannot be not blocking.
  43650. if (!this._bumpTexture.isReady()) {
  43651. return false;
  43652. }
  43653. }
  43654. var refractionTexture = this._getRefractionTexture();
  43655. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43656. if (!refractionTexture.isReadyOrNotBlocking()) {
  43657. return false;
  43658. }
  43659. }
  43660. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43661. // This is blocking.
  43662. if (!this._environmentBRDFTexture.isReady()) {
  43663. return false;
  43664. }
  43665. }
  43666. }
  43667. }
  43668. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43669. if (!this._imageProcessingConfiguration.isReady()) {
  43670. return false;
  43671. }
  43672. }
  43673. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43674. mesh.createNormals(true);
  43675. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43676. }
  43677. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43678. if (effect) {
  43679. scene.resetCachedMaterial();
  43680. subMesh.setEffect(effect, defines);
  43681. this.buildUniformLayout();
  43682. }
  43683. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43684. return false;
  43685. }
  43686. defines._renderId = scene.getRenderId();
  43687. this._wasPreviouslyReady = true;
  43688. return true;
  43689. };
  43690. /**
  43691. * Specifies if the material uses metallic roughness workflow.
  43692. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43693. */
  43694. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43695. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43696. return true;
  43697. }
  43698. return false;
  43699. };
  43700. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43701. if (onCompiled === void 0) { onCompiled = null; }
  43702. if (onError === void 0) { onError = null; }
  43703. if (useInstances === void 0) { useInstances = null; }
  43704. if (useClipPlane === void 0) { useClipPlane = null; }
  43705. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43706. if (!defines.isDirty) {
  43707. return null;
  43708. }
  43709. defines.markAsProcessed();
  43710. var scene = this.getScene();
  43711. var engine = scene.getEngine();
  43712. // Fallbacks
  43713. var fallbacks = new BABYLON.EffectFallbacks();
  43714. var fallbackRank = 0;
  43715. if (defines.USESPHERICALINVERTEX) {
  43716. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43717. }
  43718. if (defines.FOG) {
  43719. fallbacks.addFallback(fallbackRank, "FOG");
  43720. }
  43721. if (defines.SPECULARAA) {
  43722. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43723. }
  43724. if (defines.POINTSIZE) {
  43725. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43726. }
  43727. if (defines.LOGARITHMICDEPTH) {
  43728. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43729. }
  43730. if (defines.PARALLAX) {
  43731. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43732. }
  43733. if (defines.PARALLAXOCCLUSION) {
  43734. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43735. }
  43736. if (defines.ENVIRONMENTBRDF) {
  43737. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43738. }
  43739. if (defines.TANGENT) {
  43740. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43741. }
  43742. if (defines.BUMP) {
  43743. fallbacks.addFallback(fallbackRank++, "BUMP");
  43744. }
  43745. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43746. if (defines.SPECULARTERM) {
  43747. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43748. }
  43749. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43750. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43751. }
  43752. if (defines.LIGHTMAP) {
  43753. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43754. }
  43755. if (defines.NORMAL) {
  43756. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43757. }
  43758. if (defines.AMBIENT) {
  43759. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43760. }
  43761. if (defines.EMISSIVE) {
  43762. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43763. }
  43764. if (defines.VERTEXCOLOR) {
  43765. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43766. }
  43767. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43768. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43769. }
  43770. if (defines.MORPHTARGETS) {
  43771. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43772. }
  43773. //Attributes
  43774. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43775. if (defines.NORMAL) {
  43776. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43777. }
  43778. if (defines.TANGENT) {
  43779. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43780. }
  43781. if (defines.UV1) {
  43782. attribs.push(BABYLON.VertexBuffer.UVKind);
  43783. }
  43784. if (defines.UV2) {
  43785. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43786. }
  43787. if (defines.VERTEXCOLOR) {
  43788. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43789. }
  43790. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43791. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43792. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43793. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43794. "vFogInfos", "vFogColor", "pointSize",
  43795. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43796. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43797. "mBones",
  43798. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43799. "vLightingIntensity",
  43800. "logarithmicDepthConstant",
  43801. "vSphericalX", "vSphericalY", "vSphericalZ",
  43802. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43803. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43804. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43805. "vTangentSpaceParams"
  43806. ];
  43807. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43808. "bumpSampler", "lightmapSampler", "opacitySampler",
  43809. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43810. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43811. "microSurfaceSampler", "environmentBrdfSampler"];
  43812. var uniformBuffers = ["Material", "Scene"];
  43813. if (BABYLON.ImageProcessingConfiguration) {
  43814. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43815. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43816. }
  43817. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43818. uniformsNames: uniforms,
  43819. uniformBuffersNames: uniformBuffers,
  43820. samplers: samplers,
  43821. defines: defines,
  43822. maxSimultaneousLights: this._maxSimultaneousLights
  43823. });
  43824. var join = defines.toString();
  43825. return engine.createEffect("pbr", {
  43826. attributes: attribs,
  43827. uniformsNames: uniforms,
  43828. uniformBuffersNames: uniformBuffers,
  43829. samplers: samplers,
  43830. defines: join,
  43831. fallbacks: fallbacks,
  43832. onCompiled: onCompiled,
  43833. onError: onError,
  43834. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43835. }, engine);
  43836. };
  43837. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43838. if (useInstances === void 0) { useInstances = null; }
  43839. if (useClipPlane === void 0) { useClipPlane = null; }
  43840. var scene = this.getScene();
  43841. var engine = scene.getEngine();
  43842. // Lights
  43843. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43844. defines._needNormals = true;
  43845. // Textures
  43846. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43847. if (defines._areTexturesDirty) {
  43848. defines._needUVs = false;
  43849. if (scene.texturesEnabled) {
  43850. if (scene.getEngine().getCaps().textureLOD) {
  43851. defines.LODBASEDMICROSFURACE = true;
  43852. }
  43853. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43854. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43855. }
  43856. else {
  43857. defines.ALBEDO = false;
  43858. }
  43859. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43860. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43861. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43862. }
  43863. else {
  43864. defines.AMBIENT = false;
  43865. }
  43866. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43867. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43868. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43869. }
  43870. else {
  43871. defines.OPACITY = false;
  43872. }
  43873. var reflectionTexture = this._getReflectionTexture();
  43874. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43875. defines.REFLECTION = true;
  43876. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  43877. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  43878. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  43879. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  43880. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  43881. defines.INVERTCUBICMAP = true;
  43882. }
  43883. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  43884. switch (reflectionTexture.coordinatesMode) {
  43885. case BABYLON.Texture.EXPLICIT_MODE:
  43886. defines.REFLECTIONMAP_EXPLICIT = true;
  43887. break;
  43888. case BABYLON.Texture.PLANAR_MODE:
  43889. defines.REFLECTIONMAP_PLANAR = true;
  43890. break;
  43891. case BABYLON.Texture.PROJECTION_MODE:
  43892. defines.REFLECTIONMAP_PROJECTION = true;
  43893. break;
  43894. case BABYLON.Texture.SKYBOX_MODE:
  43895. defines.REFLECTIONMAP_SKYBOX = true;
  43896. break;
  43897. case BABYLON.Texture.SPHERICAL_MODE:
  43898. defines.REFLECTIONMAP_SPHERICAL = true;
  43899. break;
  43900. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43901. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  43902. break;
  43903. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43904. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  43905. break;
  43906. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43907. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  43908. break;
  43909. case BABYLON.Texture.CUBIC_MODE:
  43910. case BABYLON.Texture.INVCUBIC_MODE:
  43911. default:
  43912. defines.REFLECTIONMAP_CUBIC = true;
  43913. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  43914. break;
  43915. }
  43916. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  43917. if (reflectionTexture.sphericalPolynomial) {
  43918. defines.USESPHERICALFROMREFLECTIONMAP = true;
  43919. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  43920. defines.USESPHERICALINVERTEX = false;
  43921. }
  43922. else {
  43923. defines.USESPHERICALINVERTEX = true;
  43924. }
  43925. }
  43926. }
  43927. else {
  43928. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  43929. }
  43930. }
  43931. else {
  43932. defines.REFLECTION = false;
  43933. defines.REFLECTIONMAP_3D = false;
  43934. defines.REFLECTIONMAP_SPHERICAL = false;
  43935. defines.REFLECTIONMAP_PLANAR = false;
  43936. defines.REFLECTIONMAP_CUBIC = false;
  43937. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43938. defines.REFLECTIONMAP_PROJECTION = false;
  43939. defines.REFLECTIONMAP_SKYBOX = false;
  43940. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43941. defines.REFLECTIONMAP_EXPLICIT = false;
  43942. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43943. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43944. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43945. defines.INVERTCUBICMAP = false;
  43946. defines.USESPHERICALFROMREFLECTIONMAP = false;
  43947. defines.USESPHERICALINVERTEX = false;
  43948. defines.REFLECTIONMAP_OPPOSITEZ = false;
  43949. defines.LODINREFLECTIONALPHA = false;
  43950. defines.GAMMAREFLECTION = false;
  43951. defines.RGBDREFLECTION = false;
  43952. }
  43953. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43954. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43955. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43956. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  43957. }
  43958. else {
  43959. defines.LIGHTMAP = false;
  43960. }
  43961. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43962. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43963. }
  43964. else {
  43965. defines.EMISSIVE = false;
  43966. }
  43967. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43968. if (this._metallicTexture) {
  43969. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  43970. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  43971. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  43972. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  43973. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  43974. }
  43975. else if (this._reflectivityTexture) {
  43976. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  43977. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  43978. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  43979. }
  43980. else {
  43981. defines.REFLECTIVITY = false;
  43982. }
  43983. if (this._microSurfaceTexture) {
  43984. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  43985. }
  43986. else {
  43987. defines.MICROSURFACEMAP = false;
  43988. }
  43989. }
  43990. else {
  43991. defines.REFLECTIVITY = false;
  43992. defines.MICROSURFACEMAP = false;
  43993. }
  43994. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43995. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43996. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43997. defines.PARALLAX = true;
  43998. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  43999. }
  44000. else {
  44001. defines.PARALLAX = false;
  44002. }
  44003. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44004. }
  44005. else {
  44006. defines.BUMP = false;
  44007. }
  44008. var refractionTexture = this._getRefractionTexture();
  44009. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44010. defines.REFRACTION = true;
  44011. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44012. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44013. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44014. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44015. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44016. if (this._linkRefractionWithTransparency) {
  44017. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44018. }
  44019. }
  44020. else {
  44021. defines.REFRACTION = false;
  44022. }
  44023. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44024. defines.ENVIRONMENTBRDF = true;
  44025. }
  44026. else {
  44027. defines.ENVIRONMENTBRDF = false;
  44028. }
  44029. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44030. defines.ALPHAFROMALBEDO = true;
  44031. }
  44032. else {
  44033. defines.ALPHAFROMALBEDO = false;
  44034. }
  44035. }
  44036. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44037. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44038. defines.USEPHYSICALLIGHTFALLOFF = false;
  44039. defines.USEGLTFLIGHTFALLOFF = false;
  44040. }
  44041. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44042. defines.USEPHYSICALLIGHTFALLOFF = false;
  44043. defines.USEGLTFLIGHTFALLOFF = true;
  44044. }
  44045. else {
  44046. defines.USEPHYSICALLIGHTFALLOFF = true;
  44047. defines.USEGLTFLIGHTFALLOFF = false;
  44048. }
  44049. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44050. if (!this.backFaceCulling && this._twoSidedLighting) {
  44051. defines.TWOSIDEDLIGHTING = true;
  44052. }
  44053. else {
  44054. defines.TWOSIDEDLIGHTING = false;
  44055. }
  44056. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44057. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44058. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44059. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44060. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44061. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44062. }
  44063. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44064. this._imageProcessingConfiguration.prepareDefines(defines);
  44065. }
  44066. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44067. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44068. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44069. // Misc.
  44070. if (defines._areMiscDirty) {
  44071. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44072. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44073. }
  44074. // Values that need to be evaluated on every frame
  44075. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44076. // Attribs
  44077. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44078. };
  44079. /**
  44080. * Force shader compilation
  44081. */
  44082. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44083. var _this = this;
  44084. var localOptions = __assign({ clipPlane: false }, options);
  44085. var defines = new PBRMaterialDefines();
  44086. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44087. if (effect.isReady()) {
  44088. if (onCompiled) {
  44089. onCompiled(this);
  44090. }
  44091. }
  44092. else {
  44093. effect.onCompileObservable.add(function () {
  44094. if (onCompiled) {
  44095. onCompiled(_this);
  44096. }
  44097. });
  44098. }
  44099. };
  44100. /**
  44101. * Initializes the uniform buffer layout for the shader.
  44102. */
  44103. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44104. // Order is important !
  44105. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44106. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44107. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44108. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44109. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44110. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44111. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44112. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44113. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44114. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44115. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44116. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44117. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44118. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44119. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44120. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44121. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44122. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44123. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44124. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44125. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44126. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44127. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44128. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44129. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44130. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44131. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44132. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44133. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44134. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44135. this._uniformBuffer.addUniform("pointSize", 1);
  44136. this._uniformBuffer.create();
  44137. };
  44138. /**
  44139. * Unbinds the textures.
  44140. */
  44141. PBRBaseMaterial.prototype.unbind = function () {
  44142. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44143. this._uniformBuffer.setTexture("reflectionSampler", null);
  44144. }
  44145. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44146. this._uniformBuffer.setTexture("refractionSampler", null);
  44147. }
  44148. _super.prototype.unbind.call(this);
  44149. };
  44150. /**
  44151. * Binds the submesh data.
  44152. * @param world - The world matrix.
  44153. * @param mesh - The BJS mesh.
  44154. * @param subMesh - A submesh of the BJS mesh.
  44155. */
  44156. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44157. var scene = this.getScene();
  44158. var defines = subMesh._materialDefines;
  44159. if (!defines) {
  44160. return;
  44161. }
  44162. var effect = subMesh.effect;
  44163. if (!effect) {
  44164. return;
  44165. }
  44166. this._activeEffect = effect;
  44167. // Matrices
  44168. this.bindOnlyWorldMatrix(world);
  44169. // Normal Matrix
  44170. if (defines.OBJECTSPACE_NORMALMAP) {
  44171. world.toNormalMatrix(this._normalMatrix);
  44172. this.bindOnlyNormalMatrix(this._normalMatrix);
  44173. }
  44174. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44175. // Bones
  44176. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44177. var reflectionTexture = null;
  44178. if (mustRebind) {
  44179. this._uniformBuffer.bindToEffect(effect, "Material");
  44180. this.bindViewProjection(effect);
  44181. reflectionTexture = this._getReflectionTexture();
  44182. var refractionTexture = this._getRefractionTexture();
  44183. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44184. // Texture uniforms
  44185. if (scene.texturesEnabled) {
  44186. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44187. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44188. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44189. }
  44190. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44191. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44192. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44193. }
  44194. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44195. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44196. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44197. }
  44198. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44199. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44200. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44201. if (reflectionTexture.boundingBoxSize) {
  44202. var cubeTexture = reflectionTexture;
  44203. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44204. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44205. }
  44206. var polynomials = reflectionTexture.sphericalPolynomial;
  44207. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44208. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44209. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44210. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44211. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44212. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44213. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44214. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44215. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44216. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44217. }
  44218. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44219. }
  44220. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44221. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44222. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44223. }
  44224. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44225. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44226. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44227. }
  44228. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44229. if (this._metallicTexture) {
  44230. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44231. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44232. }
  44233. else if (this._reflectivityTexture) {
  44234. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44235. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44236. }
  44237. if (this._microSurfaceTexture) {
  44238. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44239. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44240. }
  44241. }
  44242. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44243. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44244. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44245. if (scene._mirroredCameraPosition) {
  44246. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44247. }
  44248. else {
  44249. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44250. }
  44251. }
  44252. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44253. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44254. var depth = 1.0;
  44255. if (!refractionTexture.isCube) {
  44256. if (refractionTexture.depth) {
  44257. depth = refractionTexture.depth;
  44258. }
  44259. }
  44260. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44261. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44262. }
  44263. }
  44264. // Point size
  44265. if (this.pointsCloud) {
  44266. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44267. }
  44268. // Colors
  44269. if (defines.METALLICWORKFLOW) {
  44270. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44271. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44272. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44273. }
  44274. else {
  44275. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44276. }
  44277. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44278. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44279. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44280. // Misc
  44281. this._lightingInfos.x = this._directIntensity;
  44282. this._lightingInfos.y = this._emissiveIntensity;
  44283. this._lightingInfos.z = this._environmentIntensity;
  44284. this._lightingInfos.w = this._specularIntensity;
  44285. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44286. }
  44287. // Textures
  44288. if (scene.texturesEnabled) {
  44289. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44290. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44291. }
  44292. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44293. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44294. }
  44295. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44296. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44297. }
  44298. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44299. if (defines.LODBASEDMICROSFURACE) {
  44300. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44301. }
  44302. else {
  44303. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44304. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44305. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44306. }
  44307. }
  44308. if (defines.ENVIRONMENTBRDF) {
  44309. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44310. }
  44311. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44312. if (defines.LODBASEDMICROSFURACE) {
  44313. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44314. }
  44315. else {
  44316. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44317. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44318. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44319. }
  44320. }
  44321. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44322. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44323. }
  44324. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44325. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44326. }
  44327. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44328. if (this._metallicTexture) {
  44329. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44330. }
  44331. else if (this._reflectivityTexture) {
  44332. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44333. }
  44334. if (this._microSurfaceTexture) {
  44335. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44336. }
  44337. }
  44338. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44339. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44340. }
  44341. }
  44342. // Clip plane
  44343. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44344. // Colors
  44345. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44346. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44347. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44348. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44349. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44350. }
  44351. if (mustRebind || !this.isFrozen) {
  44352. // Lights
  44353. if (scene.lightsEnabled && !this._disableLighting) {
  44354. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44355. }
  44356. // View
  44357. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44358. this.bindView(effect);
  44359. }
  44360. // Fog
  44361. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44362. // Morph targets
  44363. if (defines.NUM_MORPH_INFLUENCERS) {
  44364. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44365. }
  44366. // image processing
  44367. this._imageProcessingConfiguration.bind(this._activeEffect);
  44368. // Log. depth
  44369. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44370. }
  44371. this._uniformBuffer.update();
  44372. this._afterBind(mesh, this._activeEffect);
  44373. };
  44374. /**
  44375. * Returns the animatable textures.
  44376. * @returns - Array of animatable textures.
  44377. */
  44378. PBRBaseMaterial.prototype.getAnimatables = function () {
  44379. var results = [];
  44380. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44381. results.push(this._albedoTexture);
  44382. }
  44383. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44384. results.push(this._ambientTexture);
  44385. }
  44386. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44387. results.push(this._opacityTexture);
  44388. }
  44389. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44390. results.push(this._reflectionTexture);
  44391. }
  44392. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44393. results.push(this._emissiveTexture);
  44394. }
  44395. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44396. results.push(this._metallicTexture);
  44397. }
  44398. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44399. results.push(this._reflectivityTexture);
  44400. }
  44401. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44402. results.push(this._bumpTexture);
  44403. }
  44404. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44405. results.push(this._lightmapTexture);
  44406. }
  44407. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44408. results.push(this._refractionTexture);
  44409. }
  44410. return results;
  44411. };
  44412. /**
  44413. * Returns the texture used for reflections.
  44414. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44415. */
  44416. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44417. if (this._reflectionTexture) {
  44418. return this._reflectionTexture;
  44419. }
  44420. return this.getScene().environmentTexture;
  44421. };
  44422. /**
  44423. * Returns the texture used for refraction or null if none is used.
  44424. * @returns - Refection texture if present. If no refraction texture and refraction
  44425. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44426. */
  44427. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44428. if (this._refractionTexture) {
  44429. return this._refractionTexture;
  44430. }
  44431. if (this._linkRefractionWithTransparency) {
  44432. return this.getScene().environmentTexture;
  44433. }
  44434. return null;
  44435. };
  44436. /**
  44437. * Disposes the resources of the material.
  44438. * @param forceDisposeEffect - Forces the disposal of effects.
  44439. * @param forceDisposeTextures - Forces the disposal of all textures.
  44440. */
  44441. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44442. if (forceDisposeTextures) {
  44443. if (this._albedoTexture) {
  44444. this._albedoTexture.dispose();
  44445. }
  44446. if (this._ambientTexture) {
  44447. this._ambientTexture.dispose();
  44448. }
  44449. if (this._opacityTexture) {
  44450. this._opacityTexture.dispose();
  44451. }
  44452. if (this._reflectionTexture) {
  44453. this._reflectionTexture.dispose();
  44454. }
  44455. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44456. this._environmentBRDFTexture.dispose();
  44457. }
  44458. if (this._emissiveTexture) {
  44459. this._emissiveTexture.dispose();
  44460. }
  44461. if (this._metallicTexture) {
  44462. this._metallicTexture.dispose();
  44463. }
  44464. if (this._reflectivityTexture) {
  44465. this._reflectivityTexture.dispose();
  44466. }
  44467. if (this._bumpTexture) {
  44468. this._bumpTexture.dispose();
  44469. }
  44470. if (this._lightmapTexture) {
  44471. this._lightmapTexture.dispose();
  44472. }
  44473. if (this._refractionTexture) {
  44474. this._refractionTexture.dispose();
  44475. }
  44476. }
  44477. this._renderTargets.dispose();
  44478. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44479. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44480. }
  44481. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44482. };
  44483. /**
  44484. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44485. */
  44486. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44487. /**
  44488. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44489. * to enhance interoperability with other engines.
  44490. */
  44491. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44492. /**
  44493. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44494. * to enhance interoperability with other materials.
  44495. */
  44496. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44497. /**
  44498. * Stores the reflectivity values based on metallic roughness workflow.
  44499. */
  44500. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44501. __decorate([
  44502. BABYLON.serializeAsImageProcessingConfiguration()
  44503. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44504. __decorate([
  44505. BABYLON.serialize()
  44506. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44507. __decorate([
  44508. BABYLON.serialize()
  44509. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44510. return PBRBaseMaterial;
  44511. }(BABYLON.PushMaterial));
  44512. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44513. })(BABYLON || (BABYLON = {}));
  44514. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44515. var BABYLON;
  44516. (function (BABYLON) {
  44517. /**
  44518. * The Physically based simple base material of BJS.
  44519. *
  44520. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44521. * It is used as the base class for both the specGloss and metalRough conventions.
  44522. */
  44523. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44524. __extends(PBRBaseSimpleMaterial, _super);
  44525. /**
  44526. * Instantiates a new PBRMaterial instance.
  44527. *
  44528. * @param name The material name
  44529. * @param scene The scene the material will be use in.
  44530. */
  44531. function PBRBaseSimpleMaterial(name, scene) {
  44532. var _this = _super.call(this, name, scene) || this;
  44533. /**
  44534. * Number of Simultaneous lights allowed on the material.
  44535. */
  44536. _this.maxSimultaneousLights = 4;
  44537. /**
  44538. * If sets to true, disables all the lights affecting the material.
  44539. */
  44540. _this.disableLighting = false;
  44541. /**
  44542. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44543. */
  44544. _this.invertNormalMapX = false;
  44545. /**
  44546. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44547. */
  44548. _this.invertNormalMapY = false;
  44549. /**
  44550. * Emissivie color used to self-illuminate the model.
  44551. */
  44552. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44553. /**
  44554. * Occlusion Channel Strenght.
  44555. */
  44556. _this.occlusionStrength = 1.0;
  44557. _this.useLightmapAsShadowmap = false;
  44558. _this._useAlphaFromAlbedoTexture = true;
  44559. _this._useAmbientInGrayScale = true;
  44560. return _this;
  44561. }
  44562. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44563. /**
  44564. * Gets the current double sided mode.
  44565. */
  44566. get: function () {
  44567. return this._twoSidedLighting;
  44568. },
  44569. /**
  44570. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44571. */
  44572. set: function (value) {
  44573. if (this._twoSidedLighting === value) {
  44574. return;
  44575. }
  44576. this._twoSidedLighting = value;
  44577. this.backFaceCulling = !value;
  44578. this._markAllSubMeshesAsTexturesDirty();
  44579. },
  44580. enumerable: true,
  44581. configurable: true
  44582. });
  44583. /**
  44584. * Return the active textures of the material.
  44585. */
  44586. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44587. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44588. if (this.environmentTexture) {
  44589. activeTextures.push(this.environmentTexture);
  44590. }
  44591. if (this.normalTexture) {
  44592. activeTextures.push(this.normalTexture);
  44593. }
  44594. if (this.emissiveTexture) {
  44595. activeTextures.push(this.emissiveTexture);
  44596. }
  44597. if (this.occlusionTexture) {
  44598. activeTextures.push(this.occlusionTexture);
  44599. }
  44600. if (this.lightmapTexture) {
  44601. activeTextures.push(this.lightmapTexture);
  44602. }
  44603. return activeTextures;
  44604. };
  44605. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44606. if (_super.prototype.hasTexture.call(this, texture)) {
  44607. return true;
  44608. }
  44609. if (this.lightmapTexture === texture) {
  44610. return true;
  44611. }
  44612. return false;
  44613. };
  44614. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44615. return "PBRBaseSimpleMaterial";
  44616. };
  44617. __decorate([
  44618. BABYLON.serialize(),
  44619. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44620. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44621. __decorate([
  44622. BABYLON.serialize(),
  44623. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44624. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44625. __decorate([
  44626. BABYLON.serializeAsTexture(),
  44627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44628. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44629. __decorate([
  44630. BABYLON.serialize(),
  44631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44632. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44633. __decorate([
  44634. BABYLON.serialize(),
  44635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44636. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44637. __decorate([
  44638. BABYLON.serializeAsTexture(),
  44639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44640. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44641. __decorate([
  44642. BABYLON.serializeAsColor3("emissive"),
  44643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44644. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44645. __decorate([
  44646. BABYLON.serializeAsTexture(),
  44647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44648. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44649. __decorate([
  44650. BABYLON.serialize(),
  44651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44652. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44653. __decorate([
  44654. BABYLON.serializeAsTexture(),
  44655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44656. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44657. __decorate([
  44658. BABYLON.serialize(),
  44659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44660. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44661. __decorate([
  44662. BABYLON.serialize()
  44663. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44664. __decorate([
  44665. BABYLON.serializeAsTexture(),
  44666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44667. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44668. __decorate([
  44669. BABYLON.serialize(),
  44670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44671. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44672. return PBRBaseSimpleMaterial;
  44673. }(BABYLON.PBRBaseMaterial));
  44674. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44675. })(BABYLON || (BABYLON = {}));
  44676. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44677. var BABYLON;
  44678. (function (BABYLON) {
  44679. /**
  44680. * The Physically based material of BJS.
  44681. *
  44682. * This offers the main features of a standard PBR material.
  44683. * For more information, please refer to the documentation :
  44684. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44685. */
  44686. var PBRMaterial = /** @class */ (function (_super) {
  44687. __extends(PBRMaterial, _super);
  44688. /**
  44689. * Instantiates a new PBRMaterial instance.
  44690. *
  44691. * @param name The material name
  44692. * @param scene The scene the material will be use in.
  44693. */
  44694. function PBRMaterial(name, scene) {
  44695. var _this = _super.call(this, name, scene) || this;
  44696. /**
  44697. * Intensity of the direct lights e.g. the four lights available in your scene.
  44698. * This impacts both the direct diffuse and specular highlights.
  44699. */
  44700. _this.directIntensity = 1.0;
  44701. /**
  44702. * Intensity of the emissive part of the material.
  44703. * This helps controlling the emissive effect without modifying the emissive color.
  44704. */
  44705. _this.emissiveIntensity = 1.0;
  44706. /**
  44707. * Intensity of the environment e.g. how much the environment will light the object
  44708. * either through harmonics for rough material or through the refelction for shiny ones.
  44709. */
  44710. _this.environmentIntensity = 1.0;
  44711. /**
  44712. * This is a special control allowing the reduction of the specular highlights coming from the
  44713. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44714. */
  44715. _this.specularIntensity = 1.0;
  44716. /**
  44717. * Debug Control allowing disabling the bump map on this material.
  44718. */
  44719. _this.disableBumpMap = false;
  44720. /**
  44721. * AKA Occlusion Texture Intensity in other nomenclature.
  44722. */
  44723. _this.ambientTextureStrength = 1.0;
  44724. /**
  44725. * Defines how much the AO map is occluding the analytical lights (point spot...).
  44726. * 1 means it completely occludes it
  44727. * 0 mean it has no impact
  44728. */
  44729. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  44730. /**
  44731. * The color of a material in ambient lighting.
  44732. */
  44733. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44734. /**
  44735. * AKA Diffuse Color in other nomenclature.
  44736. */
  44737. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44738. /**
  44739. * AKA Specular Color in other nomenclature.
  44740. */
  44741. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44742. /**
  44743. * The color reflected from the material.
  44744. */
  44745. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44746. /**
  44747. * The color emitted from the material.
  44748. */
  44749. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44750. /**
  44751. * AKA Glossiness in other nomenclature.
  44752. */
  44753. _this.microSurface = 1.0;
  44754. /**
  44755. * source material index of refraction (IOR)' / 'destination material IOR.
  44756. */
  44757. _this.indexOfRefraction = 0.66;
  44758. /**
  44759. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44760. */
  44761. _this.invertRefractionY = false;
  44762. /**
  44763. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44764. * Materials half opaque for instance using refraction could benefit from this control.
  44765. */
  44766. _this.linkRefractionWithTransparency = false;
  44767. _this.useLightmapAsShadowmap = false;
  44768. /**
  44769. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44770. */
  44771. _this.useAlphaFromAlbedoTexture = false;
  44772. /**
  44773. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44774. */
  44775. _this.forceAlphaTest = false;
  44776. /**
  44777. * Defines the alpha limits in alpha test mode.
  44778. */
  44779. _this.alphaCutOff = 0.4;
  44780. /**
  44781. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44782. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44783. */
  44784. _this.useSpecularOverAlpha = true;
  44785. /**
  44786. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44787. */
  44788. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44789. /**
  44790. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44791. */
  44792. _this.useRoughnessFromMetallicTextureAlpha = true;
  44793. /**
  44794. * Specifies if the metallic texture contains the roughness information in its green channel.
  44795. */
  44796. _this.useRoughnessFromMetallicTextureGreen = false;
  44797. /**
  44798. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44799. */
  44800. _this.useMetallnessFromMetallicTextureBlue = false;
  44801. /**
  44802. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44803. */
  44804. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44805. /**
  44806. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44807. */
  44808. _this.useAmbientInGrayScale = false;
  44809. /**
  44810. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44811. * The material will try to infer what glossiness each pixel should be.
  44812. */
  44813. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44814. /**
  44815. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44816. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44817. */
  44818. _this.useRadianceOverAlpha = true;
  44819. /**
  44820. * Allows using an object space normal map (instead of tangent space).
  44821. */
  44822. _this.useObjectSpaceNormalMap = false;
  44823. /**
  44824. * Allows using the bump map in parallax mode.
  44825. */
  44826. _this.useParallax = false;
  44827. /**
  44828. * Allows using the bump map in parallax occlusion mode.
  44829. */
  44830. _this.useParallaxOcclusion = false;
  44831. /**
  44832. * Controls the scale bias of the parallax mode.
  44833. */
  44834. _this.parallaxScaleBias = 0.05;
  44835. /**
  44836. * If sets to true, disables all the lights affecting the material.
  44837. */
  44838. _this.disableLighting = false;
  44839. /**
  44840. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44841. */
  44842. _this.forceIrradianceInFragment = false;
  44843. /**
  44844. * Number of Simultaneous lights allowed on the material.
  44845. */
  44846. _this.maxSimultaneousLights = 4;
  44847. /**
  44848. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44849. */
  44850. _this.invertNormalMapX = false;
  44851. /**
  44852. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44853. */
  44854. _this.invertNormalMapY = false;
  44855. /**
  44856. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44857. */
  44858. _this.twoSidedLighting = false;
  44859. /**
  44860. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44861. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44862. */
  44863. _this.useAlphaFresnel = false;
  44864. /**
  44865. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44866. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44867. */
  44868. _this.useLinearAlphaFresnel = false;
  44869. /**
  44870. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44871. * And/Or occlude the blended part.
  44872. */
  44873. _this.environmentBRDFTexture = null;
  44874. /**
  44875. * Force normal to face away from face.
  44876. */
  44877. _this.forceNormalForward = false;
  44878. /**
  44879. * Enables specular anti aliasing in the PBR shader.
  44880. * It will both interacts on the Geometry for analytical and IBL lighting.
  44881. * It also prefilter the roughness map based on the bump values.
  44882. */
  44883. _this.enableSpecularAntiAliasing = false;
  44884. /**
  44885. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44886. * makes the reflect vector face the model (under horizon).
  44887. */
  44888. _this.useHorizonOcclusion = true;
  44889. /**
  44890. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44891. * too much the area relying on ambient texture to define their ambient occlusion.
  44892. */
  44893. _this.useRadianceOcclusion = true;
  44894. /**
  44895. * If set to true, no lighting calculations will be applied.
  44896. */
  44897. _this.unlit = false;
  44898. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44899. return _this;
  44900. }
  44901. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  44902. /**
  44903. * BJS is using an harcoded light falloff based on a manually sets up range.
  44904. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44905. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44906. */
  44907. get: function () {
  44908. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  44909. },
  44910. /**
  44911. * BJS is using an harcoded light falloff based on a manually sets up range.
  44912. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44913. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44914. */
  44915. set: function (value) {
  44916. if (value !== this.usePhysicalLightFalloff) {
  44917. // Ensure the effect will be rebuilt.
  44918. this._markAllSubMeshesAsTexturesDirty();
  44919. if (value) {
  44920. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  44921. }
  44922. else {
  44923. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  44924. }
  44925. }
  44926. },
  44927. enumerable: true,
  44928. configurable: true
  44929. });
  44930. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  44931. /**
  44932. * In order to support the falloff compatibility with gltf, a special mode has been added
  44933. * to reproduce the gltf light falloff.
  44934. */
  44935. get: function () {
  44936. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  44937. },
  44938. /**
  44939. * In order to support the falloff compatibility with gltf, a special mode has been added
  44940. * to reproduce the gltf light falloff.
  44941. */
  44942. set: function (value) {
  44943. if (value !== this.useGLTFLightFalloff) {
  44944. // Ensure the effect will be rebuilt.
  44945. this._markAllSubMeshesAsTexturesDirty();
  44946. if (value) {
  44947. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  44948. }
  44949. else {
  44950. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  44951. }
  44952. }
  44953. },
  44954. enumerable: true,
  44955. configurable: true
  44956. });
  44957. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  44958. /**
  44959. * Gets the image processing configuration used either in this material.
  44960. */
  44961. get: function () {
  44962. return this._imageProcessingConfiguration;
  44963. },
  44964. /**
  44965. * Sets the Default image processing configuration used either in the this material.
  44966. *
  44967. * If sets to null, the scene one is in use.
  44968. */
  44969. set: function (value) {
  44970. this._attachImageProcessingConfiguration(value);
  44971. // Ensure the effect will be rebuilt.
  44972. this._markAllSubMeshesAsTexturesDirty();
  44973. },
  44974. enumerable: true,
  44975. configurable: true
  44976. });
  44977. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  44978. /**
  44979. * Gets wether the color curves effect is enabled.
  44980. */
  44981. get: function () {
  44982. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44983. },
  44984. /**
  44985. * Sets wether the color curves effect is enabled.
  44986. */
  44987. set: function (value) {
  44988. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  44989. },
  44990. enumerable: true,
  44991. configurable: true
  44992. });
  44993. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  44994. /**
  44995. * Gets wether the color grading effect is enabled.
  44996. */
  44997. get: function () {
  44998. return this.imageProcessingConfiguration.colorGradingEnabled;
  44999. },
  45000. /**
  45001. * Gets wether the color grading effect is enabled.
  45002. */
  45003. set: function (value) {
  45004. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45005. },
  45006. enumerable: true,
  45007. configurable: true
  45008. });
  45009. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45010. /**
  45011. * Gets wether tonemapping is enabled or not.
  45012. */
  45013. get: function () {
  45014. return this._imageProcessingConfiguration.toneMappingEnabled;
  45015. },
  45016. /**
  45017. * Sets wether tonemapping is enabled or not
  45018. */
  45019. set: function (value) {
  45020. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45021. },
  45022. enumerable: true,
  45023. configurable: true
  45024. });
  45025. ;
  45026. ;
  45027. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45028. /**
  45029. * The camera exposure used on this material.
  45030. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45031. * This corresponds to a photographic exposure.
  45032. */
  45033. get: function () {
  45034. return this._imageProcessingConfiguration.exposure;
  45035. },
  45036. /**
  45037. * The camera exposure used on this material.
  45038. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45039. * This corresponds to a photographic exposure.
  45040. */
  45041. set: function (value) {
  45042. this._imageProcessingConfiguration.exposure = value;
  45043. },
  45044. enumerable: true,
  45045. configurable: true
  45046. });
  45047. ;
  45048. ;
  45049. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45050. /**
  45051. * Gets The camera contrast used on this material.
  45052. */
  45053. get: function () {
  45054. return this._imageProcessingConfiguration.contrast;
  45055. },
  45056. /**
  45057. * Sets The camera contrast used on this material.
  45058. */
  45059. set: function (value) {
  45060. this._imageProcessingConfiguration.contrast = value;
  45061. },
  45062. enumerable: true,
  45063. configurable: true
  45064. });
  45065. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45066. /**
  45067. * Gets the Color Grading 2D Lookup Texture.
  45068. */
  45069. get: function () {
  45070. return this._imageProcessingConfiguration.colorGradingTexture;
  45071. },
  45072. /**
  45073. * Sets the Color Grading 2D Lookup Texture.
  45074. */
  45075. set: function (value) {
  45076. this._imageProcessingConfiguration.colorGradingTexture = value;
  45077. },
  45078. enumerable: true,
  45079. configurable: true
  45080. });
  45081. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45082. /**
  45083. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45084. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45085. * 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;
  45086. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45087. */
  45088. get: function () {
  45089. return this._imageProcessingConfiguration.colorCurves;
  45090. },
  45091. /**
  45092. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45093. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45094. * 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;
  45095. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45096. */
  45097. set: function (value) {
  45098. this._imageProcessingConfiguration.colorCurves = value;
  45099. },
  45100. enumerable: true,
  45101. configurable: true
  45102. });
  45103. /**
  45104. * Returns the name of this material class.
  45105. */
  45106. PBRMaterial.prototype.getClassName = function () {
  45107. return "PBRMaterial";
  45108. };
  45109. /**
  45110. * Returns an array of the actively used textures.
  45111. * @returns - Array of BaseTextures
  45112. */
  45113. PBRMaterial.prototype.getActiveTextures = function () {
  45114. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45115. if (this._albedoTexture) {
  45116. activeTextures.push(this._albedoTexture);
  45117. }
  45118. if (this._ambientTexture) {
  45119. activeTextures.push(this._ambientTexture);
  45120. }
  45121. if (this._opacityTexture) {
  45122. activeTextures.push(this._opacityTexture);
  45123. }
  45124. if (this._reflectionTexture) {
  45125. activeTextures.push(this._reflectionTexture);
  45126. }
  45127. if (this._emissiveTexture) {
  45128. activeTextures.push(this._emissiveTexture);
  45129. }
  45130. if (this._reflectivityTexture) {
  45131. activeTextures.push(this._reflectivityTexture);
  45132. }
  45133. if (this._metallicTexture) {
  45134. activeTextures.push(this._metallicTexture);
  45135. }
  45136. if (this._microSurfaceTexture) {
  45137. activeTextures.push(this._microSurfaceTexture);
  45138. }
  45139. if (this._bumpTexture) {
  45140. activeTextures.push(this._bumpTexture);
  45141. }
  45142. if (this._lightmapTexture) {
  45143. activeTextures.push(this._lightmapTexture);
  45144. }
  45145. if (this._refractionTexture) {
  45146. activeTextures.push(this._refractionTexture);
  45147. }
  45148. return activeTextures;
  45149. };
  45150. /**
  45151. * Checks to see if a texture is used in the material.
  45152. * @param texture - Base texture to use.
  45153. * @returns - Boolean specifying if a texture is used in the material.
  45154. */
  45155. PBRMaterial.prototype.hasTexture = function (texture) {
  45156. if (_super.prototype.hasTexture.call(this, texture)) {
  45157. return true;
  45158. }
  45159. if (this._albedoTexture === texture) {
  45160. return true;
  45161. }
  45162. if (this._ambientTexture === texture) {
  45163. return true;
  45164. }
  45165. if (this._opacityTexture === texture) {
  45166. return true;
  45167. }
  45168. if (this._reflectionTexture === texture) {
  45169. return true;
  45170. }
  45171. if (this._reflectivityTexture === texture) {
  45172. return true;
  45173. }
  45174. if (this._metallicTexture === texture) {
  45175. return true;
  45176. }
  45177. if (this._microSurfaceTexture === texture) {
  45178. return true;
  45179. }
  45180. if (this._bumpTexture === texture) {
  45181. return true;
  45182. }
  45183. if (this._lightmapTexture === texture) {
  45184. return true;
  45185. }
  45186. if (this._refractionTexture === texture) {
  45187. return true;
  45188. }
  45189. return false;
  45190. };
  45191. /**
  45192. * Makes a duplicate of the current material.
  45193. * @param name - name to use for the new material.
  45194. */
  45195. PBRMaterial.prototype.clone = function (name) {
  45196. var _this = this;
  45197. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45198. clone.id = name;
  45199. clone.name = name;
  45200. return clone;
  45201. };
  45202. /**
  45203. * Serializes this PBR Material.
  45204. * @returns - An object with the serialized material.
  45205. */
  45206. PBRMaterial.prototype.serialize = function () {
  45207. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45208. serializationObject.customType = "BABYLON.PBRMaterial";
  45209. return serializationObject;
  45210. };
  45211. // Statics
  45212. /**
  45213. * Parses a PBR Material from a serialized object.
  45214. * @param source - Serialized object.
  45215. * @param scene - BJS scene instance.
  45216. * @param rootUrl - url for the scene object
  45217. * @returns - PBRMaterial
  45218. */
  45219. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45220. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45221. };
  45222. /**
  45223. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45224. */
  45225. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45226. /**
  45227. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45228. */
  45229. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45230. /**
  45231. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45232. */
  45233. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45234. /**
  45235. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45236. * They are also discarded below the alpha cutoff threshold to improve performances.
  45237. */
  45238. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45239. /**
  45240. * Defines the default value of how much AO map is occluding the analytical lights
  45241. * (point spot...).
  45242. */
  45243. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45244. __decorate([
  45245. BABYLON.serialize(),
  45246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45247. ], PBRMaterial.prototype, "directIntensity", void 0);
  45248. __decorate([
  45249. BABYLON.serialize(),
  45250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45251. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45252. __decorate([
  45253. BABYLON.serialize(),
  45254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45255. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45256. __decorate([
  45257. BABYLON.serialize(),
  45258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45259. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45260. __decorate([
  45261. BABYLON.serialize(),
  45262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45263. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45264. __decorate([
  45265. BABYLON.serializeAsTexture(),
  45266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45267. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45268. __decorate([
  45269. BABYLON.serializeAsTexture(),
  45270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45271. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45272. __decorate([
  45273. BABYLON.serialize(),
  45274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45275. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45276. __decorate([
  45277. BABYLON.serialize(),
  45278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45279. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45280. __decorate([
  45281. BABYLON.serializeAsTexture(),
  45282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45283. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45284. __decorate([
  45285. BABYLON.serializeAsTexture(),
  45286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45287. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45288. __decorate([
  45289. BABYLON.serializeAsTexture(),
  45290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45291. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45292. __decorate([
  45293. BABYLON.serializeAsTexture(),
  45294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45295. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45296. __decorate([
  45297. BABYLON.serializeAsTexture(),
  45298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45299. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45300. __decorate([
  45301. BABYLON.serialize(),
  45302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45303. ], PBRMaterial.prototype, "metallic", void 0);
  45304. __decorate([
  45305. BABYLON.serialize(),
  45306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45307. ], PBRMaterial.prototype, "roughness", void 0);
  45308. __decorate([
  45309. BABYLON.serializeAsTexture(),
  45310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45311. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45312. __decorate([
  45313. BABYLON.serializeAsTexture(),
  45314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45315. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45316. __decorate([
  45317. BABYLON.serializeAsTexture(),
  45318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45319. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45320. __decorate([
  45321. BABYLON.serializeAsTexture(),
  45322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45323. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45324. __decorate([
  45325. BABYLON.serializeAsColor3("ambient"),
  45326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45327. ], PBRMaterial.prototype, "ambientColor", void 0);
  45328. __decorate([
  45329. BABYLON.serializeAsColor3("albedo"),
  45330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45331. ], PBRMaterial.prototype, "albedoColor", void 0);
  45332. __decorate([
  45333. BABYLON.serializeAsColor3("reflectivity"),
  45334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45335. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45336. __decorate([
  45337. BABYLON.serializeAsColor3("reflection"),
  45338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45339. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45340. __decorate([
  45341. BABYLON.serializeAsColor3("emissive"),
  45342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45343. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45344. __decorate([
  45345. BABYLON.serialize(),
  45346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45347. ], PBRMaterial.prototype, "microSurface", void 0);
  45348. __decorate([
  45349. BABYLON.serialize(),
  45350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45351. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45352. __decorate([
  45353. BABYLON.serialize(),
  45354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45355. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45356. __decorate([
  45357. BABYLON.serialize(),
  45358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45359. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45360. __decorate([
  45361. BABYLON.serialize(),
  45362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45363. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45364. __decorate([
  45365. BABYLON.serialize(),
  45366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45367. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45368. __decorate([
  45369. BABYLON.serialize(),
  45370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45371. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45372. __decorate([
  45373. BABYLON.serialize(),
  45374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45375. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45376. __decorate([
  45377. BABYLON.serialize(),
  45378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45379. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45380. __decorate([
  45381. BABYLON.serialize(),
  45382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45383. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45384. __decorate([
  45385. BABYLON.serialize(),
  45386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45387. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45388. __decorate([
  45389. BABYLON.serialize(),
  45390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45391. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45392. __decorate([
  45393. BABYLON.serialize(),
  45394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45395. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45396. __decorate([
  45397. BABYLON.serialize(),
  45398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45399. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45400. __decorate([
  45401. BABYLON.serialize(),
  45402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45403. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45404. __decorate([
  45405. BABYLON.serialize(),
  45406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45407. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45408. __decorate([
  45409. BABYLON.serialize()
  45410. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45411. __decorate([
  45412. BABYLON.serialize()
  45413. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45414. __decorate([
  45415. BABYLON.serialize(),
  45416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45417. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45418. __decorate([
  45419. BABYLON.serialize(),
  45420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45421. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45422. __decorate([
  45423. BABYLON.serialize(),
  45424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45425. ], PBRMaterial.prototype, "useParallax", void 0);
  45426. __decorate([
  45427. BABYLON.serialize(),
  45428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45429. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45430. __decorate([
  45431. BABYLON.serialize(),
  45432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45433. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45434. __decorate([
  45435. BABYLON.serialize(),
  45436. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45437. ], PBRMaterial.prototype, "disableLighting", void 0);
  45438. __decorate([
  45439. BABYLON.serialize(),
  45440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45441. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45442. __decorate([
  45443. BABYLON.serialize(),
  45444. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45445. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45446. __decorate([
  45447. BABYLON.serialize(),
  45448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45449. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45450. __decorate([
  45451. BABYLON.serialize(),
  45452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45453. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45454. __decorate([
  45455. BABYLON.serialize(),
  45456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45457. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45458. __decorate([
  45459. BABYLON.serialize(),
  45460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45461. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45462. __decorate([
  45463. BABYLON.serialize(),
  45464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45465. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45466. __decorate([
  45467. BABYLON.serializeAsTexture(),
  45468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45469. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45470. __decorate([
  45471. BABYLON.serialize(),
  45472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45473. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45474. __decorate([
  45475. BABYLON.serialize(),
  45476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45477. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45478. __decorate([
  45479. BABYLON.serialize(),
  45480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45481. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45482. __decorate([
  45483. BABYLON.serialize(),
  45484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45485. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45486. __decorate([
  45487. BABYLON.serialize(),
  45488. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45489. ], PBRMaterial.prototype, "unlit", void 0);
  45490. return PBRMaterial;
  45491. }(BABYLON.PBRBaseMaterial));
  45492. BABYLON.PBRMaterial = PBRMaterial;
  45493. })(BABYLON || (BABYLON = {}));
  45494. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45495. var BABYLON;
  45496. (function (BABYLON) {
  45497. /**
  45498. * The PBR material of BJS following the metal roughness convention.
  45499. *
  45500. * This fits to the PBR convention in the GLTF definition:
  45501. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45502. */
  45503. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45504. __extends(PBRMetallicRoughnessMaterial, _super);
  45505. /**
  45506. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45507. *
  45508. * @param name The material name
  45509. * @param scene The scene the material will be use in.
  45510. */
  45511. function PBRMetallicRoughnessMaterial(name, scene) {
  45512. var _this = _super.call(this, name, scene) || this;
  45513. _this._useRoughnessFromMetallicTextureAlpha = false;
  45514. _this._useRoughnessFromMetallicTextureGreen = true;
  45515. _this._useMetallnessFromMetallicTextureBlue = true;
  45516. _this.metallic = 1.0;
  45517. _this.roughness = 1.0;
  45518. return _this;
  45519. }
  45520. /**
  45521. * Return the currrent class name of the material.
  45522. */
  45523. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45524. return "PBRMetallicRoughnessMaterial";
  45525. };
  45526. /**
  45527. * Return the active textures of the material.
  45528. */
  45529. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45530. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45531. if (this.baseTexture) {
  45532. activeTextures.push(this.baseTexture);
  45533. }
  45534. if (this.metallicRoughnessTexture) {
  45535. activeTextures.push(this.metallicRoughnessTexture);
  45536. }
  45537. return activeTextures;
  45538. };
  45539. /**
  45540. * Checks to see if a texture is used in the material.
  45541. * @param texture - Base texture to use.
  45542. * @returns - Boolean specifying if a texture is used in the material.
  45543. */
  45544. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45545. if (_super.prototype.hasTexture.call(this, texture)) {
  45546. return true;
  45547. }
  45548. if (this.baseTexture === texture) {
  45549. return true;
  45550. }
  45551. if (this.metallicRoughnessTexture === texture) {
  45552. return true;
  45553. }
  45554. return false;
  45555. };
  45556. /**
  45557. * Makes a duplicate of the current material.
  45558. * @param name - name to use for the new material.
  45559. */
  45560. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45561. var _this = this;
  45562. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45563. clone.id = name;
  45564. clone.name = name;
  45565. return clone;
  45566. };
  45567. /**
  45568. * Serialize the material to a parsable JSON object.
  45569. */
  45570. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45571. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45572. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45573. return serializationObject;
  45574. };
  45575. /**
  45576. * Parses a JSON object correponding to the serialize function.
  45577. */
  45578. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45579. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45580. };
  45581. __decorate([
  45582. BABYLON.serializeAsColor3(),
  45583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45584. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45585. __decorate([
  45586. BABYLON.serializeAsTexture(),
  45587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45588. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45589. __decorate([
  45590. BABYLON.serialize(),
  45591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45592. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45593. __decorate([
  45594. BABYLON.serialize(),
  45595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45596. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45597. __decorate([
  45598. BABYLON.serializeAsTexture(),
  45599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45600. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45601. return PBRMetallicRoughnessMaterial;
  45602. }(BABYLON.PBRBaseSimpleMaterial));
  45603. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45604. })(BABYLON || (BABYLON = {}));
  45605. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45606. var BABYLON;
  45607. (function (BABYLON) {
  45608. /**
  45609. * The PBR material of BJS following the specular glossiness convention.
  45610. *
  45611. * This fits to the PBR convention in the GLTF definition:
  45612. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45613. */
  45614. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45615. __extends(PBRSpecularGlossinessMaterial, _super);
  45616. /**
  45617. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45618. *
  45619. * @param name The material name
  45620. * @param scene The scene the material will be use in.
  45621. */
  45622. function PBRSpecularGlossinessMaterial(name, scene) {
  45623. var _this = _super.call(this, name, scene) || this;
  45624. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45625. return _this;
  45626. }
  45627. /**
  45628. * Return the currrent class name of the material.
  45629. */
  45630. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45631. return "PBRSpecularGlossinessMaterial";
  45632. };
  45633. /**
  45634. * Return the active textures of the material.
  45635. */
  45636. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45637. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45638. if (this.diffuseTexture) {
  45639. activeTextures.push(this.diffuseTexture);
  45640. }
  45641. if (this.specularGlossinessTexture) {
  45642. activeTextures.push(this.specularGlossinessTexture);
  45643. }
  45644. return activeTextures;
  45645. };
  45646. /**
  45647. * Checks to see if a texture is used in the material.
  45648. * @param texture - Base texture to use.
  45649. * @returns - Boolean specifying if a texture is used in the material.
  45650. */
  45651. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45652. if (_super.prototype.hasTexture.call(this, texture)) {
  45653. return true;
  45654. }
  45655. if (this.diffuseTexture === texture) {
  45656. return true;
  45657. }
  45658. if (this.specularGlossinessTexture === texture) {
  45659. return true;
  45660. }
  45661. return false;
  45662. };
  45663. /**
  45664. * Makes a duplicate of the current material.
  45665. * @param name - name to use for the new material.
  45666. */
  45667. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45668. var _this = this;
  45669. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45670. clone.id = name;
  45671. clone.name = name;
  45672. return clone;
  45673. };
  45674. /**
  45675. * Serialize the material to a parsable JSON object.
  45676. */
  45677. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45678. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45679. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45680. return serializationObject;
  45681. };
  45682. /**
  45683. * Parses a JSON object correponding to the serialize function.
  45684. */
  45685. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45686. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45687. };
  45688. __decorate([
  45689. BABYLON.serializeAsColor3("diffuse"),
  45690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45691. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45692. __decorate([
  45693. BABYLON.serializeAsTexture(),
  45694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45695. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45696. __decorate([
  45697. BABYLON.serializeAsColor3("specular"),
  45698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45699. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45700. __decorate([
  45701. BABYLON.serialize(),
  45702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45703. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45704. __decorate([
  45705. BABYLON.serializeAsTexture(),
  45706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45707. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45708. return PBRSpecularGlossinessMaterial;
  45709. }(BABYLON.PBRBaseSimpleMaterial));
  45710. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45711. })(BABYLON || (BABYLON = {}));
  45712. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45713. var BABYLON;
  45714. (function (BABYLON) {
  45715. BABYLON.CameraInputTypes = {};
  45716. var CameraInputsManager = /** @class */ (function () {
  45717. function CameraInputsManager(camera) {
  45718. this.attached = {};
  45719. this.camera = camera;
  45720. this.checkInputs = function () { };
  45721. }
  45722. /**
  45723. * Add an input method to a camera
  45724. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45725. * @param input camera input method
  45726. */
  45727. CameraInputsManager.prototype.add = function (input) {
  45728. var type = input.getSimpleName();
  45729. if (this.attached[type]) {
  45730. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45731. return;
  45732. }
  45733. this.attached[type] = input;
  45734. input.camera = this.camera;
  45735. //for checkInputs, we are dynamically creating a function
  45736. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45737. if (input.checkInputs) {
  45738. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45739. }
  45740. if (this.attachedElement) {
  45741. input.attachControl(this.attachedElement);
  45742. }
  45743. };
  45744. /**
  45745. * Remove a specific input method from a camera
  45746. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45747. * @param inputToRemove camera input method
  45748. */
  45749. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45750. for (var cam in this.attached) {
  45751. var input = this.attached[cam];
  45752. if (input === inputToRemove) {
  45753. input.detachControl(this.attachedElement);
  45754. input.camera = null;
  45755. delete this.attached[cam];
  45756. this.rebuildInputCheck();
  45757. }
  45758. }
  45759. };
  45760. CameraInputsManager.prototype.removeByType = function (inputType) {
  45761. for (var cam in this.attached) {
  45762. var input = this.attached[cam];
  45763. if (input.getClassName() === inputType) {
  45764. input.detachControl(this.attachedElement);
  45765. input.camera = null;
  45766. delete this.attached[cam];
  45767. this.rebuildInputCheck();
  45768. }
  45769. }
  45770. };
  45771. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45772. var current = this.checkInputs;
  45773. return function () {
  45774. current();
  45775. fn();
  45776. };
  45777. };
  45778. CameraInputsManager.prototype.attachInput = function (input) {
  45779. if (this.attachedElement) {
  45780. input.attachControl(this.attachedElement, this.noPreventDefault);
  45781. }
  45782. };
  45783. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45784. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45785. if (this.attachedElement) {
  45786. return;
  45787. }
  45788. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45789. this.attachedElement = element;
  45790. this.noPreventDefault = noPreventDefault;
  45791. for (var cam in this.attached) {
  45792. this.attached[cam].attachControl(element, noPreventDefault);
  45793. }
  45794. };
  45795. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45796. if (disconnect === void 0) { disconnect = false; }
  45797. if (this.attachedElement !== element) {
  45798. return;
  45799. }
  45800. for (var cam in this.attached) {
  45801. this.attached[cam].detachControl(element);
  45802. if (disconnect) {
  45803. this.attached[cam].camera = null;
  45804. }
  45805. }
  45806. this.attachedElement = null;
  45807. };
  45808. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45809. this.checkInputs = function () { };
  45810. for (var cam in this.attached) {
  45811. var input = this.attached[cam];
  45812. if (input.checkInputs) {
  45813. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45814. }
  45815. }
  45816. };
  45817. /**
  45818. * Remove all attached input methods from a camera
  45819. */
  45820. CameraInputsManager.prototype.clear = function () {
  45821. if (this.attachedElement) {
  45822. this.detachElement(this.attachedElement, true);
  45823. }
  45824. this.attached = {};
  45825. this.attachedElement = null;
  45826. this.checkInputs = function () { };
  45827. };
  45828. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45829. var inputs = {};
  45830. for (var cam in this.attached) {
  45831. var input = this.attached[cam];
  45832. var res = BABYLON.SerializationHelper.Serialize(input);
  45833. inputs[input.getClassName()] = res;
  45834. }
  45835. serializedCamera.inputsmgr = inputs;
  45836. };
  45837. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45838. var parsedInputs = parsedCamera.inputsmgr;
  45839. if (parsedInputs) {
  45840. this.clear();
  45841. for (var n in parsedInputs) {
  45842. var construct = BABYLON.CameraInputTypes[n];
  45843. if (construct) {
  45844. var parsedinput = parsedInputs[n];
  45845. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45846. this.add(input);
  45847. }
  45848. }
  45849. }
  45850. else {
  45851. //2016-03-08 this part is for managing backward compatibility
  45852. for (var n in this.attached) {
  45853. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45854. if (construct) {
  45855. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45856. this.remove(this.attached[n]);
  45857. this.add(input);
  45858. }
  45859. }
  45860. }
  45861. };
  45862. return CameraInputsManager;
  45863. }());
  45864. BABYLON.CameraInputsManager = CameraInputsManager;
  45865. })(BABYLON || (BABYLON = {}));
  45866. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45867. var BABYLON;
  45868. (function (BABYLON) {
  45869. var TargetCamera = /** @class */ (function (_super) {
  45870. __extends(TargetCamera, _super);
  45871. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  45872. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  45873. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  45874. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45875. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45876. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45877. _this.speed = 2.0;
  45878. _this.noRotationConstraint = false;
  45879. _this.lockedTarget = null;
  45880. /** @hidden */
  45881. _this._currentTarget = BABYLON.Vector3.Zero();
  45882. /** @hidden */
  45883. _this._viewMatrix = BABYLON.Matrix.Zero();
  45884. /** @hidden */
  45885. _this._camMatrix = BABYLON.Matrix.Zero();
  45886. /** @hidden */
  45887. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45888. /** @hidden */
  45889. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45890. /** @hidden */
  45891. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45892. /** @hidden */
  45893. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45894. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  45895. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  45896. _this._defaultUp = BABYLON.Vector3.Up();
  45897. _this._cachedRotationZ = 0;
  45898. return _this;
  45899. }
  45900. TargetCamera.prototype.getFrontPosition = function (distance) {
  45901. this.getWorldMatrix();
  45902. var direction = this.getTarget().subtract(this.position);
  45903. direction.normalize();
  45904. direction.scaleInPlace(distance);
  45905. return this.globalPosition.add(direction);
  45906. };
  45907. /** @hidden */
  45908. TargetCamera.prototype._getLockedTargetPosition = function () {
  45909. if (!this.lockedTarget) {
  45910. return null;
  45911. }
  45912. if (this.lockedTarget.absolutePosition) {
  45913. this.lockedTarget.computeWorldMatrix();
  45914. }
  45915. return this.lockedTarget.absolutePosition || this.lockedTarget;
  45916. };
  45917. TargetCamera.prototype.storeState = function () {
  45918. this._storedPosition = this.position.clone();
  45919. this._storedRotation = this.rotation.clone();
  45920. if (this.rotationQuaternion) {
  45921. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  45922. }
  45923. return _super.prototype.storeState.call(this);
  45924. };
  45925. /**
  45926. * Restored camera state. You must call storeState() first
  45927. * @returns whether it was successful or not
  45928. * @hidden
  45929. */
  45930. TargetCamera.prototype._restoreStateValues = function () {
  45931. if (!_super.prototype._restoreStateValues.call(this)) {
  45932. return false;
  45933. }
  45934. this.position = this._storedPosition.clone();
  45935. this.rotation = this._storedRotation.clone();
  45936. if (this.rotationQuaternion) {
  45937. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45938. }
  45939. this.cameraDirection.copyFromFloats(0, 0, 0);
  45940. this.cameraRotation.copyFromFloats(0, 0);
  45941. return true;
  45942. };
  45943. // Cache
  45944. /** @hidden */
  45945. TargetCamera.prototype._initCache = function () {
  45946. _super.prototype._initCache.call(this);
  45947. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45948. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45949. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45950. };
  45951. /** @hidden */
  45952. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  45953. if (!ignoreParentClass) {
  45954. _super.prototype._updateCache.call(this);
  45955. }
  45956. var lockedTargetPosition = this._getLockedTargetPosition();
  45957. if (!lockedTargetPosition) {
  45958. this._cache.lockedTarget = null;
  45959. }
  45960. else {
  45961. if (!this._cache.lockedTarget) {
  45962. this._cache.lockedTarget = lockedTargetPosition.clone();
  45963. }
  45964. else {
  45965. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  45966. }
  45967. }
  45968. this._cache.rotation.copyFrom(this.rotation);
  45969. if (this.rotationQuaternion)
  45970. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45971. };
  45972. // Synchronized
  45973. /** @hidden */
  45974. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  45975. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  45976. return false;
  45977. }
  45978. var lockedTargetPosition = this._getLockedTargetPosition();
  45979. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  45980. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  45981. };
  45982. // Methods
  45983. /** @hidden */
  45984. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  45985. var engine = this.getEngine();
  45986. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  45987. };
  45988. // Target
  45989. /** @hidden */
  45990. TargetCamera.prototype.setTarget = function (target) {
  45991. this.upVector.normalize();
  45992. if (this.position.z === target.z) {
  45993. this.position.z += BABYLON.Epsilon;
  45994. }
  45995. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  45996. this._camMatrix.invert();
  45997. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  45998. var vDir = target.subtract(this.position);
  45999. if (vDir.x >= 0.0) {
  46000. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46001. }
  46002. else {
  46003. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46004. }
  46005. this.rotation.z = 0;
  46006. if (isNaN(this.rotation.x)) {
  46007. this.rotation.x = 0;
  46008. }
  46009. if (isNaN(this.rotation.y)) {
  46010. this.rotation.y = 0;
  46011. }
  46012. if (isNaN(this.rotation.z)) {
  46013. this.rotation.z = 0;
  46014. }
  46015. if (this.rotationQuaternion) {
  46016. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46017. }
  46018. };
  46019. /**
  46020. * Return the current target position of the camera. This value is expressed in local space.
  46021. */
  46022. TargetCamera.prototype.getTarget = function () {
  46023. return this._currentTarget;
  46024. };
  46025. /** @hidden */
  46026. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46027. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46028. };
  46029. /** @hidden */
  46030. TargetCamera.prototype._updatePosition = function () {
  46031. if (this.parent) {
  46032. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46033. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46034. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46035. return;
  46036. }
  46037. this.position.addInPlace(this.cameraDirection);
  46038. };
  46039. /** @hidden */
  46040. TargetCamera.prototype._checkInputs = function () {
  46041. var needToMove = this._decideIfNeedsToMove();
  46042. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46043. // Move
  46044. if (needToMove) {
  46045. this._updatePosition();
  46046. }
  46047. // Rotate
  46048. if (needToRotate) {
  46049. this.rotation.x += this.cameraRotation.x;
  46050. this.rotation.y += this.cameraRotation.y;
  46051. //rotate, if quaternion is set and rotation was used
  46052. if (this.rotationQuaternion) {
  46053. var len = this.rotation.lengthSquared();
  46054. if (len) {
  46055. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46056. }
  46057. }
  46058. if (!this.noRotationConstraint) {
  46059. var limit = (Math.PI / 2) * 0.95;
  46060. if (this.rotation.x > limit)
  46061. this.rotation.x = limit;
  46062. if (this.rotation.x < -limit)
  46063. this.rotation.x = -limit;
  46064. }
  46065. }
  46066. // Inertia
  46067. if (needToMove) {
  46068. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46069. this.cameraDirection.x = 0;
  46070. }
  46071. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46072. this.cameraDirection.y = 0;
  46073. }
  46074. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46075. this.cameraDirection.z = 0;
  46076. }
  46077. this.cameraDirection.scaleInPlace(this.inertia);
  46078. }
  46079. if (needToRotate) {
  46080. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46081. this.cameraRotation.x = 0;
  46082. }
  46083. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46084. this.cameraRotation.y = 0;
  46085. }
  46086. this.cameraRotation.scaleInPlace(this.inertia);
  46087. }
  46088. _super.prototype._checkInputs.call(this);
  46089. };
  46090. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46091. if (this.rotationQuaternion) {
  46092. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46093. }
  46094. else {
  46095. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46096. }
  46097. };
  46098. /**
  46099. * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)
  46100. * @returns the current camera
  46101. */
  46102. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46103. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46104. return this;
  46105. };
  46106. /** @hidden */
  46107. TargetCamera.prototype._getViewMatrix = function () {
  46108. if (this.lockedTarget) {
  46109. this.setTarget(this._getLockedTargetPosition());
  46110. }
  46111. // Compute
  46112. this._updateCameraRotationMatrix();
  46113. // Apply the changed rotation to the upVector.
  46114. if (this._cachedRotationZ != this.rotation.z) {
  46115. this._rotateUpVectorWithCameraRotationMatrix();
  46116. this._cachedRotationZ = this.rotation.z;
  46117. }
  46118. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46119. // Computing target and final matrix
  46120. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46121. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46122. return this._viewMatrix;
  46123. };
  46124. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46125. if (this.parent) {
  46126. var parentWorldMatrix = this.parent.getWorldMatrix();
  46127. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46128. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46129. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46130. this._markSyncedWithParent();
  46131. }
  46132. else {
  46133. this._globalPosition.copyFrom(position);
  46134. this._globalCurrentTarget.copyFrom(target);
  46135. this._globalCurrentUpVector.copyFrom(up);
  46136. }
  46137. if (this.getScene().useRightHandedSystem) {
  46138. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46139. }
  46140. else {
  46141. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46142. }
  46143. };
  46144. /**
  46145. * @override
  46146. * Override Camera.createRigCamera
  46147. */
  46148. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46149. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46150. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46151. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46152. if (!this.rotationQuaternion) {
  46153. this.rotationQuaternion = new BABYLON.Quaternion();
  46154. }
  46155. rigCamera._cameraRigParams = {};
  46156. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46157. }
  46158. return rigCamera;
  46159. }
  46160. return null;
  46161. };
  46162. /**
  46163. * @hidden
  46164. * @override
  46165. * Override Camera._updateRigCameras
  46166. */
  46167. TargetCamera.prototype._updateRigCameras = function () {
  46168. var camLeft = this._rigCameras[0];
  46169. var camRight = this._rigCameras[1];
  46170. switch (this.cameraRigMode) {
  46171. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46172. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46173. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46174. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46175. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46176. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46177. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46178. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46179. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46180. camLeft.setTarget(this.getTarget());
  46181. camRight.setTarget(this.getTarget());
  46182. break;
  46183. case BABYLON.Camera.RIG_MODE_VR:
  46184. if (camLeft.rotationQuaternion) {
  46185. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46186. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46187. }
  46188. else {
  46189. camLeft.rotation.copyFrom(this.rotation);
  46190. camRight.rotation.copyFrom(this.rotation);
  46191. }
  46192. camLeft.position.copyFrom(this.position);
  46193. camRight.position.copyFrom(this.position);
  46194. break;
  46195. }
  46196. _super.prototype._updateRigCameras.call(this);
  46197. };
  46198. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46199. if (!this._rigCamTransformMatrix) {
  46200. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46201. }
  46202. var target = this.getTarget();
  46203. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46204. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46205. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46206. };
  46207. TargetCamera.prototype.getClassName = function () {
  46208. return "TargetCamera";
  46209. };
  46210. __decorate([
  46211. BABYLON.serializeAsVector3()
  46212. ], TargetCamera.prototype, "rotation", void 0);
  46213. __decorate([
  46214. BABYLON.serialize()
  46215. ], TargetCamera.prototype, "speed", void 0);
  46216. __decorate([
  46217. BABYLON.serializeAsMeshReference("lockedTargetId")
  46218. ], TargetCamera.prototype, "lockedTarget", void 0);
  46219. return TargetCamera;
  46220. }(BABYLON.Camera));
  46221. BABYLON.TargetCamera = TargetCamera;
  46222. })(BABYLON || (BABYLON = {}));
  46223. //# sourceMappingURL=babylon.targetCamera.js.map
  46224. var BABYLON;
  46225. (function (BABYLON) {
  46226. var FreeCameraMouseInput = /** @class */ (function () {
  46227. function FreeCameraMouseInput(touchEnabled) {
  46228. if (touchEnabled === void 0) { touchEnabled = true; }
  46229. this.touchEnabled = touchEnabled;
  46230. this.buttons = [0, 1, 2];
  46231. this.angularSensibility = 2000.0;
  46232. this.previousPosition = null;
  46233. }
  46234. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46235. var _this = this;
  46236. var engine = this.camera.getEngine();
  46237. if (!this._pointerInput) {
  46238. this._pointerInput = function (p, s) {
  46239. var evt = p.event;
  46240. if (engine.isInVRExclusivePointerMode) {
  46241. return;
  46242. }
  46243. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46244. return;
  46245. }
  46246. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46247. return;
  46248. }
  46249. var srcElement = (evt.srcElement || evt.target);
  46250. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46251. try {
  46252. srcElement.setPointerCapture(evt.pointerId);
  46253. }
  46254. catch (e) {
  46255. //Nothing to do with the error. Execution will continue.
  46256. }
  46257. _this.previousPosition = {
  46258. x: evt.clientX,
  46259. y: evt.clientY
  46260. };
  46261. if (!noPreventDefault) {
  46262. evt.preventDefault();
  46263. element.focus();
  46264. }
  46265. }
  46266. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46267. try {
  46268. srcElement.releasePointerCapture(evt.pointerId);
  46269. }
  46270. catch (e) {
  46271. //Nothing to do with the error.
  46272. }
  46273. _this.previousPosition = null;
  46274. if (!noPreventDefault) {
  46275. evt.preventDefault();
  46276. }
  46277. }
  46278. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46279. if (!_this.previousPosition || engine.isPointerLock) {
  46280. return;
  46281. }
  46282. var offsetX = evt.clientX - _this.previousPosition.x;
  46283. if (_this.camera.getScene().useRightHandedSystem)
  46284. offsetX *= -1;
  46285. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46286. offsetX *= -1;
  46287. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46288. var offsetY = evt.clientY - _this.previousPosition.y;
  46289. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46290. _this.previousPosition = {
  46291. x: evt.clientX,
  46292. y: evt.clientY
  46293. };
  46294. if (!noPreventDefault) {
  46295. evt.preventDefault();
  46296. }
  46297. }
  46298. };
  46299. }
  46300. this._onMouseMove = function (evt) {
  46301. if (!engine.isPointerLock) {
  46302. return;
  46303. }
  46304. if (engine.isInVRExclusivePointerMode) {
  46305. return;
  46306. }
  46307. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46308. if (_this.camera.getScene().useRightHandedSystem)
  46309. offsetX *= -1;
  46310. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46311. offsetX *= -1;
  46312. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46313. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46314. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46315. _this.previousPosition = null;
  46316. if (!noPreventDefault) {
  46317. evt.preventDefault();
  46318. }
  46319. };
  46320. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46321. element.addEventListener("mousemove", this._onMouseMove, false);
  46322. };
  46323. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46324. if (this._observer && element) {
  46325. this.camera.getScene().onPointerObservable.remove(this._observer);
  46326. if (this._onMouseMove) {
  46327. element.removeEventListener("mousemove", this._onMouseMove);
  46328. }
  46329. this._observer = null;
  46330. this._onMouseMove = null;
  46331. this.previousPosition = null;
  46332. }
  46333. };
  46334. FreeCameraMouseInput.prototype.getClassName = function () {
  46335. return "FreeCameraMouseInput";
  46336. };
  46337. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46338. return "mouse";
  46339. };
  46340. __decorate([
  46341. BABYLON.serialize()
  46342. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46343. __decorate([
  46344. BABYLON.serialize()
  46345. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46346. return FreeCameraMouseInput;
  46347. }());
  46348. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46349. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46350. })(BABYLON || (BABYLON = {}));
  46351. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46352. var BABYLON;
  46353. (function (BABYLON) {
  46354. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46355. function FreeCameraKeyboardMoveInput() {
  46356. this._keys = new Array();
  46357. this.keysUp = [38];
  46358. this.keysDown = [40];
  46359. this.keysLeft = [37];
  46360. this.keysRight = [39];
  46361. }
  46362. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46363. var _this = this;
  46364. if (this._onCanvasBlurObserver) {
  46365. return;
  46366. }
  46367. this._scene = this.camera.getScene();
  46368. this._engine = this._scene.getEngine();
  46369. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46370. _this._keys = [];
  46371. });
  46372. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46373. var evt = info.event;
  46374. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46375. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46376. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46377. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46378. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46379. var index = _this._keys.indexOf(evt.keyCode);
  46380. if (index === -1) {
  46381. _this._keys.push(evt.keyCode);
  46382. }
  46383. if (!noPreventDefault) {
  46384. evt.preventDefault();
  46385. }
  46386. }
  46387. }
  46388. else {
  46389. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46390. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46391. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46392. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46393. var index = _this._keys.indexOf(evt.keyCode);
  46394. if (index >= 0) {
  46395. _this._keys.splice(index, 1);
  46396. }
  46397. if (!noPreventDefault) {
  46398. evt.preventDefault();
  46399. }
  46400. }
  46401. }
  46402. });
  46403. };
  46404. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46405. if (this._scene) {
  46406. if (this._onKeyboardObserver) {
  46407. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46408. }
  46409. if (this._onCanvasBlurObserver) {
  46410. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46411. }
  46412. this._onKeyboardObserver = null;
  46413. this._onCanvasBlurObserver = null;
  46414. }
  46415. this._keys = [];
  46416. };
  46417. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46418. if (this._onKeyboardObserver) {
  46419. var camera = this.camera;
  46420. // Keyboard
  46421. for (var index = 0; index < this._keys.length; index++) {
  46422. var keyCode = this._keys[index];
  46423. var speed = camera._computeLocalCameraSpeed();
  46424. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46425. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46426. }
  46427. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46428. camera._localDirection.copyFromFloats(0, 0, speed);
  46429. }
  46430. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46431. camera._localDirection.copyFromFloats(speed, 0, 0);
  46432. }
  46433. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46434. camera._localDirection.copyFromFloats(0, 0, -speed);
  46435. }
  46436. if (camera.getScene().useRightHandedSystem) {
  46437. camera._localDirection.z *= -1;
  46438. }
  46439. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46440. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46441. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46442. }
  46443. }
  46444. };
  46445. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46446. return "FreeCameraKeyboardMoveInput";
  46447. };
  46448. /** @hidden */
  46449. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46450. this._keys = [];
  46451. };
  46452. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46453. return "keyboard";
  46454. };
  46455. __decorate([
  46456. BABYLON.serialize()
  46457. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46458. __decorate([
  46459. BABYLON.serialize()
  46460. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46461. __decorate([
  46462. BABYLON.serialize()
  46463. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46464. __decorate([
  46465. BABYLON.serialize()
  46466. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46467. return FreeCameraKeyboardMoveInput;
  46468. }());
  46469. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46470. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46471. })(BABYLON || (BABYLON = {}));
  46472. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46473. var BABYLON;
  46474. (function (BABYLON) {
  46475. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46476. __extends(FreeCameraInputsManager, _super);
  46477. function FreeCameraInputsManager(camera) {
  46478. return _super.call(this, camera) || this;
  46479. }
  46480. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46481. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46482. return this;
  46483. };
  46484. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46485. if (touchEnabled === void 0) { touchEnabled = true; }
  46486. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46487. return this;
  46488. };
  46489. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46490. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46491. return this;
  46492. };
  46493. FreeCameraInputsManager.prototype.addTouch = function () {
  46494. this.add(new BABYLON.FreeCameraTouchInput());
  46495. return this;
  46496. };
  46497. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46498. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46499. return this;
  46500. };
  46501. return FreeCameraInputsManager;
  46502. }(BABYLON.CameraInputsManager));
  46503. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46504. })(BABYLON || (BABYLON = {}));
  46505. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46506. var BABYLON;
  46507. (function (BABYLON) {
  46508. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46509. // Forcing to use the Universal camera
  46510. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46511. });
  46512. var FreeCamera = /** @class */ (function (_super) {
  46513. __extends(FreeCamera, _super);
  46514. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46515. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46516. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46517. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46518. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46519. _this.checkCollisions = false;
  46520. _this.applyGravity = false;
  46521. _this._needMoveForGravity = false;
  46522. _this._oldPosition = BABYLON.Vector3.Zero();
  46523. _this._diffPosition = BABYLON.Vector3.Zero();
  46524. _this._newPosition = BABYLON.Vector3.Zero();
  46525. // Collisions
  46526. _this._collisionMask = -1;
  46527. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46528. if (collidedMesh === void 0) { collidedMesh = null; }
  46529. //TODO move this to the collision coordinator!
  46530. if (_this.getScene().workerCollisions)
  46531. newPosition.multiplyInPlace(_this._collider._radius);
  46532. var updatePosition = function (newPos) {
  46533. _this._newPosition.copyFrom(newPos);
  46534. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46535. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46536. _this.position.addInPlace(_this._diffPosition);
  46537. if (_this.onCollide && collidedMesh) {
  46538. _this.onCollide(collidedMesh);
  46539. }
  46540. }
  46541. };
  46542. updatePosition(newPosition);
  46543. };
  46544. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46545. _this.inputs.addKeyboard().addMouse();
  46546. return _this;
  46547. }
  46548. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46549. //-- begin properties for backward compatibility for inputs
  46550. /**
  46551. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46552. * Higher values reduce sensitivity.
  46553. */
  46554. get: function () {
  46555. var mouse = this.inputs.attached["mouse"];
  46556. if (mouse)
  46557. return mouse.angularSensibility;
  46558. return 0;
  46559. },
  46560. /**
  46561. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46562. * Higher values reduce sensitivity.
  46563. */
  46564. set: function (value) {
  46565. var mouse = this.inputs.attached["mouse"];
  46566. if (mouse)
  46567. mouse.angularSensibility = value;
  46568. },
  46569. enumerable: true,
  46570. configurable: true
  46571. });
  46572. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46573. get: function () {
  46574. var keyboard = this.inputs.attached["keyboard"];
  46575. if (keyboard)
  46576. return keyboard.keysUp;
  46577. return [];
  46578. },
  46579. set: function (value) {
  46580. var keyboard = this.inputs.attached["keyboard"];
  46581. if (keyboard)
  46582. keyboard.keysUp = value;
  46583. },
  46584. enumerable: true,
  46585. configurable: true
  46586. });
  46587. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46588. get: function () {
  46589. var keyboard = this.inputs.attached["keyboard"];
  46590. if (keyboard)
  46591. return keyboard.keysDown;
  46592. return [];
  46593. },
  46594. set: function (value) {
  46595. var keyboard = this.inputs.attached["keyboard"];
  46596. if (keyboard)
  46597. keyboard.keysDown = value;
  46598. },
  46599. enumerable: true,
  46600. configurable: true
  46601. });
  46602. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46603. get: function () {
  46604. var keyboard = this.inputs.attached["keyboard"];
  46605. if (keyboard)
  46606. return keyboard.keysLeft;
  46607. return [];
  46608. },
  46609. set: function (value) {
  46610. var keyboard = this.inputs.attached["keyboard"];
  46611. if (keyboard)
  46612. keyboard.keysLeft = value;
  46613. },
  46614. enumerable: true,
  46615. configurable: true
  46616. });
  46617. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46618. get: function () {
  46619. var keyboard = this.inputs.attached["keyboard"];
  46620. if (keyboard)
  46621. return keyboard.keysRight;
  46622. return [];
  46623. },
  46624. set: function (value) {
  46625. var keyboard = this.inputs.attached["keyboard"];
  46626. if (keyboard)
  46627. keyboard.keysRight = value;
  46628. },
  46629. enumerable: true,
  46630. configurable: true
  46631. });
  46632. // Controls
  46633. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46634. this.inputs.attachElement(element, noPreventDefault);
  46635. };
  46636. FreeCamera.prototype.detachControl = function (element) {
  46637. this.inputs.detachElement(element);
  46638. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46639. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46640. };
  46641. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46642. get: function () {
  46643. return this._collisionMask;
  46644. },
  46645. set: function (mask) {
  46646. this._collisionMask = !isNaN(mask) ? mask : -1;
  46647. },
  46648. enumerable: true,
  46649. configurable: true
  46650. });
  46651. /** @hidden */
  46652. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46653. var globalPosition;
  46654. if (this.parent) {
  46655. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46656. }
  46657. else {
  46658. globalPosition = this.position;
  46659. }
  46660. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46661. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46662. if (!this._collider) {
  46663. this._collider = new BABYLON.Collider();
  46664. }
  46665. this._collider._radius = this.ellipsoid;
  46666. this._collider.collisionMask = this._collisionMask;
  46667. //no need for clone, as long as gravity is not on.
  46668. var actualDisplacement = displacement;
  46669. //add gravity to the direction to prevent the dual-collision checking
  46670. if (this.applyGravity) {
  46671. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46672. actualDisplacement = displacement.add(this.getScene().gravity);
  46673. }
  46674. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46675. };
  46676. /** @hidden */
  46677. FreeCamera.prototype._checkInputs = function () {
  46678. if (!this._localDirection) {
  46679. this._localDirection = BABYLON.Vector3.Zero();
  46680. this._transformedDirection = BABYLON.Vector3.Zero();
  46681. }
  46682. this.inputs.checkInputs();
  46683. _super.prototype._checkInputs.call(this);
  46684. };
  46685. /** @hidden */
  46686. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46687. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46688. };
  46689. /** @hidden */
  46690. FreeCamera.prototype._updatePosition = function () {
  46691. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46692. this._collideWithWorld(this.cameraDirection);
  46693. }
  46694. else {
  46695. _super.prototype._updatePosition.call(this);
  46696. }
  46697. };
  46698. FreeCamera.prototype.dispose = function () {
  46699. this.inputs.clear();
  46700. _super.prototype.dispose.call(this);
  46701. };
  46702. FreeCamera.prototype.getClassName = function () {
  46703. return "FreeCamera";
  46704. };
  46705. __decorate([
  46706. BABYLON.serializeAsVector3()
  46707. ], FreeCamera.prototype, "ellipsoid", void 0);
  46708. __decorate([
  46709. BABYLON.serializeAsVector3()
  46710. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46711. __decorate([
  46712. BABYLON.serialize()
  46713. ], FreeCamera.prototype, "checkCollisions", void 0);
  46714. __decorate([
  46715. BABYLON.serialize()
  46716. ], FreeCamera.prototype, "applyGravity", void 0);
  46717. return FreeCamera;
  46718. }(BABYLON.TargetCamera));
  46719. BABYLON.FreeCamera = FreeCamera;
  46720. })(BABYLON || (BABYLON = {}));
  46721. //# sourceMappingURL=babylon.freeCamera.js.map
  46722. var BABYLON;
  46723. (function (BABYLON) {
  46724. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46725. function ArcRotateCameraKeyboardMoveInput() {
  46726. this._keys = new Array();
  46727. this.keysUp = [38];
  46728. this.keysDown = [40];
  46729. this.keysLeft = [37];
  46730. this.keysRight = [39];
  46731. this.keysReset = [220];
  46732. this.panningSensibility = 50.0;
  46733. this.zoomingSensibility = 25.0;
  46734. this.useAltToZoom = true;
  46735. }
  46736. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46737. var _this = this;
  46738. if (this._onCanvasBlurObserver) {
  46739. return;
  46740. }
  46741. this._scene = this.camera.getScene();
  46742. this._engine = this._scene.getEngine();
  46743. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46744. _this._keys = [];
  46745. });
  46746. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46747. var evt = info.event;
  46748. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46749. _this._ctrlPressed = evt.ctrlKey;
  46750. _this._altPressed = evt.altKey;
  46751. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46752. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46753. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46754. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46755. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46756. var index = _this._keys.indexOf(evt.keyCode);
  46757. if (index === -1) {
  46758. _this._keys.push(evt.keyCode);
  46759. }
  46760. if (evt.preventDefault) {
  46761. if (!noPreventDefault) {
  46762. evt.preventDefault();
  46763. }
  46764. }
  46765. }
  46766. }
  46767. else {
  46768. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46769. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46770. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46771. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46772. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46773. var index = _this._keys.indexOf(evt.keyCode);
  46774. if (index >= 0) {
  46775. _this._keys.splice(index, 1);
  46776. }
  46777. if (evt.preventDefault) {
  46778. if (!noPreventDefault) {
  46779. evt.preventDefault();
  46780. }
  46781. }
  46782. }
  46783. }
  46784. });
  46785. };
  46786. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46787. if (this._scene) {
  46788. if (this._onKeyboardObserver) {
  46789. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46790. }
  46791. if (this._onCanvasBlurObserver) {
  46792. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46793. }
  46794. this._onKeyboardObserver = null;
  46795. this._onCanvasBlurObserver = null;
  46796. }
  46797. this._keys = [];
  46798. };
  46799. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46800. if (this._onKeyboardObserver) {
  46801. var camera = this.camera;
  46802. for (var index = 0; index < this._keys.length; index++) {
  46803. var keyCode = this._keys[index];
  46804. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46805. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46806. camera.inertialPanningX -= 1 / this.panningSensibility;
  46807. }
  46808. else {
  46809. camera.inertialAlphaOffset -= 0.01;
  46810. }
  46811. }
  46812. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46813. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46814. camera.inertialPanningY += 1 / this.panningSensibility;
  46815. }
  46816. else if (this._altPressed && this.useAltToZoom) {
  46817. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46818. }
  46819. else {
  46820. camera.inertialBetaOffset -= 0.01;
  46821. }
  46822. }
  46823. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46824. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46825. camera.inertialPanningX += 1 / this.panningSensibility;
  46826. }
  46827. else {
  46828. camera.inertialAlphaOffset += 0.01;
  46829. }
  46830. }
  46831. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46832. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46833. camera.inertialPanningY -= 1 / this.panningSensibility;
  46834. }
  46835. else if (this._altPressed && this.useAltToZoom) {
  46836. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46837. }
  46838. else {
  46839. camera.inertialBetaOffset += 0.01;
  46840. }
  46841. }
  46842. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46843. camera.restoreState();
  46844. }
  46845. }
  46846. }
  46847. };
  46848. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46849. return "ArcRotateCameraKeyboardMoveInput";
  46850. };
  46851. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46852. return "keyboard";
  46853. };
  46854. __decorate([
  46855. BABYLON.serialize()
  46856. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46857. __decorate([
  46858. BABYLON.serialize()
  46859. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46860. __decorate([
  46861. BABYLON.serialize()
  46862. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46863. __decorate([
  46864. BABYLON.serialize()
  46865. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46866. __decorate([
  46867. BABYLON.serialize()
  46868. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46869. __decorate([
  46870. BABYLON.serialize()
  46871. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46872. __decorate([
  46873. BABYLON.serialize()
  46874. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46875. __decorate([
  46876. BABYLON.serialize()
  46877. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46878. return ArcRotateCameraKeyboardMoveInput;
  46879. }());
  46880. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46881. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46882. })(BABYLON || (BABYLON = {}));
  46883. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46884. var BABYLON;
  46885. (function (BABYLON) {
  46886. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46887. function ArcRotateCameraMouseWheelInput() {
  46888. this.wheelPrecision = 3.0;
  46889. /**
  46890. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46891. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46892. */
  46893. this.wheelDeltaPercentage = 0;
  46894. }
  46895. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46896. var _this = this;
  46897. this._wheel = function (p, s) {
  46898. //sanity check - this should be a PointerWheel event.
  46899. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46900. return;
  46901. var event = p.event;
  46902. var delta = 0;
  46903. if (event.wheelDelta) {
  46904. if (_this.wheelDeltaPercentage) {
  46905. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46906. if (event.wheelDelta > 0) {
  46907. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46908. }
  46909. else {
  46910. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46911. }
  46912. }
  46913. else {
  46914. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46915. }
  46916. }
  46917. else if (event.detail) {
  46918. delta = -event.detail / _this.wheelPrecision;
  46919. }
  46920. if (delta)
  46921. _this.camera.inertialRadiusOffset += delta;
  46922. if (event.preventDefault) {
  46923. if (!noPreventDefault) {
  46924. event.preventDefault();
  46925. }
  46926. }
  46927. };
  46928. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46929. };
  46930. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46931. if (this._observer && element) {
  46932. this.camera.getScene().onPointerObservable.remove(this._observer);
  46933. this._observer = null;
  46934. this._wheel = null;
  46935. }
  46936. };
  46937. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46938. return "ArcRotateCameraMouseWheelInput";
  46939. };
  46940. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46941. return "mousewheel";
  46942. };
  46943. __decorate([
  46944. BABYLON.serialize()
  46945. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  46946. __decorate([
  46947. BABYLON.serialize()
  46948. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  46949. return ArcRotateCameraMouseWheelInput;
  46950. }());
  46951. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  46952. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  46953. })(BABYLON || (BABYLON = {}));
  46954. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  46955. var BABYLON;
  46956. (function (BABYLON) {
  46957. var ArcRotateCameraPointersInput = /** @class */ (function () {
  46958. function ArcRotateCameraPointersInput() {
  46959. this.buttons = [0, 1, 2];
  46960. this.angularSensibilityX = 1000.0;
  46961. this.angularSensibilityY = 1000.0;
  46962. this.pinchPrecision = 12.0;
  46963. /**
  46964. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  46965. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  46966. */
  46967. this.pinchDeltaPercentage = 0;
  46968. this.panningSensibility = 1000.0;
  46969. this.multiTouchPanning = true;
  46970. this.multiTouchPanAndZoom = true;
  46971. this._isPanClick = false;
  46972. this.pinchInwards = true;
  46973. }
  46974. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  46975. var _this = this;
  46976. var engine = this.camera.getEngine();
  46977. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  46978. var pointA = null;
  46979. var pointB = null;
  46980. var previousPinchSquaredDistance = 0;
  46981. var initialDistance = 0;
  46982. var twoFingerActivityCount = 0;
  46983. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  46984. this._pointerInput = function (p, s) {
  46985. var evt = p.event;
  46986. var isTouch = p.event.pointerType === "touch";
  46987. if (engine.isInVRExclusivePointerMode) {
  46988. return;
  46989. }
  46990. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46991. return;
  46992. }
  46993. var srcElement = (evt.srcElement || evt.target);
  46994. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46995. try {
  46996. srcElement.setPointerCapture(evt.pointerId);
  46997. }
  46998. catch (e) {
  46999. //Nothing to do with the error. Execution will continue.
  47000. }
  47001. // Manage panning with pan button click
  47002. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47003. // manage pointers
  47004. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47005. if (pointA === null) {
  47006. pointA = cacheSoloPointer;
  47007. }
  47008. else if (pointB === null) {
  47009. pointB = cacheSoloPointer;
  47010. }
  47011. if (!noPreventDefault) {
  47012. evt.preventDefault();
  47013. element.focus();
  47014. }
  47015. }
  47016. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47017. _this.camera.restoreState();
  47018. }
  47019. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47020. try {
  47021. srcElement.releasePointerCapture(evt.pointerId);
  47022. }
  47023. catch (e) {
  47024. //Nothing to do with the error.
  47025. }
  47026. cacheSoloPointer = null;
  47027. previousPinchSquaredDistance = 0;
  47028. previousMultiTouchPanPosition.isPaning = false;
  47029. previousMultiTouchPanPosition.isPinching = false;
  47030. twoFingerActivityCount = 0;
  47031. initialDistance = 0;
  47032. if (!isTouch) {
  47033. pointB = null; // Mouse and pen are mono pointer
  47034. }
  47035. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47036. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47037. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47038. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47039. if (engine._badOS) {
  47040. pointA = pointB = null;
  47041. }
  47042. else {
  47043. //only remove the impacted pointer in case of multitouch allowing on most
  47044. //platforms switching from rotate to zoom and pan seamlessly.
  47045. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47046. pointA = pointB;
  47047. pointB = null;
  47048. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47049. }
  47050. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47051. pointB = null;
  47052. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47053. }
  47054. else {
  47055. pointA = pointB = null;
  47056. }
  47057. }
  47058. if (!noPreventDefault) {
  47059. evt.preventDefault();
  47060. }
  47061. }
  47062. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47063. if (!noPreventDefault) {
  47064. evt.preventDefault();
  47065. }
  47066. // One button down
  47067. if (pointA && pointB === null && cacheSoloPointer) {
  47068. if (_this.panningSensibility !== 0 &&
  47069. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47070. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47071. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47072. }
  47073. else {
  47074. var offsetX = evt.clientX - cacheSoloPointer.x;
  47075. var offsetY = evt.clientY - cacheSoloPointer.y;
  47076. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47077. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47078. }
  47079. cacheSoloPointer.x = evt.clientX;
  47080. cacheSoloPointer.y = evt.clientY;
  47081. }
  47082. // Two buttons down: pinch/pan
  47083. else if (pointA && pointB) {
  47084. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47085. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47086. ed.x = evt.clientX;
  47087. ed.y = evt.clientY;
  47088. var direction = _this.pinchInwards ? 1 : -1;
  47089. var distX = pointA.x - pointB.x;
  47090. var distY = pointA.y - pointB.y;
  47091. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47092. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47093. if (previousPinchSquaredDistance === 0) {
  47094. initialDistance = pinchDistance;
  47095. previousPinchSquaredDistance = pinchSquaredDistance;
  47096. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47097. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47098. return;
  47099. }
  47100. if (_this.multiTouchPanAndZoom) {
  47101. if (_this.pinchDeltaPercentage) {
  47102. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47103. }
  47104. else {
  47105. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47106. (_this.pinchPrecision *
  47107. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47108. direction);
  47109. }
  47110. if (_this.panningSensibility !== 0) {
  47111. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47112. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47113. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47114. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47115. previousMultiTouchPanPosition.x = pointersCenterX;
  47116. previousMultiTouchPanPosition.y = pointersCenterY;
  47117. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47118. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47119. }
  47120. }
  47121. else {
  47122. twoFingerActivityCount++;
  47123. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47124. if (_this.pinchDeltaPercentage) {
  47125. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47126. }
  47127. else {
  47128. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47129. (_this.pinchPrecision *
  47130. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47131. direction);
  47132. }
  47133. previousMultiTouchPanPosition.isPaning = false;
  47134. previousMultiTouchPanPosition.isPinching = true;
  47135. }
  47136. else {
  47137. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47138. if (!previousMultiTouchPanPosition.isPaning) {
  47139. previousMultiTouchPanPosition.isPaning = true;
  47140. previousMultiTouchPanPosition.isPinching = false;
  47141. previousMultiTouchPanPosition.x = ed.x;
  47142. previousMultiTouchPanPosition.y = ed.y;
  47143. return;
  47144. }
  47145. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47146. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47147. }
  47148. }
  47149. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47150. previousMultiTouchPanPosition.x = ed.x;
  47151. previousMultiTouchPanPosition.y = ed.y;
  47152. }
  47153. }
  47154. previousPinchSquaredDistance = pinchSquaredDistance;
  47155. }
  47156. }
  47157. };
  47158. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47159. this._onContextMenu = function (evt) {
  47160. evt.preventDefault();
  47161. };
  47162. if (!this.camera._useCtrlForPanning) {
  47163. element.addEventListener("contextmenu", this._onContextMenu, false);
  47164. }
  47165. this._onLostFocus = function () {
  47166. //this._keys = [];
  47167. pointA = pointB = null;
  47168. previousPinchSquaredDistance = 0;
  47169. previousMultiTouchPanPosition.isPaning = false;
  47170. previousMultiTouchPanPosition.isPinching = false;
  47171. twoFingerActivityCount = 0;
  47172. cacheSoloPointer = null;
  47173. initialDistance = 0;
  47174. };
  47175. this._onMouseMove = function (evt) {
  47176. if (!engine.isPointerLock) {
  47177. return;
  47178. }
  47179. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47180. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47181. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47182. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47183. if (!noPreventDefault) {
  47184. evt.preventDefault();
  47185. }
  47186. };
  47187. this._onGestureStart = function (e) {
  47188. if (window.MSGesture === undefined) {
  47189. return;
  47190. }
  47191. if (!_this._MSGestureHandler) {
  47192. _this._MSGestureHandler = new MSGesture();
  47193. _this._MSGestureHandler.target = element;
  47194. }
  47195. _this._MSGestureHandler.addPointer(e.pointerId);
  47196. };
  47197. this._onGesture = function (e) {
  47198. _this.camera.radius *= e.scale;
  47199. if (e.preventDefault) {
  47200. if (!noPreventDefault) {
  47201. e.stopPropagation();
  47202. e.preventDefault();
  47203. }
  47204. }
  47205. };
  47206. element.addEventListener("mousemove", this._onMouseMove, false);
  47207. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47208. element.addEventListener("MSGestureChange", this._onGesture, false);
  47209. BABYLON.Tools.RegisterTopRootEvents([
  47210. { name: "blur", handler: this._onLostFocus }
  47211. ]);
  47212. };
  47213. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47214. if (this._onLostFocus) {
  47215. BABYLON.Tools.UnregisterTopRootEvents([
  47216. { name: "blur", handler: this._onLostFocus }
  47217. ]);
  47218. }
  47219. if (element && this._observer) {
  47220. this.camera.getScene().onPointerObservable.remove(this._observer);
  47221. this._observer = null;
  47222. if (this._onContextMenu) {
  47223. element.removeEventListener("contextmenu", this._onContextMenu);
  47224. }
  47225. if (this._onMouseMove) {
  47226. element.removeEventListener("mousemove", this._onMouseMove);
  47227. }
  47228. if (this._onGestureStart) {
  47229. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47230. }
  47231. if (this._onGesture) {
  47232. element.removeEventListener("MSGestureChange", this._onGesture);
  47233. }
  47234. this._isPanClick = false;
  47235. this.pinchInwards = true;
  47236. this._onMouseMove = null;
  47237. this._onGestureStart = null;
  47238. this._onGesture = null;
  47239. this._MSGestureHandler = null;
  47240. this._onLostFocus = null;
  47241. this._onContextMenu = null;
  47242. }
  47243. };
  47244. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47245. return "ArcRotateCameraPointersInput";
  47246. };
  47247. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47248. return "pointers";
  47249. };
  47250. __decorate([
  47251. BABYLON.serialize()
  47252. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47253. __decorate([
  47254. BABYLON.serialize()
  47255. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47256. __decorate([
  47257. BABYLON.serialize()
  47258. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47259. __decorate([
  47260. BABYLON.serialize()
  47261. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47262. __decorate([
  47263. BABYLON.serialize()
  47264. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47265. __decorate([
  47266. BABYLON.serialize()
  47267. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47268. __decorate([
  47269. BABYLON.serialize()
  47270. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47271. __decorate([
  47272. BABYLON.serialize()
  47273. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47274. return ArcRotateCameraPointersInput;
  47275. }());
  47276. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47277. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47278. })(BABYLON || (BABYLON = {}));
  47279. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47280. var BABYLON;
  47281. (function (BABYLON) {
  47282. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47283. __extends(ArcRotateCameraInputsManager, _super);
  47284. function ArcRotateCameraInputsManager(camera) {
  47285. return _super.call(this, camera) || this;
  47286. }
  47287. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47288. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47289. return this;
  47290. };
  47291. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47292. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47293. return this;
  47294. };
  47295. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47296. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47297. return this;
  47298. };
  47299. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47300. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47301. return this;
  47302. };
  47303. return ArcRotateCameraInputsManager;
  47304. }(BABYLON.CameraInputsManager));
  47305. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47306. })(BABYLON || (BABYLON = {}));
  47307. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47308. var BABYLON;
  47309. (function (BABYLON) {
  47310. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47311. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47312. });
  47313. var ArcRotateCamera = /** @class */ (function (_super) {
  47314. __extends(ArcRotateCamera, _super);
  47315. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47316. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47317. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47318. _this.inertialAlphaOffset = 0;
  47319. _this.inertialBetaOffset = 0;
  47320. _this.inertialRadiusOffset = 0;
  47321. _this.lowerAlphaLimit = null;
  47322. _this.upperAlphaLimit = null;
  47323. _this.lowerBetaLimit = 0.01;
  47324. _this.upperBetaLimit = Math.PI;
  47325. _this.lowerRadiusLimit = null;
  47326. _this.upperRadiusLimit = null;
  47327. _this.inertialPanningX = 0;
  47328. _this.inertialPanningY = 0;
  47329. _this.pinchToPanMaxDistance = 20;
  47330. _this.panningDistanceLimit = null;
  47331. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47332. _this.panningInertia = 0.9;
  47333. //-- end properties for backward compatibility for inputs
  47334. _this.zoomOnFactor = 1;
  47335. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47336. _this.allowUpsideDown = true;
  47337. /** @hidden */
  47338. _this._viewMatrix = new BABYLON.Matrix();
  47339. // Panning
  47340. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47341. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47342. _this.checkCollisions = false;
  47343. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47344. _this._previousPosition = BABYLON.Vector3.Zero();
  47345. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47346. _this._newPosition = BABYLON.Vector3.Zero();
  47347. _this._computationVector = BABYLON.Vector3.Zero();
  47348. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47349. if (collidedMesh === void 0) { collidedMesh = null; }
  47350. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47351. newPosition.multiplyInPlace(_this._collider._radius);
  47352. }
  47353. if (!collidedMesh) {
  47354. _this._previousPosition.copyFrom(_this.position);
  47355. }
  47356. else {
  47357. _this.setPosition(newPosition);
  47358. if (_this.onCollide) {
  47359. _this.onCollide(collidedMesh);
  47360. }
  47361. }
  47362. // Recompute because of constraints
  47363. var cosa = Math.cos(_this.alpha);
  47364. var sina = Math.sin(_this.alpha);
  47365. var cosb = Math.cos(_this.beta);
  47366. var sinb = Math.sin(_this.beta);
  47367. if (sinb === 0) {
  47368. sinb = 0.0001;
  47369. }
  47370. var target = _this._getTargetPosition();
  47371. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47372. target.addToRef(_this._computationVector, _this._newPosition);
  47373. _this.position.copyFrom(_this._newPosition);
  47374. var up = _this.upVector;
  47375. if (_this.allowUpsideDown && _this.beta < 0) {
  47376. up = up.clone();
  47377. up = up.negate();
  47378. }
  47379. _this._computeViewMatrix(_this.position, target, up);
  47380. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47381. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47382. _this._collisionTriggered = false;
  47383. };
  47384. _this._target = BABYLON.Vector3.Zero();
  47385. if (target) {
  47386. _this.setTarget(target);
  47387. }
  47388. _this.alpha = alpha;
  47389. _this.beta = beta;
  47390. _this.radius = radius;
  47391. _this.getViewMatrix();
  47392. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47393. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47394. return _this;
  47395. }
  47396. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47397. get: function () {
  47398. return this._target;
  47399. },
  47400. set: function (value) {
  47401. this.setTarget(value);
  47402. },
  47403. enumerable: true,
  47404. configurable: true
  47405. });
  47406. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47407. //-- begin properties for backward compatibility for inputs
  47408. get: function () {
  47409. var pointers = this.inputs.attached["pointers"];
  47410. if (pointers)
  47411. return pointers.angularSensibilityX;
  47412. return 0;
  47413. },
  47414. set: function (value) {
  47415. var pointers = this.inputs.attached["pointers"];
  47416. if (pointers) {
  47417. pointers.angularSensibilityX = value;
  47418. }
  47419. },
  47420. enumerable: true,
  47421. configurable: true
  47422. });
  47423. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47424. get: function () {
  47425. var pointers = this.inputs.attached["pointers"];
  47426. if (pointers)
  47427. return pointers.angularSensibilityY;
  47428. return 0;
  47429. },
  47430. set: function (value) {
  47431. var pointers = this.inputs.attached["pointers"];
  47432. if (pointers) {
  47433. pointers.angularSensibilityY = value;
  47434. }
  47435. },
  47436. enumerable: true,
  47437. configurable: true
  47438. });
  47439. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47440. get: function () {
  47441. var pointers = this.inputs.attached["pointers"];
  47442. if (pointers)
  47443. return pointers.pinchPrecision;
  47444. return 0;
  47445. },
  47446. set: function (value) {
  47447. var pointers = this.inputs.attached["pointers"];
  47448. if (pointers) {
  47449. pointers.pinchPrecision = value;
  47450. }
  47451. },
  47452. enumerable: true,
  47453. configurable: true
  47454. });
  47455. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47456. get: function () {
  47457. var pointers = this.inputs.attached["pointers"];
  47458. if (pointers)
  47459. return pointers.pinchDeltaPercentage;
  47460. return 0;
  47461. },
  47462. set: function (value) {
  47463. var pointers = this.inputs.attached["pointers"];
  47464. if (pointers) {
  47465. pointers.pinchDeltaPercentage = value;
  47466. }
  47467. },
  47468. enumerable: true,
  47469. configurable: true
  47470. });
  47471. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47472. get: function () {
  47473. var pointers = this.inputs.attached["pointers"];
  47474. if (pointers)
  47475. return pointers.panningSensibility;
  47476. return 0;
  47477. },
  47478. set: function (value) {
  47479. var pointers = this.inputs.attached["pointers"];
  47480. if (pointers) {
  47481. pointers.panningSensibility = value;
  47482. }
  47483. },
  47484. enumerable: true,
  47485. configurable: true
  47486. });
  47487. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47488. get: function () {
  47489. var keyboard = this.inputs.attached["keyboard"];
  47490. if (keyboard)
  47491. return keyboard.keysUp;
  47492. return [];
  47493. },
  47494. set: function (value) {
  47495. var keyboard = this.inputs.attached["keyboard"];
  47496. if (keyboard)
  47497. keyboard.keysUp = value;
  47498. },
  47499. enumerable: true,
  47500. configurable: true
  47501. });
  47502. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47503. get: function () {
  47504. var keyboard = this.inputs.attached["keyboard"];
  47505. if (keyboard)
  47506. return keyboard.keysDown;
  47507. return [];
  47508. },
  47509. set: function (value) {
  47510. var keyboard = this.inputs.attached["keyboard"];
  47511. if (keyboard)
  47512. keyboard.keysDown = value;
  47513. },
  47514. enumerable: true,
  47515. configurable: true
  47516. });
  47517. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47518. get: function () {
  47519. var keyboard = this.inputs.attached["keyboard"];
  47520. if (keyboard)
  47521. return keyboard.keysLeft;
  47522. return [];
  47523. },
  47524. set: function (value) {
  47525. var keyboard = this.inputs.attached["keyboard"];
  47526. if (keyboard)
  47527. keyboard.keysLeft = value;
  47528. },
  47529. enumerable: true,
  47530. configurable: true
  47531. });
  47532. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47533. get: function () {
  47534. var keyboard = this.inputs.attached["keyboard"];
  47535. if (keyboard)
  47536. return keyboard.keysRight;
  47537. return [];
  47538. },
  47539. set: function (value) {
  47540. var keyboard = this.inputs.attached["keyboard"];
  47541. if (keyboard)
  47542. keyboard.keysRight = value;
  47543. },
  47544. enumerable: true,
  47545. configurable: true
  47546. });
  47547. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47548. get: function () {
  47549. var mousewheel = this.inputs.attached["mousewheel"];
  47550. if (mousewheel)
  47551. return mousewheel.wheelPrecision;
  47552. return 0;
  47553. },
  47554. set: function (value) {
  47555. var mousewheel = this.inputs.attached["mousewheel"];
  47556. if (mousewheel)
  47557. mousewheel.wheelPrecision = value;
  47558. },
  47559. enumerable: true,
  47560. configurable: true
  47561. });
  47562. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47563. get: function () {
  47564. var mousewheel = this.inputs.attached["mousewheel"];
  47565. if (mousewheel)
  47566. return mousewheel.wheelDeltaPercentage;
  47567. return 0;
  47568. },
  47569. set: function (value) {
  47570. var mousewheel = this.inputs.attached["mousewheel"];
  47571. if (mousewheel)
  47572. mousewheel.wheelDeltaPercentage = value;
  47573. },
  47574. enumerable: true,
  47575. configurable: true
  47576. });
  47577. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47578. get: function () {
  47579. return this._bouncingBehavior;
  47580. },
  47581. enumerable: true,
  47582. configurable: true
  47583. });
  47584. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47585. get: function () {
  47586. return this._bouncingBehavior != null;
  47587. },
  47588. set: function (value) {
  47589. if (value === this.useBouncingBehavior) {
  47590. return;
  47591. }
  47592. if (value) {
  47593. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47594. this.addBehavior(this._bouncingBehavior);
  47595. }
  47596. else if (this._bouncingBehavior) {
  47597. this.removeBehavior(this._bouncingBehavior);
  47598. this._bouncingBehavior = null;
  47599. }
  47600. },
  47601. enumerable: true,
  47602. configurable: true
  47603. });
  47604. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47605. get: function () {
  47606. return this._framingBehavior;
  47607. },
  47608. enumerable: true,
  47609. configurable: true
  47610. });
  47611. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47612. get: function () {
  47613. return this._framingBehavior != null;
  47614. },
  47615. set: function (value) {
  47616. if (value === this.useFramingBehavior) {
  47617. return;
  47618. }
  47619. if (value) {
  47620. this._framingBehavior = new BABYLON.FramingBehavior();
  47621. this.addBehavior(this._framingBehavior);
  47622. }
  47623. else if (this._framingBehavior) {
  47624. this.removeBehavior(this._framingBehavior);
  47625. this._framingBehavior = null;
  47626. }
  47627. },
  47628. enumerable: true,
  47629. configurable: true
  47630. });
  47631. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47632. get: function () {
  47633. return this._autoRotationBehavior;
  47634. },
  47635. enumerable: true,
  47636. configurable: true
  47637. });
  47638. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47639. get: function () {
  47640. return this._autoRotationBehavior != null;
  47641. },
  47642. set: function (value) {
  47643. if (value === this.useAutoRotationBehavior) {
  47644. return;
  47645. }
  47646. if (value) {
  47647. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47648. this.addBehavior(this._autoRotationBehavior);
  47649. }
  47650. else if (this._autoRotationBehavior) {
  47651. this.removeBehavior(this._autoRotationBehavior);
  47652. this._autoRotationBehavior = null;
  47653. }
  47654. },
  47655. enumerable: true,
  47656. configurable: true
  47657. });
  47658. // Cache
  47659. /** @hidden */
  47660. ArcRotateCamera.prototype._initCache = function () {
  47661. _super.prototype._initCache.call(this);
  47662. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47663. this._cache.alpha = undefined;
  47664. this._cache.beta = undefined;
  47665. this._cache.radius = undefined;
  47666. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47667. };
  47668. /** @hidden */
  47669. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47670. if (!ignoreParentClass) {
  47671. _super.prototype._updateCache.call(this);
  47672. }
  47673. this._cache._target.copyFrom(this._getTargetPosition());
  47674. this._cache.alpha = this.alpha;
  47675. this._cache.beta = this.beta;
  47676. this._cache.radius = this.radius;
  47677. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47678. };
  47679. ArcRotateCamera.prototype._getTargetPosition = function () {
  47680. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47681. var pos = this._targetHost.getAbsolutePosition();
  47682. if (this._targetBoundingCenter) {
  47683. pos.addToRef(this._targetBoundingCenter, this._target);
  47684. }
  47685. else {
  47686. this._target.copyFrom(pos);
  47687. }
  47688. }
  47689. var lockedTargetPosition = this._getLockedTargetPosition();
  47690. if (lockedTargetPosition) {
  47691. return lockedTargetPosition;
  47692. }
  47693. return this._target;
  47694. };
  47695. ArcRotateCamera.prototype.storeState = function () {
  47696. this._storedAlpha = this.alpha;
  47697. this._storedBeta = this.beta;
  47698. this._storedRadius = this.radius;
  47699. this._storedTarget = this._getTargetPosition().clone();
  47700. return _super.prototype.storeState.call(this);
  47701. };
  47702. /**
  47703. * @hidden
  47704. * Restored camera state. You must call storeState() first
  47705. */
  47706. ArcRotateCamera.prototype._restoreStateValues = function () {
  47707. if (!_super.prototype._restoreStateValues.call(this)) {
  47708. return false;
  47709. }
  47710. this.alpha = this._storedAlpha;
  47711. this.beta = this._storedBeta;
  47712. this.radius = this._storedRadius;
  47713. this.setTarget(this._storedTarget.clone());
  47714. this.inertialAlphaOffset = 0;
  47715. this.inertialBetaOffset = 0;
  47716. this.inertialRadiusOffset = 0;
  47717. this.inertialPanningX = 0;
  47718. this.inertialPanningY = 0;
  47719. return true;
  47720. };
  47721. // Synchronized
  47722. /** @hidden */
  47723. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47724. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47725. return false;
  47726. return this._cache._target.equals(this._getTargetPosition())
  47727. && this._cache.alpha === this.alpha
  47728. && this._cache.beta === this.beta
  47729. && this._cache.radius === this.radius
  47730. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47731. };
  47732. // Methods
  47733. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47734. var _this = this;
  47735. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47736. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47737. this._useCtrlForPanning = useCtrlForPanning;
  47738. this._panningMouseButton = panningMouseButton;
  47739. this.inputs.attachElement(element, noPreventDefault);
  47740. this._reset = function () {
  47741. _this.inertialAlphaOffset = 0;
  47742. _this.inertialBetaOffset = 0;
  47743. _this.inertialRadiusOffset = 0;
  47744. _this.inertialPanningX = 0;
  47745. _this.inertialPanningY = 0;
  47746. };
  47747. };
  47748. ArcRotateCamera.prototype.detachControl = function (element) {
  47749. this.inputs.detachElement(element);
  47750. if (this._reset) {
  47751. this._reset();
  47752. }
  47753. };
  47754. /** @hidden */
  47755. ArcRotateCamera.prototype._checkInputs = function () {
  47756. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47757. if (this._collisionTriggered) {
  47758. return;
  47759. }
  47760. this.inputs.checkInputs();
  47761. // Inertia
  47762. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47763. var inertialAlphaOffset = this.inertialAlphaOffset;
  47764. if (this.beta <= 0)
  47765. inertialAlphaOffset *= -1;
  47766. if (this.getScene().useRightHandedSystem)
  47767. inertialAlphaOffset *= -1;
  47768. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47769. inertialAlphaOffset *= -1;
  47770. this.alpha += inertialAlphaOffset;
  47771. this.beta += this.inertialBetaOffset;
  47772. this.radius -= this.inertialRadiusOffset;
  47773. this.inertialAlphaOffset *= this.inertia;
  47774. this.inertialBetaOffset *= this.inertia;
  47775. this.inertialRadiusOffset *= this.inertia;
  47776. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47777. this.inertialAlphaOffset = 0;
  47778. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47779. this.inertialBetaOffset = 0;
  47780. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47781. this.inertialRadiusOffset = 0;
  47782. }
  47783. // Panning inertia
  47784. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47785. if (!this._localDirection) {
  47786. this._localDirection = BABYLON.Vector3.Zero();
  47787. this._transformedDirection = BABYLON.Vector3.Zero();
  47788. }
  47789. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47790. this._localDirection.multiplyInPlace(this.panningAxis);
  47791. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47792. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47793. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47794. if (!this.panningAxis.y) {
  47795. this._transformedDirection.y = 0;
  47796. }
  47797. if (!this._targetHost) {
  47798. if (this.panningDistanceLimit) {
  47799. this._transformedDirection.addInPlace(this._target);
  47800. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47801. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47802. this._target.copyFrom(this._transformedDirection);
  47803. }
  47804. }
  47805. else {
  47806. this._target.addInPlace(this._transformedDirection);
  47807. }
  47808. }
  47809. this.inertialPanningX *= this.panningInertia;
  47810. this.inertialPanningY *= this.panningInertia;
  47811. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47812. this.inertialPanningX = 0;
  47813. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47814. this.inertialPanningY = 0;
  47815. }
  47816. // Limits
  47817. this._checkLimits();
  47818. _super.prototype._checkInputs.call(this);
  47819. };
  47820. ArcRotateCamera.prototype._checkLimits = function () {
  47821. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47822. if (this.allowUpsideDown && this.beta > Math.PI) {
  47823. this.beta = this.beta - (2 * Math.PI);
  47824. }
  47825. }
  47826. else {
  47827. if (this.beta < this.lowerBetaLimit) {
  47828. this.beta = this.lowerBetaLimit;
  47829. }
  47830. }
  47831. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47832. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47833. this.beta = this.beta + (2 * Math.PI);
  47834. }
  47835. }
  47836. else {
  47837. if (this.beta > this.upperBetaLimit) {
  47838. this.beta = this.upperBetaLimit;
  47839. }
  47840. }
  47841. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  47842. this.alpha = this.lowerAlphaLimit;
  47843. }
  47844. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  47845. this.alpha = this.upperAlphaLimit;
  47846. }
  47847. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  47848. this.radius = this.lowerRadiusLimit;
  47849. }
  47850. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  47851. this.radius = this.upperRadiusLimit;
  47852. }
  47853. };
  47854. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47855. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47856. this.radius = this._computationVector.length();
  47857. if (this.radius === 0) {
  47858. this.radius = 0.0001; // Just to avoid division by zero
  47859. }
  47860. // Alpha
  47861. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47862. if (this._computationVector.z < 0) {
  47863. this.alpha = 2 * Math.PI - this.alpha;
  47864. }
  47865. // Beta
  47866. this.beta = Math.acos(this._computationVector.y / this.radius);
  47867. this._checkLimits();
  47868. };
  47869. ArcRotateCamera.prototype.setPosition = function (position) {
  47870. if (this.position.equals(position)) {
  47871. return;
  47872. }
  47873. this.position.copyFrom(position);
  47874. this.rebuildAnglesAndRadius();
  47875. };
  47876. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47877. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47878. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47879. if (target.getBoundingInfo) {
  47880. if (toBoundingCenter) {
  47881. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47882. }
  47883. else {
  47884. this._targetBoundingCenter = null;
  47885. }
  47886. this._targetHost = target;
  47887. this._target = this._getTargetPosition();
  47888. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47889. }
  47890. else {
  47891. var newTarget = target;
  47892. var currentTarget = this._getTargetPosition();
  47893. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47894. return;
  47895. }
  47896. this._targetHost = null;
  47897. this._target = newTarget;
  47898. this._targetBoundingCenter = null;
  47899. this.onMeshTargetChangedObservable.notifyObservers(null);
  47900. }
  47901. this.rebuildAnglesAndRadius();
  47902. };
  47903. /** @hidden */
  47904. ArcRotateCamera.prototype._getViewMatrix = function () {
  47905. // Compute
  47906. var cosa = Math.cos(this.alpha);
  47907. var sina = Math.sin(this.alpha);
  47908. var cosb = Math.cos(this.beta);
  47909. var sinb = Math.sin(this.beta);
  47910. if (sinb === 0) {
  47911. sinb = 0.0001;
  47912. }
  47913. var target = this._getTargetPosition();
  47914. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47915. target.addToRef(this._computationVector, this._newPosition);
  47916. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47917. if (!this._collider) {
  47918. this._collider = new BABYLON.Collider();
  47919. }
  47920. this._collider._radius = this.collisionRadius;
  47921. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47922. this._collisionTriggered = true;
  47923. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47924. }
  47925. else {
  47926. this.position.copyFrom(this._newPosition);
  47927. var up = this.upVector;
  47928. if (this.allowUpsideDown && sinb < 0) {
  47929. up = up.clone();
  47930. up = up.negate();
  47931. }
  47932. this._computeViewMatrix(this.position, target, up);
  47933. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  47934. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  47935. }
  47936. this._currentTarget = target;
  47937. return this._viewMatrix;
  47938. };
  47939. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  47940. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47941. meshes = meshes || this.getScene().meshes;
  47942. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  47943. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  47944. this.radius = distance * this.zoomOnFactor;
  47945. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  47946. };
  47947. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  47948. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47949. var meshesOrMinMaxVector;
  47950. var distance;
  47951. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  47952. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  47953. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  47954. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  47955. }
  47956. else { //minMaxVector and distance
  47957. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  47958. meshesOrMinMaxVector = minMaxVectorAndDistance;
  47959. distance = minMaxVectorAndDistance.distance;
  47960. }
  47961. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  47962. if (!doNotUpdateMaxZ) {
  47963. this.maxZ = distance * 2;
  47964. }
  47965. };
  47966. /**
  47967. * @override
  47968. * Override Camera.createRigCamera
  47969. */
  47970. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47971. var alphaShift = 0;
  47972. switch (this.cameraRigMode) {
  47973. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47974. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47975. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47976. case BABYLON.Camera.RIG_MODE_VR:
  47977. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  47978. break;
  47979. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47980. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  47981. break;
  47982. }
  47983. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  47984. rigCam._cameraRigParams = {};
  47985. return rigCam;
  47986. };
  47987. /**
  47988. * @hidden
  47989. * @override
  47990. * Override Camera._updateRigCameras
  47991. */
  47992. ArcRotateCamera.prototype._updateRigCameras = function () {
  47993. var camLeft = this._rigCameras[0];
  47994. var camRight = this._rigCameras[1];
  47995. camLeft.beta = camRight.beta = this.beta;
  47996. camLeft.radius = camRight.radius = this.radius;
  47997. switch (this.cameraRigMode) {
  47998. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47999. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48000. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48001. case BABYLON.Camera.RIG_MODE_VR:
  48002. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48003. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48004. break;
  48005. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48006. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48007. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48008. break;
  48009. }
  48010. _super.prototype._updateRigCameras.call(this);
  48011. };
  48012. ArcRotateCamera.prototype.dispose = function () {
  48013. this.inputs.clear();
  48014. _super.prototype.dispose.call(this);
  48015. };
  48016. ArcRotateCamera.prototype.getClassName = function () {
  48017. return "ArcRotateCamera";
  48018. };
  48019. __decorate([
  48020. BABYLON.serialize()
  48021. ], ArcRotateCamera.prototype, "alpha", void 0);
  48022. __decorate([
  48023. BABYLON.serialize()
  48024. ], ArcRotateCamera.prototype, "beta", void 0);
  48025. __decorate([
  48026. BABYLON.serialize()
  48027. ], ArcRotateCamera.prototype, "radius", void 0);
  48028. __decorate([
  48029. BABYLON.serializeAsVector3("target")
  48030. ], ArcRotateCamera.prototype, "_target", void 0);
  48031. __decorate([
  48032. BABYLON.serialize()
  48033. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48034. __decorate([
  48035. BABYLON.serialize()
  48036. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48037. __decorate([
  48038. BABYLON.serialize()
  48039. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48040. __decorate([
  48041. BABYLON.serialize()
  48042. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48043. __decorate([
  48044. BABYLON.serialize()
  48045. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48046. __decorate([
  48047. BABYLON.serialize()
  48048. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48049. __decorate([
  48050. BABYLON.serialize()
  48051. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48052. __decorate([
  48053. BABYLON.serialize()
  48054. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48055. __decorate([
  48056. BABYLON.serialize()
  48057. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48058. __decorate([
  48059. BABYLON.serialize()
  48060. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48061. __decorate([
  48062. BABYLON.serialize()
  48063. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48064. __decorate([
  48065. BABYLON.serialize()
  48066. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48067. __decorate([
  48068. BABYLON.serialize()
  48069. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48070. __decorate([
  48071. BABYLON.serializeAsVector3()
  48072. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48073. __decorate([
  48074. BABYLON.serialize()
  48075. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48076. __decorate([
  48077. BABYLON.serialize()
  48078. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48079. __decorate([
  48080. BABYLON.serialize()
  48081. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48082. return ArcRotateCamera;
  48083. }(BABYLON.TargetCamera));
  48084. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48085. })(BABYLON || (BABYLON = {}));
  48086. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48087. var BABYLON;
  48088. (function (BABYLON) {
  48089. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48090. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48091. });
  48092. /**
  48093. * The HemisphericLight simulates the ambient environment light,
  48094. * so the passed direction is the light reflection direction, not the incoming direction.
  48095. */
  48096. var HemisphericLight = /** @class */ (function (_super) {
  48097. __extends(HemisphericLight, _super);
  48098. /**
  48099. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48100. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48101. * The HemisphericLight can't cast shadows.
  48102. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48103. * @param name The friendly name of the light
  48104. * @param direction The direction of the light reflection
  48105. * @param scene The scene the light belongs to
  48106. */
  48107. function HemisphericLight(name, direction, scene) {
  48108. var _this = _super.call(this, name, scene) || this;
  48109. /**
  48110. * The groundColor is the light in the opposite direction to the one specified during creation.
  48111. * 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.
  48112. */
  48113. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48114. _this.direction = direction || BABYLON.Vector3.Up();
  48115. return _this;
  48116. }
  48117. HemisphericLight.prototype._buildUniformLayout = function () {
  48118. this._uniformBuffer.addUniform("vLightData", 4);
  48119. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48120. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48121. this._uniformBuffer.addUniform("vLightGround", 3);
  48122. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48123. this._uniformBuffer.addUniform("depthValues", 2);
  48124. this._uniformBuffer.create();
  48125. };
  48126. /**
  48127. * Returns the string "HemisphericLight".
  48128. * @return The class name
  48129. */
  48130. HemisphericLight.prototype.getClassName = function () {
  48131. return "HemisphericLight";
  48132. };
  48133. /**
  48134. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48135. * Returns the updated direction.
  48136. * @param target The target the direction should point to
  48137. * @return The computed direction
  48138. */
  48139. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48140. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48141. return this.direction;
  48142. };
  48143. /**
  48144. * Returns the shadow generator associated to the light.
  48145. * @returns Always null for hemispheric lights because it does not support shadows.
  48146. */
  48147. HemisphericLight.prototype.getShadowGenerator = function () {
  48148. return null;
  48149. };
  48150. /**
  48151. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48152. * @param effect The effect to update
  48153. * @param lightIndex The index of the light in the effect to update
  48154. * @returns The hemispheric light
  48155. */
  48156. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48157. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48158. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48159. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48160. return this;
  48161. };
  48162. /**
  48163. * Computes the world matrix of the node
  48164. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  48165. * @param useWasUpdatedFlag defines a reserved property
  48166. * @returns the world matrix
  48167. */
  48168. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  48169. if (!this._worldMatrix) {
  48170. this._worldMatrix = BABYLON.Matrix.Identity();
  48171. }
  48172. return this._worldMatrix;
  48173. };
  48174. /**
  48175. * Returns the integer 3.
  48176. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48177. */
  48178. HemisphericLight.prototype.getTypeID = function () {
  48179. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48180. };
  48181. /**
  48182. * Prepares the list of defines specific to the light type.
  48183. * @param defines the list of defines
  48184. * @param lightIndex defines the index of the light for the effect
  48185. */
  48186. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48187. defines["HEMILIGHT" + lightIndex] = true;
  48188. };
  48189. __decorate([
  48190. BABYLON.serializeAsColor3()
  48191. ], HemisphericLight.prototype, "groundColor", void 0);
  48192. __decorate([
  48193. BABYLON.serializeAsVector3()
  48194. ], HemisphericLight.prototype, "direction", void 0);
  48195. return HemisphericLight;
  48196. }(BABYLON.Light));
  48197. BABYLON.HemisphericLight = HemisphericLight;
  48198. })(BABYLON || (BABYLON = {}));
  48199. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48200. var BABYLON;
  48201. (function (BABYLON) {
  48202. /**
  48203. * Base implementation IShadowLight
  48204. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48205. */
  48206. var ShadowLight = /** @class */ (function (_super) {
  48207. __extends(ShadowLight, _super);
  48208. function ShadowLight() {
  48209. var _this = _super !== null && _super.apply(this, arguments) || this;
  48210. _this._needProjectionMatrixCompute = true;
  48211. return _this;
  48212. }
  48213. ShadowLight.prototype._setPosition = function (value) {
  48214. this._position = value;
  48215. };
  48216. Object.defineProperty(ShadowLight.prototype, "position", {
  48217. /**
  48218. * Sets the position the shadow will be casted from. Also use as the light position for both
  48219. * point and spot lights.
  48220. */
  48221. get: function () {
  48222. return this._position;
  48223. },
  48224. /**
  48225. * Sets the position the shadow will be casted from. Also use as the light position for both
  48226. * point and spot lights.
  48227. */
  48228. set: function (value) {
  48229. this._setPosition(value);
  48230. },
  48231. enumerable: true,
  48232. configurable: true
  48233. });
  48234. ShadowLight.prototype._setDirection = function (value) {
  48235. this._direction = value;
  48236. };
  48237. Object.defineProperty(ShadowLight.prototype, "direction", {
  48238. /**
  48239. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48240. * Also use as the light direction on spot and directional lights.
  48241. */
  48242. get: function () {
  48243. return this._direction;
  48244. },
  48245. /**
  48246. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48247. * Also use as the light direction on spot and directional lights.
  48248. */
  48249. set: function (value) {
  48250. this._setDirection(value);
  48251. },
  48252. enumerable: true,
  48253. configurable: true
  48254. });
  48255. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48256. /**
  48257. * Gets the shadow projection clipping minimum z value.
  48258. */
  48259. get: function () {
  48260. return this._shadowMinZ;
  48261. },
  48262. /**
  48263. * Sets the shadow projection clipping minimum z value.
  48264. */
  48265. set: function (value) {
  48266. this._shadowMinZ = value;
  48267. this.forceProjectionMatrixCompute();
  48268. },
  48269. enumerable: true,
  48270. configurable: true
  48271. });
  48272. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48273. /**
  48274. * Sets the shadow projection clipping maximum z value.
  48275. */
  48276. get: function () {
  48277. return this._shadowMaxZ;
  48278. },
  48279. /**
  48280. * Gets the shadow projection clipping maximum z value.
  48281. */
  48282. set: function (value) {
  48283. this._shadowMaxZ = value;
  48284. this.forceProjectionMatrixCompute();
  48285. },
  48286. enumerable: true,
  48287. configurable: true
  48288. });
  48289. /**
  48290. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48291. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48292. */
  48293. ShadowLight.prototype.computeTransformedInformation = function () {
  48294. if (this.parent && this.parent.getWorldMatrix) {
  48295. if (!this.transformedPosition) {
  48296. this.transformedPosition = BABYLON.Vector3.Zero();
  48297. }
  48298. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48299. // In case the direction is present.
  48300. if (this.direction) {
  48301. if (!this.transformedDirection) {
  48302. this.transformedDirection = BABYLON.Vector3.Zero();
  48303. }
  48304. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48305. }
  48306. return true;
  48307. }
  48308. return false;
  48309. };
  48310. /**
  48311. * Return the depth scale used for the shadow map.
  48312. * @returns the depth scale.
  48313. */
  48314. ShadowLight.prototype.getDepthScale = function () {
  48315. return 50.0;
  48316. };
  48317. /**
  48318. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48319. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48320. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48321. */
  48322. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48323. return this.transformedDirection ? this.transformedDirection : this.direction;
  48324. };
  48325. /**
  48326. * Returns the ShadowLight absolute position in the World.
  48327. * @returns the position vector in world space
  48328. */
  48329. ShadowLight.prototype.getAbsolutePosition = function () {
  48330. return this.transformedPosition ? this.transformedPosition : this.position;
  48331. };
  48332. /**
  48333. * Sets the ShadowLight direction toward the passed target.
  48334. * @param target The point tot target in local space
  48335. * @returns the updated ShadowLight direction
  48336. */
  48337. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48338. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48339. return this.direction;
  48340. };
  48341. /**
  48342. * Returns the light rotation in euler definition.
  48343. * @returns the x y z rotation in local space.
  48344. */
  48345. ShadowLight.prototype.getRotation = function () {
  48346. this.direction.normalize();
  48347. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48348. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48349. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48350. };
  48351. /**
  48352. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48353. * @returns true if a cube texture needs to be use
  48354. */
  48355. ShadowLight.prototype.needCube = function () {
  48356. return false;
  48357. };
  48358. /**
  48359. * Detects if the projection matrix requires to be recomputed this frame.
  48360. * @returns true if it requires to be recomputed otherwise, false.
  48361. */
  48362. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48363. return this._needProjectionMatrixCompute;
  48364. };
  48365. /**
  48366. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48367. */
  48368. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48369. this._needProjectionMatrixCompute = true;
  48370. };
  48371. /** @hidden */
  48372. ShadowLight.prototype._initCache = function () {
  48373. _super.prototype._initCache.call(this);
  48374. this._cache.position = BABYLON.Vector3.Zero();
  48375. };
  48376. /** @hidden */
  48377. ShadowLight.prototype._isSynchronized = function () {
  48378. if (!this._cache.position.equals(this.position))
  48379. return false;
  48380. return true;
  48381. };
  48382. /**
  48383. * Computes the world matrix of the node
  48384. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  48385. * @returns the world matrix
  48386. */
  48387. ShadowLight.prototype.computeWorldMatrix = function (force) {
  48388. if (!force && this.isSynchronized()) {
  48389. this._currentRenderId = this.getScene().getRenderId();
  48390. return this._worldMatrix;
  48391. }
  48392. this._updateCache();
  48393. this._cache.position.copyFrom(this.position);
  48394. if (!this._worldMatrix) {
  48395. this._worldMatrix = BABYLON.Matrix.Identity();
  48396. }
  48397. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48398. if (this.parent && this.parent.getWorldMatrix) {
  48399. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  48400. this._markSyncedWithParent();
  48401. }
  48402. // Cache the determinant
  48403. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  48404. return this._worldMatrix;
  48405. };
  48406. /**
  48407. * Gets the minZ used for shadow according to both the scene and the light.
  48408. * @param activeCamera The camera we are returning the min for
  48409. * @returns the depth min z
  48410. */
  48411. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48412. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48413. };
  48414. /**
  48415. * Gets the maxZ used for shadow according to both the scene and the light.
  48416. * @param activeCamera The camera we are returning the max for
  48417. * @returns the depth max z
  48418. */
  48419. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48420. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48421. };
  48422. /**
  48423. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48424. * @param matrix The materix to updated with the projection information
  48425. * @param viewMatrix The transform matrix of the light
  48426. * @param renderList The list of mesh to render in the map
  48427. * @returns The current light
  48428. */
  48429. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48430. if (this.customProjectionMatrixBuilder) {
  48431. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48432. }
  48433. else {
  48434. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48435. }
  48436. return this;
  48437. };
  48438. __decorate([
  48439. BABYLON.serializeAsVector3()
  48440. ], ShadowLight.prototype, "position", null);
  48441. __decorate([
  48442. BABYLON.serializeAsVector3()
  48443. ], ShadowLight.prototype, "direction", null);
  48444. __decorate([
  48445. BABYLON.serialize()
  48446. ], ShadowLight.prototype, "shadowMinZ", null);
  48447. __decorate([
  48448. BABYLON.serialize()
  48449. ], ShadowLight.prototype, "shadowMaxZ", null);
  48450. return ShadowLight;
  48451. }(BABYLON.Light));
  48452. BABYLON.ShadowLight = ShadowLight;
  48453. })(BABYLON || (BABYLON = {}));
  48454. //# sourceMappingURL=babylon.shadowLight.js.map
  48455. var BABYLON;
  48456. (function (BABYLON) {
  48457. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48458. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48459. });
  48460. /**
  48461. * A point light is a light defined by an unique point in world space.
  48462. * The light is emitted in every direction from this point.
  48463. * A good example of a point light is a standard light bulb.
  48464. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48465. */
  48466. var PointLight = /** @class */ (function (_super) {
  48467. __extends(PointLight, _super);
  48468. /**
  48469. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48470. * A PointLight emits the light in every direction.
  48471. * It can cast shadows.
  48472. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48473. * ```javascript
  48474. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48475. * ```
  48476. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48477. * @param name The light friendly name
  48478. * @param position The position of the point light in the scene
  48479. * @param scene The scene the lights belongs to
  48480. */
  48481. function PointLight(name, position, scene) {
  48482. var _this = _super.call(this, name, scene) || this;
  48483. _this._shadowAngle = Math.PI / 2;
  48484. _this.position = position;
  48485. return _this;
  48486. }
  48487. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48488. /**
  48489. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48490. * This specifies what angle the shadow will use to be created.
  48491. *
  48492. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48493. */
  48494. get: function () {
  48495. return this._shadowAngle;
  48496. },
  48497. /**
  48498. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48499. * This specifies what angle the shadow will use to be created.
  48500. *
  48501. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48502. */
  48503. set: function (value) {
  48504. this._shadowAngle = value;
  48505. this.forceProjectionMatrixCompute();
  48506. },
  48507. enumerable: true,
  48508. configurable: true
  48509. });
  48510. Object.defineProperty(PointLight.prototype, "direction", {
  48511. /**
  48512. * Gets the direction if it has been set.
  48513. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48514. */
  48515. get: function () {
  48516. return this._direction;
  48517. },
  48518. /**
  48519. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48520. */
  48521. set: function (value) {
  48522. var previousNeedCube = this.needCube();
  48523. this._direction = value;
  48524. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48525. this._shadowGenerator.recreateShadowMap();
  48526. }
  48527. },
  48528. enumerable: true,
  48529. configurable: true
  48530. });
  48531. /**
  48532. * Returns the string "PointLight"
  48533. * @returns the class name
  48534. */
  48535. PointLight.prototype.getClassName = function () {
  48536. return "PointLight";
  48537. };
  48538. /**
  48539. * Returns the integer 0.
  48540. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48541. */
  48542. PointLight.prototype.getTypeID = function () {
  48543. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48544. };
  48545. /**
  48546. * Specifies wether or not the shadowmap should be a cube texture.
  48547. * @returns true if the shadowmap needs to be a cube texture.
  48548. */
  48549. PointLight.prototype.needCube = function () {
  48550. return !this.direction;
  48551. };
  48552. /**
  48553. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48554. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48555. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48556. */
  48557. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48558. if (this.direction) {
  48559. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48560. }
  48561. else {
  48562. switch (faceIndex) {
  48563. case 0:
  48564. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48565. case 1:
  48566. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48567. case 2:
  48568. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48569. case 3:
  48570. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48571. case 4:
  48572. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48573. case 5:
  48574. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48575. }
  48576. }
  48577. return BABYLON.Vector3.Zero();
  48578. };
  48579. /**
  48580. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48581. * - fov = PI / 2
  48582. * - aspect ratio : 1.0
  48583. * - z-near and far equal to the active camera minZ and maxZ.
  48584. * Returns the PointLight.
  48585. */
  48586. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48587. var activeCamera = this.getScene().activeCamera;
  48588. if (!activeCamera) {
  48589. return;
  48590. }
  48591. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48592. };
  48593. PointLight.prototype._buildUniformLayout = function () {
  48594. this._uniformBuffer.addUniform("vLightData", 4);
  48595. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48596. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48597. this._uniformBuffer.addUniform("vLightFalloff", 4);
  48598. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48599. this._uniformBuffer.addUniform("depthValues", 2);
  48600. this._uniformBuffer.create();
  48601. };
  48602. /**
  48603. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48604. * @param effect The effect to update
  48605. * @param lightIndex The index of the light in the effect to update
  48606. * @returns The point light
  48607. */
  48608. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48609. if (this.computeTransformedInformation()) {
  48610. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48611. }
  48612. else {
  48613. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48614. }
  48615. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  48616. return this;
  48617. };
  48618. /**
  48619. * Prepares the list of defines specific to the light type.
  48620. * @param defines the list of defines
  48621. * @param lightIndex defines the index of the light for the effect
  48622. */
  48623. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48624. defines["POINTLIGHT" + lightIndex] = true;
  48625. };
  48626. __decorate([
  48627. BABYLON.serialize()
  48628. ], PointLight.prototype, "shadowAngle", null);
  48629. return PointLight;
  48630. }(BABYLON.ShadowLight));
  48631. BABYLON.PointLight = PointLight;
  48632. })(BABYLON || (BABYLON = {}));
  48633. //# sourceMappingURL=babylon.pointLight.js.map
  48634. var BABYLON;
  48635. (function (BABYLON) {
  48636. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48637. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48638. });
  48639. /**
  48640. * A directional light is defined by a direction (what a surprise!).
  48641. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48642. * 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.
  48643. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48644. */
  48645. var DirectionalLight = /** @class */ (function (_super) {
  48646. __extends(DirectionalLight, _super);
  48647. /**
  48648. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48649. * The directional light is emitted from everywhere in the given direction.
  48650. * It can cast shawdows.
  48651. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48652. * @param name The friendly name of the light
  48653. * @param direction The direction of the light
  48654. * @param scene The scene the light belongs to
  48655. */
  48656. function DirectionalLight(name, direction, scene) {
  48657. var _this = _super.call(this, name, scene) || this;
  48658. _this._shadowFrustumSize = 0;
  48659. _this._shadowOrthoScale = 0.1;
  48660. /**
  48661. * Automatically compute the projection matrix to best fit (including all the casters)
  48662. * on each frame.
  48663. */
  48664. _this.autoUpdateExtends = true;
  48665. // Cache
  48666. _this._orthoLeft = Number.MAX_VALUE;
  48667. _this._orthoRight = Number.MIN_VALUE;
  48668. _this._orthoTop = Number.MIN_VALUE;
  48669. _this._orthoBottom = Number.MAX_VALUE;
  48670. _this.position = direction.scale(-1.0);
  48671. _this.direction = direction;
  48672. return _this;
  48673. }
  48674. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48675. /**
  48676. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48677. */
  48678. get: function () {
  48679. return this._shadowFrustumSize;
  48680. },
  48681. /**
  48682. * Specifies a fix frustum size for the shadow generation.
  48683. */
  48684. set: function (value) {
  48685. this._shadowFrustumSize = value;
  48686. this.forceProjectionMatrixCompute();
  48687. },
  48688. enumerable: true,
  48689. configurable: true
  48690. });
  48691. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48692. /**
  48693. * Gets the shadow projection scale against the optimal computed one.
  48694. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48695. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48696. */
  48697. get: function () {
  48698. return this._shadowOrthoScale;
  48699. },
  48700. /**
  48701. * Sets the shadow projection scale against the optimal computed one.
  48702. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48703. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48704. */
  48705. set: function (value) {
  48706. this._shadowOrthoScale = value;
  48707. this.forceProjectionMatrixCompute();
  48708. },
  48709. enumerable: true,
  48710. configurable: true
  48711. });
  48712. /**
  48713. * Returns the string "DirectionalLight".
  48714. * @return The class name
  48715. */
  48716. DirectionalLight.prototype.getClassName = function () {
  48717. return "DirectionalLight";
  48718. };
  48719. /**
  48720. * Returns the integer 1.
  48721. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48722. */
  48723. DirectionalLight.prototype.getTypeID = function () {
  48724. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48725. };
  48726. /**
  48727. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48728. * Returns the DirectionalLight Shadow projection matrix.
  48729. */
  48730. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48731. if (this.shadowFrustumSize > 0) {
  48732. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48733. }
  48734. else {
  48735. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48736. }
  48737. };
  48738. /**
  48739. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48740. * Returns the DirectionalLight Shadow projection matrix.
  48741. */
  48742. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48743. var activeCamera = this.getScene().activeCamera;
  48744. if (!activeCamera) {
  48745. return;
  48746. }
  48747. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48748. };
  48749. /**
  48750. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48751. * Returns the DirectionalLight Shadow projection matrix.
  48752. */
  48753. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48754. var activeCamera = this.getScene().activeCamera;
  48755. if (!activeCamera) {
  48756. return;
  48757. }
  48758. // Check extends
  48759. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48760. var tempVector3 = BABYLON.Vector3.Zero();
  48761. this._orthoLeft = Number.MAX_VALUE;
  48762. this._orthoRight = Number.MIN_VALUE;
  48763. this._orthoTop = Number.MIN_VALUE;
  48764. this._orthoBottom = Number.MAX_VALUE;
  48765. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48766. var mesh = renderList[meshIndex];
  48767. if (!mesh) {
  48768. continue;
  48769. }
  48770. var boundingInfo = mesh.getBoundingInfo();
  48771. var boundingBox = boundingInfo.boundingBox;
  48772. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48773. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48774. if (tempVector3.x < this._orthoLeft)
  48775. this._orthoLeft = tempVector3.x;
  48776. if (tempVector3.y < this._orthoBottom)
  48777. this._orthoBottom = tempVector3.y;
  48778. if (tempVector3.x > this._orthoRight)
  48779. this._orthoRight = tempVector3.x;
  48780. if (tempVector3.y > this._orthoTop)
  48781. this._orthoTop = tempVector3.y;
  48782. }
  48783. }
  48784. }
  48785. var xOffset = this._orthoRight - this._orthoLeft;
  48786. var yOffset = this._orthoTop - this._orthoBottom;
  48787. 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);
  48788. };
  48789. DirectionalLight.prototype._buildUniformLayout = function () {
  48790. this._uniformBuffer.addUniform("vLightData", 4);
  48791. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48792. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48793. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48794. this._uniformBuffer.addUniform("depthValues", 2);
  48795. this._uniformBuffer.create();
  48796. };
  48797. /**
  48798. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48799. * @param effect The effect to update
  48800. * @param lightIndex The index of the light in the effect to update
  48801. * @returns The directional light
  48802. */
  48803. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48804. if (this.computeTransformedInformation()) {
  48805. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48806. return this;
  48807. }
  48808. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48809. return this;
  48810. };
  48811. /**
  48812. * Gets the minZ used for shadow according to both the scene and the light.
  48813. *
  48814. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48815. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48816. * @param activeCamera The camera we are returning the min for
  48817. * @returns the depth min z
  48818. */
  48819. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48820. return 1;
  48821. };
  48822. /**
  48823. * Gets the maxZ used for shadow according to both the scene and the light.
  48824. *
  48825. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48826. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48827. * @param activeCamera The camera we are returning the max for
  48828. * @returns the depth max z
  48829. */
  48830. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48831. return 1;
  48832. };
  48833. /**
  48834. * Prepares the list of defines specific to the light type.
  48835. * @param defines the list of defines
  48836. * @param lightIndex defines the index of the light for the effect
  48837. */
  48838. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48839. defines["DIRLIGHT" + lightIndex] = true;
  48840. };
  48841. __decorate([
  48842. BABYLON.serialize()
  48843. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48844. __decorate([
  48845. BABYLON.serialize()
  48846. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48847. __decorate([
  48848. BABYLON.serialize()
  48849. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48850. return DirectionalLight;
  48851. }(BABYLON.ShadowLight));
  48852. BABYLON.DirectionalLight = DirectionalLight;
  48853. })(BABYLON || (BABYLON = {}));
  48854. //# sourceMappingURL=babylon.directionalLight.js.map
  48855. var BABYLON;
  48856. (function (BABYLON) {
  48857. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  48858. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  48859. });
  48860. /**
  48861. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48862. * These values define a cone of light starting from the position, emitting toward the direction.
  48863. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48864. * and the exponent defines the speed of the decay of the light with distance (reach).
  48865. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48866. */
  48867. var SpotLight = /** @class */ (function (_super) {
  48868. __extends(SpotLight, _super);
  48869. /**
  48870. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48871. * It can cast shadows.
  48872. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48873. * @param name The light friendly name
  48874. * @param position The position of the spot light in the scene
  48875. * @param direction The direction of the light in the scene
  48876. * @param angle The cone angle of the light in Radians
  48877. * @param exponent The light decay speed with the distance from the emission spot
  48878. * @param scene The scene the lights belongs to
  48879. */
  48880. function SpotLight(name, position, direction, angle, exponent, scene) {
  48881. var _this = _super.call(this, name, scene) || this;
  48882. _this._innerAngle = 0;
  48883. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48884. _this._projectionTextureLightNear = 1e-6;
  48885. _this._projectionTextureLightFar = 1000.0;
  48886. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48887. _this._projectionTextureViewLightDirty = true;
  48888. _this._projectionTextureProjectionLightDirty = true;
  48889. _this._projectionTextureDirty = true;
  48890. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48891. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48892. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48893. _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);
  48894. _this.position = position;
  48895. _this.direction = direction;
  48896. _this.angle = angle;
  48897. _this.exponent = exponent;
  48898. return _this;
  48899. }
  48900. Object.defineProperty(SpotLight.prototype, "angle", {
  48901. /**
  48902. * Gets the cone angle of the spot light in Radians.
  48903. */
  48904. get: function () {
  48905. return this._angle;
  48906. },
  48907. /**
  48908. * Sets the cone angle of the spot light in Radians.
  48909. */
  48910. set: function (value) {
  48911. this._angle = value;
  48912. this._cosHalfAngle = Math.cos(value * 0.5);
  48913. this._projectionTextureProjectionLightDirty = true;
  48914. this.forceProjectionMatrixCompute();
  48915. this._computeAngleValues();
  48916. },
  48917. enumerable: true,
  48918. configurable: true
  48919. });
  48920. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  48921. /**
  48922. * Only used in gltf falloff mode, this defines the angle where
  48923. * the directional falloff will start before cutting at angle which could be seen
  48924. * as outer angle.
  48925. */
  48926. get: function () {
  48927. return this._angle;
  48928. },
  48929. /**
  48930. * Only used in gltf falloff mode, this defines the angle where
  48931. * the directional falloff will start before cutting at angle which could be seen
  48932. * as outer angle.
  48933. */
  48934. set: function (value) {
  48935. this._innerAngle = value;
  48936. this._computeAngleValues();
  48937. },
  48938. enumerable: true,
  48939. configurable: true
  48940. });
  48941. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48942. /**
  48943. * Allows scaling the angle of the light for shadow generation only.
  48944. */
  48945. get: function () {
  48946. return this._shadowAngleScale;
  48947. },
  48948. /**
  48949. * Allows scaling the angle of the light for shadow generation only.
  48950. */
  48951. set: function (value) {
  48952. this._shadowAngleScale = value;
  48953. this.forceProjectionMatrixCompute();
  48954. },
  48955. enumerable: true,
  48956. configurable: true
  48957. });
  48958. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48959. /**
  48960. * Allows reading the projecton texture
  48961. */
  48962. get: function () {
  48963. return this._projectionTextureMatrix;
  48964. },
  48965. enumerable: true,
  48966. configurable: true
  48967. });
  48968. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48969. /**
  48970. * Gets the near clip of the Spotlight for texture projection.
  48971. */
  48972. get: function () {
  48973. return this._projectionTextureLightNear;
  48974. },
  48975. /**
  48976. * Sets the near clip of the Spotlight for texture projection.
  48977. */
  48978. set: function (value) {
  48979. this._projectionTextureLightNear = value;
  48980. this._projectionTextureProjectionLightDirty = true;
  48981. },
  48982. enumerable: true,
  48983. configurable: true
  48984. });
  48985. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48986. /**
  48987. * Gets the far clip of the Spotlight for texture projection.
  48988. */
  48989. get: function () {
  48990. return this._projectionTextureLightFar;
  48991. },
  48992. /**
  48993. * Sets the far clip of the Spotlight for texture projection.
  48994. */
  48995. set: function (value) {
  48996. this._projectionTextureLightFar = value;
  48997. this._projectionTextureProjectionLightDirty = true;
  48998. },
  48999. enumerable: true,
  49000. configurable: true
  49001. });
  49002. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49003. /**
  49004. * Gets the Up vector of the Spotlight for texture projection.
  49005. */
  49006. get: function () {
  49007. return this._projectionTextureUpDirection;
  49008. },
  49009. /**
  49010. * Sets the Up vector of the Spotlight for texture projection.
  49011. */
  49012. set: function (value) {
  49013. this._projectionTextureUpDirection = value;
  49014. this._projectionTextureProjectionLightDirty = true;
  49015. },
  49016. enumerable: true,
  49017. configurable: true
  49018. });
  49019. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49020. /**
  49021. * Gets the projection texture of the light.
  49022. */
  49023. get: function () {
  49024. return this._projectionTexture;
  49025. },
  49026. /**
  49027. * Sets the projection texture of the light.
  49028. */
  49029. set: function (value) {
  49030. this._projectionTexture = value;
  49031. this._projectionTextureDirty = true;
  49032. },
  49033. enumerable: true,
  49034. configurable: true
  49035. });
  49036. /**
  49037. * Returns the string "SpotLight".
  49038. * @returns the class name
  49039. */
  49040. SpotLight.prototype.getClassName = function () {
  49041. return "SpotLight";
  49042. };
  49043. /**
  49044. * Returns the integer 2.
  49045. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49046. */
  49047. SpotLight.prototype.getTypeID = function () {
  49048. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49049. };
  49050. /**
  49051. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49052. */
  49053. SpotLight.prototype._setDirection = function (value) {
  49054. _super.prototype._setDirection.call(this, value);
  49055. this._projectionTextureViewLightDirty = true;
  49056. };
  49057. /**
  49058. * Overrides the position setter to recompute the projection texture view light Matrix.
  49059. */
  49060. SpotLight.prototype._setPosition = function (value) {
  49061. _super.prototype._setPosition.call(this, value);
  49062. this._projectionTextureViewLightDirty = true;
  49063. };
  49064. /**
  49065. * 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.
  49066. * Returns the SpotLight.
  49067. */
  49068. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49069. var activeCamera = this.getScene().activeCamera;
  49070. if (!activeCamera) {
  49071. return;
  49072. }
  49073. this._shadowAngleScale = this._shadowAngleScale || 1;
  49074. var angle = this._shadowAngleScale * this._angle;
  49075. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49076. };
  49077. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49078. this._projectionTextureViewLightDirty = false;
  49079. this._projectionTextureDirty = true;
  49080. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49081. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49082. };
  49083. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49084. this._projectionTextureProjectionLightDirty = false;
  49085. this._projectionTextureDirty = true;
  49086. var light_far = this.projectionTextureLightFar;
  49087. var light_near = this.projectionTextureLightNear;
  49088. var P = light_far / (light_far - light_near);
  49089. var Q = -P * light_near;
  49090. var S = 1.0 / Math.tan(this._angle / 2.0);
  49091. var A = 1.0;
  49092. 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);
  49093. };
  49094. /**
  49095. * Main function for light texture projection matrix computing.
  49096. */
  49097. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49098. this._projectionTextureDirty = false;
  49099. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49100. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49101. };
  49102. SpotLight.prototype._buildUniformLayout = function () {
  49103. this._uniformBuffer.addUniform("vLightData", 4);
  49104. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49105. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49106. this._uniformBuffer.addUniform("vLightDirection", 3);
  49107. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49108. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49109. this._uniformBuffer.addUniform("depthValues", 2);
  49110. this._uniformBuffer.create();
  49111. };
  49112. SpotLight.prototype._computeAngleValues = function () {
  49113. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49114. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49115. };
  49116. /**
  49117. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49118. * @param effect The effect to update
  49119. * @param lightIndex The index of the light in the effect to update
  49120. * @returns The spot light
  49121. */
  49122. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49123. var normalizeDirection;
  49124. if (this.computeTransformedInformation()) {
  49125. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49126. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49127. }
  49128. else {
  49129. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49130. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49131. }
  49132. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49133. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49134. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49135. if (this._projectionTextureViewLightDirty) {
  49136. this._computeProjectionTextureViewLightMatrix();
  49137. }
  49138. if (this._projectionTextureProjectionLightDirty) {
  49139. this._computeProjectionTextureProjectionLightMatrix();
  49140. }
  49141. if (this._projectionTextureDirty) {
  49142. this._computeProjectionTextureMatrix();
  49143. }
  49144. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49145. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49146. }
  49147. return this;
  49148. };
  49149. /**
  49150. * Disposes the light and the associated resources.
  49151. */
  49152. SpotLight.prototype.dispose = function () {
  49153. _super.prototype.dispose.call(this);
  49154. if (this._projectionTexture) {
  49155. this._projectionTexture.dispose();
  49156. }
  49157. };
  49158. /**
  49159. * Prepares the list of defines specific to the light type.
  49160. * @param defines the list of defines
  49161. * @param lightIndex defines the index of the light for the effect
  49162. */
  49163. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49164. defines["SPOTLIGHT" + lightIndex] = true;
  49165. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49166. };
  49167. __decorate([
  49168. BABYLON.serialize()
  49169. ], SpotLight.prototype, "angle", null);
  49170. __decorate([
  49171. BABYLON.serialize()
  49172. ], SpotLight.prototype, "innerAngle", null);
  49173. __decorate([
  49174. BABYLON.serialize()
  49175. ], SpotLight.prototype, "shadowAngleScale", null);
  49176. __decorate([
  49177. BABYLON.serialize()
  49178. ], SpotLight.prototype, "exponent", void 0);
  49179. __decorate([
  49180. BABYLON.serialize()
  49181. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49182. __decorate([
  49183. BABYLON.serialize()
  49184. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49185. __decorate([
  49186. BABYLON.serialize()
  49187. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49188. __decorate([
  49189. BABYLON.serializeAsTexture("projectedLightTexture")
  49190. ], SpotLight.prototype, "_projectionTexture", void 0);
  49191. return SpotLight;
  49192. }(BABYLON.ShadowLight));
  49193. BABYLON.SpotLight = SpotLight;
  49194. })(BABYLON || (BABYLON = {}));
  49195. //# sourceMappingURL=babylon.spotLight.js.map
  49196. var BABYLON;
  49197. (function (BABYLON) {
  49198. /**
  49199. * Class used to override all child animations of a given target
  49200. */
  49201. var AnimationPropertiesOverride = /** @class */ (function () {
  49202. function AnimationPropertiesOverride() {
  49203. /**
  49204. * Gets or sets a value indicating if animation blending must be used
  49205. */
  49206. this.enableBlending = false;
  49207. /**
  49208. * Gets or sets the blending speed to use when enableBlending is true
  49209. */
  49210. this.blendingSpeed = 0.01;
  49211. /**
  49212. * Gets or sets the default loop mode to use
  49213. */
  49214. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49215. }
  49216. return AnimationPropertiesOverride;
  49217. }());
  49218. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49219. })(BABYLON || (BABYLON = {}));
  49220. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49221. var BABYLON;
  49222. (function (BABYLON) {
  49223. /**
  49224. * Represents the range of an animation
  49225. */
  49226. var AnimationRange = /** @class */ (function () {
  49227. /**
  49228. * Initializes the range of an animation
  49229. * @param name The name of the animation range
  49230. * @param from The starting frame of the animation
  49231. * @param to The ending frame of the animation
  49232. */
  49233. function AnimationRange(
  49234. /**The name of the animation range**/
  49235. name,
  49236. /**The starting frame of the animation */
  49237. from,
  49238. /**The ending frame of the animation*/
  49239. to) {
  49240. this.name = name;
  49241. this.from = from;
  49242. this.to = to;
  49243. }
  49244. /**
  49245. * Makes a copy of the animation range
  49246. * @returns A copy of the animation range
  49247. */
  49248. AnimationRange.prototype.clone = function () {
  49249. return new AnimationRange(this.name, this.from, this.to);
  49250. };
  49251. return AnimationRange;
  49252. }());
  49253. BABYLON.AnimationRange = AnimationRange;
  49254. /**
  49255. * Composed of a frame, and an action function
  49256. */
  49257. var AnimationEvent = /** @class */ (function () {
  49258. /**
  49259. * Initializes the animation event
  49260. * @param frame The frame for which the event is triggered
  49261. * @param action The event to perform when triggered
  49262. * @param onlyOnce Specifies if the event should be triggered only once
  49263. */
  49264. function AnimationEvent(
  49265. /** The frame for which the event is triggered **/
  49266. frame,
  49267. /** The event to perform when triggered **/
  49268. action,
  49269. /** Specifies if the event should be triggered only once**/
  49270. onlyOnce) {
  49271. this.frame = frame;
  49272. this.action = action;
  49273. this.onlyOnce = onlyOnce;
  49274. /**
  49275. * Specifies if the animation event is done
  49276. */
  49277. this.isDone = false;
  49278. }
  49279. /** @hidden */
  49280. AnimationEvent.prototype._clone = function () {
  49281. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49282. };
  49283. return AnimationEvent;
  49284. }());
  49285. BABYLON.AnimationEvent = AnimationEvent;
  49286. /**
  49287. * A cursor which tracks a point on a path
  49288. */
  49289. var PathCursor = /** @class */ (function () {
  49290. /**
  49291. * Initializes the path cursor
  49292. * @param path The path to track
  49293. */
  49294. function PathCursor(path) {
  49295. this.path = path;
  49296. /**
  49297. * Stores path cursor callbacks for when an onchange event is triggered
  49298. */
  49299. this._onchange = new Array();
  49300. /**
  49301. * The value of the path cursor
  49302. */
  49303. this.value = 0;
  49304. /**
  49305. * The animation array of the path cursor
  49306. */
  49307. this.animations = new Array();
  49308. }
  49309. /**
  49310. * Gets the cursor point on the path
  49311. * @returns A point on the path cursor at the cursor location
  49312. */
  49313. PathCursor.prototype.getPoint = function () {
  49314. var point = this.path.getPointAtLengthPosition(this.value);
  49315. return new BABYLON.Vector3(point.x, 0, point.y);
  49316. };
  49317. /**
  49318. * Moves the cursor ahead by the step amount
  49319. * @param step The amount to move the cursor forward
  49320. * @returns This path cursor
  49321. */
  49322. PathCursor.prototype.moveAhead = function (step) {
  49323. if (step === void 0) { step = 0.002; }
  49324. this.move(step);
  49325. return this;
  49326. };
  49327. /**
  49328. * Moves the cursor behind by the step amount
  49329. * @param step The amount to move the cursor back
  49330. * @returns This path cursor
  49331. */
  49332. PathCursor.prototype.moveBack = function (step) {
  49333. if (step === void 0) { step = 0.002; }
  49334. this.move(-step);
  49335. return this;
  49336. };
  49337. /**
  49338. * Moves the cursor by the step amount
  49339. * If the step amount is greater than one, an exception is thrown
  49340. * @param step The amount to move the cursor
  49341. * @returns This path cursor
  49342. */
  49343. PathCursor.prototype.move = function (step) {
  49344. if (Math.abs(step) > 1) {
  49345. throw "step size should be less than 1.";
  49346. }
  49347. this.value += step;
  49348. this.ensureLimits();
  49349. this.raiseOnChange();
  49350. return this;
  49351. };
  49352. /**
  49353. * Ensures that the value is limited between zero and one
  49354. * @returns This path cursor
  49355. */
  49356. PathCursor.prototype.ensureLimits = function () {
  49357. while (this.value > 1) {
  49358. this.value -= 1;
  49359. }
  49360. while (this.value < 0) {
  49361. this.value += 1;
  49362. }
  49363. return this;
  49364. };
  49365. /**
  49366. * Runs onchange callbacks on change (used by the animation engine)
  49367. * @returns This path cursor
  49368. */
  49369. PathCursor.prototype.raiseOnChange = function () {
  49370. var _this = this;
  49371. this._onchange.forEach(function (f) { return f(_this); });
  49372. return this;
  49373. };
  49374. /**
  49375. * Executes a function on change
  49376. * @param f A path cursor onchange callback
  49377. * @returns This path cursor
  49378. */
  49379. PathCursor.prototype.onchange = function (f) {
  49380. this._onchange.push(f);
  49381. return this;
  49382. };
  49383. return PathCursor;
  49384. }());
  49385. BABYLON.PathCursor = PathCursor;
  49386. /**
  49387. * Enum for the animation key frame interpolation type
  49388. */
  49389. var AnimationKeyInterpolation;
  49390. (function (AnimationKeyInterpolation) {
  49391. /**
  49392. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49393. */
  49394. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49395. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49396. /**
  49397. * Class used to store any kind of animation
  49398. */
  49399. var Animation = /** @class */ (function () {
  49400. /**
  49401. * Initializes the animation
  49402. * @param name Name of the animation
  49403. * @param targetProperty Property to animate
  49404. * @param framePerSecond The frames per second of the animation
  49405. * @param dataType The data type of the animation
  49406. * @param loopMode The loop mode of the animation
  49407. * @param enableBlendings Specifies if blending should be enabled
  49408. */
  49409. function Animation(
  49410. /**Name of the animation */
  49411. name,
  49412. /**Property to animate */
  49413. targetProperty,
  49414. /**The frames per second of the animation */
  49415. framePerSecond,
  49416. /**The data type of the animation */
  49417. dataType,
  49418. /**The loop mode of the animation */
  49419. loopMode,
  49420. /**Specifies if blending should be enabled */
  49421. enableBlending) {
  49422. this.name = name;
  49423. this.targetProperty = targetProperty;
  49424. this.framePerSecond = framePerSecond;
  49425. this.dataType = dataType;
  49426. this.loopMode = loopMode;
  49427. this.enableBlending = enableBlending;
  49428. /**
  49429. * @hidden Internal use only
  49430. */
  49431. this._runtimeAnimations = new Array();
  49432. /**
  49433. * The set of event that will be linked to this animation
  49434. */
  49435. this._events = new Array();
  49436. /**
  49437. * Stores the blending speed of the animation
  49438. */
  49439. this.blendingSpeed = 0.01;
  49440. /**
  49441. * Stores the animation ranges for the animation
  49442. */
  49443. this._ranges = {};
  49444. this.targetPropertyPath = targetProperty.split(".");
  49445. this.dataType = dataType;
  49446. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49447. }
  49448. /**
  49449. * @hidden Internal use
  49450. */
  49451. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49452. var dataType = undefined;
  49453. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49454. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49455. }
  49456. else if (from instanceof BABYLON.Quaternion) {
  49457. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49458. }
  49459. else if (from instanceof BABYLON.Vector3) {
  49460. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49461. }
  49462. else if (from instanceof BABYLON.Vector2) {
  49463. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49464. }
  49465. else if (from instanceof BABYLON.Color3) {
  49466. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49467. }
  49468. else if (from instanceof BABYLON.Size) {
  49469. dataType = Animation.ANIMATIONTYPE_SIZE;
  49470. }
  49471. if (dataType == undefined) {
  49472. return null;
  49473. }
  49474. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49475. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49476. animation.setKeys(keys);
  49477. if (easingFunction !== undefined) {
  49478. animation.setEasingFunction(easingFunction);
  49479. }
  49480. return animation;
  49481. };
  49482. /**
  49483. * Sets up an animation
  49484. * @param property The property to animate
  49485. * @param animationType The animation type to apply
  49486. * @param framePerSecond The frames per second of the animation
  49487. * @param easingFunction The easing function used in the animation
  49488. * @returns The created animation
  49489. */
  49490. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49491. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49492. animation.setEasingFunction(easingFunction);
  49493. return animation;
  49494. };
  49495. /**
  49496. * Create and start an animation on a node
  49497. * @param name defines the name of the global animation that will be run on all nodes
  49498. * @param node defines the root node where the animation will take place
  49499. * @param targetProperty defines property to animate
  49500. * @param framePerSecond defines the number of frame per second yo use
  49501. * @param totalFrame defines the number of frames in total
  49502. * @param from defines the initial value
  49503. * @param to defines the final value
  49504. * @param loopMode defines which loop mode you want to use (off by default)
  49505. * @param easingFunction defines the easing function to use (linear by default)
  49506. * @param onAnimationEnd defines the callback to call when animation end
  49507. * @returns the animatable created for this animation
  49508. */
  49509. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49510. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49511. if (!animation) {
  49512. return null;
  49513. }
  49514. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49515. };
  49516. /**
  49517. * Create and start an animation on a node and its descendants
  49518. * @param name defines the name of the global animation that will be run on all nodes
  49519. * @param node defines the root node where the animation will take place
  49520. * @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
  49521. * @param targetProperty defines property to animate
  49522. * @param framePerSecond defines the number of frame per second to use
  49523. * @param totalFrame defines the number of frames in total
  49524. * @param from defines the initial value
  49525. * @param to defines the final value
  49526. * @param loopMode defines which loop mode you want to use (off by default)
  49527. * @param easingFunction defines the easing function to use (linear by default)
  49528. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49529. * @returns the list of animatables created for all nodes
  49530. * @example https://www.babylonjs-playground.com/#MH0VLI
  49531. */
  49532. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49533. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49534. if (!animation) {
  49535. return null;
  49536. }
  49537. var scene = node.getScene();
  49538. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49539. };
  49540. /**
  49541. * Creates a new animation, merges it with the existing animations and starts it
  49542. * @param name Name of the animation
  49543. * @param node Node which contains the scene that begins the animations
  49544. * @param targetProperty Specifies which property to animate
  49545. * @param framePerSecond The frames per second of the animation
  49546. * @param totalFrame The total number of frames
  49547. * @param from The frame at the beginning of the animation
  49548. * @param to The frame at the end of the animation
  49549. * @param loopMode Specifies the loop mode of the animation
  49550. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49551. * @param onAnimationEnd Callback to run once the animation is complete
  49552. * @returns Nullable animation
  49553. */
  49554. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49555. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49556. if (!animation) {
  49557. return null;
  49558. }
  49559. node.animations.push(animation);
  49560. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49561. };
  49562. /**
  49563. * Transition property of an host to the target Value
  49564. * @param property The property to transition
  49565. * @param targetValue The target Value of the property
  49566. * @param host The object where the property to animate belongs
  49567. * @param scene Scene used to run the animation
  49568. * @param frameRate Framerate (in frame/s) to use
  49569. * @param transition The transition type we want to use
  49570. * @param duration The duration of the animation, in milliseconds
  49571. * @param onAnimationEnd Callback trigger at the end of the animation
  49572. * @returns Nullable animation
  49573. */
  49574. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49575. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49576. if (duration <= 0) {
  49577. host[property] = targetValue;
  49578. if (onAnimationEnd) {
  49579. onAnimationEnd();
  49580. }
  49581. return null;
  49582. }
  49583. var endFrame = frameRate * (duration / 1000);
  49584. transition.setKeys([{
  49585. frame: 0,
  49586. value: host[property].clone ? host[property].clone() : host[property]
  49587. },
  49588. {
  49589. frame: endFrame,
  49590. value: targetValue
  49591. }]);
  49592. if (!host.animations) {
  49593. host.animations = [];
  49594. }
  49595. host.animations.push(transition);
  49596. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49597. animation.onAnimationEnd = onAnimationEnd;
  49598. return animation;
  49599. };
  49600. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49601. /**
  49602. * Return the array of runtime animations currently using this animation
  49603. */
  49604. get: function () {
  49605. return this._runtimeAnimations;
  49606. },
  49607. enumerable: true,
  49608. configurable: true
  49609. });
  49610. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49611. /**
  49612. * Specifies if any of the runtime animations are currently running
  49613. */
  49614. get: function () {
  49615. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49616. var runtimeAnimation = _a[_i];
  49617. if (!runtimeAnimation.isStopped) {
  49618. return true;
  49619. }
  49620. }
  49621. return false;
  49622. },
  49623. enumerable: true,
  49624. configurable: true
  49625. });
  49626. // Methods
  49627. /**
  49628. * Converts the animation to a string
  49629. * @param fullDetails support for multiple levels of logging within scene loading
  49630. * @returns String form of the animation
  49631. */
  49632. Animation.prototype.toString = function (fullDetails) {
  49633. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49634. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49635. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49636. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49637. if (fullDetails) {
  49638. ret += ", Ranges: {";
  49639. var first = true;
  49640. for (var name in this._ranges) {
  49641. if (first) {
  49642. ret += ", ";
  49643. first = false;
  49644. }
  49645. ret += name;
  49646. }
  49647. ret += "}";
  49648. }
  49649. return ret;
  49650. };
  49651. /**
  49652. * Add an event to this animation
  49653. * @param event Event to add
  49654. */
  49655. Animation.prototype.addEvent = function (event) {
  49656. this._events.push(event);
  49657. };
  49658. /**
  49659. * Remove all events found at the given frame
  49660. * @param frame The frame to remove events from
  49661. */
  49662. Animation.prototype.removeEvents = function (frame) {
  49663. for (var index = 0; index < this._events.length; index++) {
  49664. if (this._events[index].frame === frame) {
  49665. this._events.splice(index, 1);
  49666. index--;
  49667. }
  49668. }
  49669. };
  49670. /**
  49671. * Retrieves all the events from the animation
  49672. * @returns Events from the animation
  49673. */
  49674. Animation.prototype.getEvents = function () {
  49675. return this._events;
  49676. };
  49677. /**
  49678. * Creates an animation range
  49679. * @param name Name of the animation range
  49680. * @param from Starting frame of the animation range
  49681. * @param to Ending frame of the animation
  49682. */
  49683. Animation.prototype.createRange = function (name, from, to) {
  49684. // check name not already in use; could happen for bones after serialized
  49685. if (!this._ranges[name]) {
  49686. this._ranges[name] = new AnimationRange(name, from, to);
  49687. }
  49688. };
  49689. /**
  49690. * Deletes an animation range by name
  49691. * @param name Name of the animation range to delete
  49692. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49693. */
  49694. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49695. if (deleteFrames === void 0) { deleteFrames = true; }
  49696. var range = this._ranges[name];
  49697. if (!range) {
  49698. return;
  49699. }
  49700. if (deleteFrames) {
  49701. var from = range.from;
  49702. var to = range.to;
  49703. // this loop MUST go high to low for multiple splices to work
  49704. for (var key = this._keys.length - 1; key >= 0; key--) {
  49705. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49706. this._keys.splice(key, 1);
  49707. }
  49708. }
  49709. }
  49710. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49711. };
  49712. /**
  49713. * Gets the animation range by name, or null if not defined
  49714. * @param name Name of the animation range
  49715. * @returns Nullable animation range
  49716. */
  49717. Animation.prototype.getRange = function (name) {
  49718. return this._ranges[name];
  49719. };
  49720. /**
  49721. * Gets the key frames from the animation
  49722. * @returns The key frames of the animation
  49723. */
  49724. Animation.prototype.getKeys = function () {
  49725. return this._keys;
  49726. };
  49727. /**
  49728. * Gets the highest frame rate of the animation
  49729. * @returns Highest frame rate of the animation
  49730. */
  49731. Animation.prototype.getHighestFrame = function () {
  49732. var ret = 0;
  49733. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49734. if (ret < this._keys[key].frame) {
  49735. ret = this._keys[key].frame;
  49736. }
  49737. }
  49738. return ret;
  49739. };
  49740. /**
  49741. * Gets the easing function of the animation
  49742. * @returns Easing function of the animation
  49743. */
  49744. Animation.prototype.getEasingFunction = function () {
  49745. return this._easingFunction;
  49746. };
  49747. /**
  49748. * Sets the easing function of the animation
  49749. * @param easingFunction A custom mathematical formula for animation
  49750. */
  49751. Animation.prototype.setEasingFunction = function (easingFunction) {
  49752. this._easingFunction = easingFunction;
  49753. };
  49754. /**
  49755. * Interpolates a scalar linearly
  49756. * @param startValue Start value of the animation curve
  49757. * @param endValue End value of the animation curve
  49758. * @param gradient Scalar amount to interpolate
  49759. * @returns Interpolated scalar value
  49760. */
  49761. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49762. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49763. };
  49764. /**
  49765. * Interpolates a scalar cubically
  49766. * @param startValue Start value of the animation curve
  49767. * @param outTangent End tangent of the animation
  49768. * @param endValue End value of the animation curve
  49769. * @param inTangent Start tangent of the animation curve
  49770. * @param gradient Scalar amount to interpolate
  49771. * @returns Interpolated scalar value
  49772. */
  49773. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49774. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49775. };
  49776. /**
  49777. * Interpolates a quaternion using a spherical linear interpolation
  49778. * @param startValue Start value of the animation curve
  49779. * @param endValue End value of the animation curve
  49780. * @param gradient Scalar amount to interpolate
  49781. * @returns Interpolated quaternion value
  49782. */
  49783. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49784. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49785. };
  49786. /**
  49787. * Interpolates a quaternion cubically
  49788. * @param startValue Start value of the animation curve
  49789. * @param outTangent End tangent of the animation curve
  49790. * @param endValue End value of the animation curve
  49791. * @param inTangent Start tangent of the animation curve
  49792. * @param gradient Scalar amount to interpolate
  49793. * @returns Interpolated quaternion value
  49794. */
  49795. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49796. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49797. };
  49798. /**
  49799. * Interpolates a Vector3 linearl
  49800. * @param startValue Start value of the animation curve
  49801. * @param endValue End value of the animation curve
  49802. * @param gradient Scalar amount to interpolate
  49803. * @returns Interpolated scalar value
  49804. */
  49805. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49806. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49807. };
  49808. /**
  49809. * Interpolates a Vector3 cubically
  49810. * @param startValue Start value of the animation curve
  49811. * @param outTangent End tangent of the animation
  49812. * @param endValue End value of the animation curve
  49813. * @param inTangent Start tangent of the animation curve
  49814. * @param gradient Scalar amount to interpolate
  49815. * @returns InterpolatedVector3 value
  49816. */
  49817. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49818. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49819. };
  49820. /**
  49821. * Interpolates a Vector2 linearly
  49822. * @param startValue Start value of the animation curve
  49823. * @param endValue End value of the animation curve
  49824. * @param gradient Scalar amount to interpolate
  49825. * @returns Interpolated Vector2 value
  49826. */
  49827. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49828. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49829. };
  49830. /**
  49831. * Interpolates a Vector2 cubically
  49832. * @param startValue Start value of the animation curve
  49833. * @param outTangent End tangent of the animation
  49834. * @param endValue End value of the animation curve
  49835. * @param inTangent Start tangent of the animation curve
  49836. * @param gradient Scalar amount to interpolate
  49837. * @returns Interpolated Vector2 value
  49838. */
  49839. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49840. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49841. };
  49842. /**
  49843. * Interpolates a size linearly
  49844. * @param startValue Start value of the animation curve
  49845. * @param endValue End value of the animation curve
  49846. * @param gradient Scalar amount to interpolate
  49847. * @returns Interpolated Size value
  49848. */
  49849. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49850. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49851. };
  49852. /**
  49853. * Interpolates a Color3 linearly
  49854. * @param startValue Start value of the animation curve
  49855. * @param endValue End value of the animation curve
  49856. * @param gradient Scalar amount to interpolate
  49857. * @returns Interpolated Color3 value
  49858. */
  49859. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49860. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49861. };
  49862. /**
  49863. * @hidden Internal use only
  49864. */
  49865. Animation.prototype._getKeyValue = function (value) {
  49866. if (typeof value === "function") {
  49867. return value();
  49868. }
  49869. return value;
  49870. };
  49871. /**
  49872. * @hidden Internal use only
  49873. */
  49874. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49875. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49876. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49877. }
  49878. var keys = this.getKeys();
  49879. // Try to get a hash to find the right key
  49880. 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));
  49881. if (keys[startKeyIndex].frame >= currentFrame) {
  49882. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49883. startKeyIndex--;
  49884. }
  49885. }
  49886. for (var key = startKeyIndex; key < keys.length; key++) {
  49887. var endKey = keys[key + 1];
  49888. if (endKey.frame >= currentFrame) {
  49889. var startKey = keys[key];
  49890. var startValue = this._getKeyValue(startKey.value);
  49891. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49892. return startValue;
  49893. }
  49894. var endValue = this._getKeyValue(endKey.value);
  49895. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49896. var frameDelta = endKey.frame - startKey.frame;
  49897. // gradient : percent of currentFrame between the frame inf and the frame sup
  49898. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49899. // check for easingFunction and correction of gradient
  49900. var easingFunction = this.getEasingFunction();
  49901. if (easingFunction != null) {
  49902. gradient = easingFunction.ease(gradient);
  49903. }
  49904. switch (this.dataType) {
  49905. // Float
  49906. case Animation.ANIMATIONTYPE_FLOAT:
  49907. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49908. switch (loopMode) {
  49909. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49910. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49911. return floatValue;
  49912. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49913. return offsetValue * repeatCount + floatValue;
  49914. }
  49915. break;
  49916. // Quaternion
  49917. case Animation.ANIMATIONTYPE_QUATERNION:
  49918. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49919. switch (loopMode) {
  49920. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49921. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49922. return quatValue;
  49923. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49924. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49925. }
  49926. return quatValue;
  49927. // Vector3
  49928. case Animation.ANIMATIONTYPE_VECTOR3:
  49929. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49930. switch (loopMode) {
  49931. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49932. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49933. return vec3Value;
  49934. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49935. return vec3Value.add(offsetValue.scale(repeatCount));
  49936. }
  49937. // Vector2
  49938. case Animation.ANIMATIONTYPE_VECTOR2:
  49939. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49940. switch (loopMode) {
  49941. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49942. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49943. return vec2Value;
  49944. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49945. return vec2Value.add(offsetValue.scale(repeatCount));
  49946. }
  49947. // Size
  49948. case Animation.ANIMATIONTYPE_SIZE:
  49949. switch (loopMode) {
  49950. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49951. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49952. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49953. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49954. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49955. }
  49956. // Color3
  49957. case Animation.ANIMATIONTYPE_COLOR3:
  49958. switch (loopMode) {
  49959. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49960. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49961. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49962. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49963. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49964. }
  49965. // Matrix
  49966. case Animation.ANIMATIONTYPE_MATRIX:
  49967. switch (loopMode) {
  49968. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49969. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49970. if (Animation.AllowMatricesInterpolation) {
  49971. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49972. }
  49973. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49974. return startValue;
  49975. }
  49976. default:
  49977. break;
  49978. }
  49979. break;
  49980. }
  49981. }
  49982. return this._getKeyValue(keys[keys.length - 1].value);
  49983. };
  49984. /**
  49985. * Defines the function to use to interpolate matrices
  49986. * @param startValue defines the start matrix
  49987. * @param endValue defines the end matrix
  49988. * @param gradient defines the gradient between both matrices
  49989. * @param result defines an optional target matrix where to store the interpolation
  49990. * @returns the interpolated matrix
  49991. */
  49992. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49993. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49994. if (result) {
  49995. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49996. return result;
  49997. }
  49998. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49999. }
  50000. if (result) {
  50001. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50002. return result;
  50003. }
  50004. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50005. };
  50006. /**
  50007. * Makes a copy of the animation
  50008. * @returns Cloned animation
  50009. */
  50010. Animation.prototype.clone = function () {
  50011. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50012. clone.enableBlending = this.enableBlending;
  50013. clone.blendingSpeed = this.blendingSpeed;
  50014. if (this._keys) {
  50015. clone.setKeys(this._keys);
  50016. }
  50017. if (this._ranges) {
  50018. clone._ranges = {};
  50019. for (var name in this._ranges) {
  50020. var range = this._ranges[name];
  50021. if (!range) {
  50022. continue;
  50023. }
  50024. clone._ranges[name] = range.clone();
  50025. }
  50026. }
  50027. return clone;
  50028. };
  50029. /**
  50030. * Sets the key frames of the animation
  50031. * @param values The animation key frames to set
  50032. */
  50033. Animation.prototype.setKeys = function (values) {
  50034. this._keys = values.slice(0);
  50035. };
  50036. /**
  50037. * Serializes the animation to an object
  50038. * @returns Serialized object
  50039. */
  50040. Animation.prototype.serialize = function () {
  50041. var serializationObject = {};
  50042. serializationObject.name = this.name;
  50043. serializationObject.property = this.targetProperty;
  50044. serializationObject.framePerSecond = this.framePerSecond;
  50045. serializationObject.dataType = this.dataType;
  50046. serializationObject.loopBehavior = this.loopMode;
  50047. serializationObject.enableBlending = this.enableBlending;
  50048. serializationObject.blendingSpeed = this.blendingSpeed;
  50049. var dataType = this.dataType;
  50050. serializationObject.keys = [];
  50051. var keys = this.getKeys();
  50052. for (var index = 0; index < keys.length; index++) {
  50053. var animationKey = keys[index];
  50054. var key = {};
  50055. key.frame = animationKey.frame;
  50056. switch (dataType) {
  50057. case Animation.ANIMATIONTYPE_FLOAT:
  50058. key.values = [animationKey.value];
  50059. break;
  50060. case Animation.ANIMATIONTYPE_QUATERNION:
  50061. case Animation.ANIMATIONTYPE_MATRIX:
  50062. case Animation.ANIMATIONTYPE_VECTOR3:
  50063. case Animation.ANIMATIONTYPE_COLOR3:
  50064. key.values = animationKey.value.asArray();
  50065. break;
  50066. }
  50067. serializationObject.keys.push(key);
  50068. }
  50069. serializationObject.ranges = [];
  50070. for (var name in this._ranges) {
  50071. var source = this._ranges[name];
  50072. if (!source) {
  50073. continue;
  50074. }
  50075. var range = {};
  50076. range.name = name;
  50077. range.from = source.from;
  50078. range.to = source.to;
  50079. serializationObject.ranges.push(range);
  50080. }
  50081. return serializationObject;
  50082. };
  50083. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50084. /**
  50085. * Get the float animation type
  50086. */
  50087. get: function () {
  50088. return Animation._ANIMATIONTYPE_FLOAT;
  50089. },
  50090. enumerable: true,
  50091. configurable: true
  50092. });
  50093. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50094. /**
  50095. * Get the Vector3 animation type
  50096. */
  50097. get: function () {
  50098. return Animation._ANIMATIONTYPE_VECTOR3;
  50099. },
  50100. enumerable: true,
  50101. configurable: true
  50102. });
  50103. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50104. /**
  50105. * Get the Vector2 animation type
  50106. */
  50107. get: function () {
  50108. return Animation._ANIMATIONTYPE_VECTOR2;
  50109. },
  50110. enumerable: true,
  50111. configurable: true
  50112. });
  50113. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50114. /**
  50115. * Get the Size animation type
  50116. */
  50117. get: function () {
  50118. return Animation._ANIMATIONTYPE_SIZE;
  50119. },
  50120. enumerable: true,
  50121. configurable: true
  50122. });
  50123. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50124. /**
  50125. * Get the Quaternion animation type
  50126. */
  50127. get: function () {
  50128. return Animation._ANIMATIONTYPE_QUATERNION;
  50129. },
  50130. enumerable: true,
  50131. configurable: true
  50132. });
  50133. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50134. /**
  50135. * Get the Matrix animation type
  50136. */
  50137. get: function () {
  50138. return Animation._ANIMATIONTYPE_MATRIX;
  50139. },
  50140. enumerable: true,
  50141. configurable: true
  50142. });
  50143. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50144. /**
  50145. * Get the Color3 animation type
  50146. */
  50147. get: function () {
  50148. return Animation._ANIMATIONTYPE_COLOR3;
  50149. },
  50150. enumerable: true,
  50151. configurable: true
  50152. });
  50153. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50154. /**
  50155. * Get the Relative Loop Mode
  50156. */
  50157. get: function () {
  50158. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50159. },
  50160. enumerable: true,
  50161. configurable: true
  50162. });
  50163. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50164. /**
  50165. * Get the Cycle Loop Mode
  50166. */
  50167. get: function () {
  50168. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50169. },
  50170. enumerable: true,
  50171. configurable: true
  50172. });
  50173. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50174. /**
  50175. * Get the Constant Loop Mode
  50176. */
  50177. get: function () {
  50178. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50179. },
  50180. enumerable: true,
  50181. configurable: true
  50182. });
  50183. /** @hidden */
  50184. Animation._UniversalLerp = function (left, right, amount) {
  50185. var constructor = left.constructor;
  50186. if (constructor.Lerp) { // Lerp supported
  50187. return constructor.Lerp(left, right, amount);
  50188. }
  50189. else if (constructor.Slerp) { // Slerp supported
  50190. return constructor.Slerp(left, right, amount);
  50191. }
  50192. else if (left.toFixed) { // Number
  50193. return left * (1.0 - amount) + amount * right;
  50194. }
  50195. else { // Blending not supported
  50196. return right;
  50197. }
  50198. };
  50199. /**
  50200. * Parses an animation object and creates an animation
  50201. * @param parsedAnimation Parsed animation object
  50202. * @returns Animation object
  50203. */
  50204. Animation.Parse = function (parsedAnimation) {
  50205. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50206. var dataType = parsedAnimation.dataType;
  50207. var keys = [];
  50208. var data;
  50209. var index;
  50210. if (parsedAnimation.enableBlending) {
  50211. animation.enableBlending = parsedAnimation.enableBlending;
  50212. }
  50213. if (parsedAnimation.blendingSpeed) {
  50214. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50215. }
  50216. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50217. var key = parsedAnimation.keys[index];
  50218. var inTangent;
  50219. var outTangent;
  50220. switch (dataType) {
  50221. case Animation.ANIMATIONTYPE_FLOAT:
  50222. data = key.values[0];
  50223. if (key.values.length >= 1) {
  50224. inTangent = key.values[1];
  50225. }
  50226. if (key.values.length >= 2) {
  50227. outTangent = key.values[2];
  50228. }
  50229. break;
  50230. case Animation.ANIMATIONTYPE_QUATERNION:
  50231. data = BABYLON.Quaternion.FromArray(key.values);
  50232. if (key.values.length >= 8) {
  50233. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50234. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50235. inTangent = _inTangent;
  50236. }
  50237. }
  50238. if (key.values.length >= 12) {
  50239. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50240. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50241. outTangent = _outTangent;
  50242. }
  50243. }
  50244. break;
  50245. case Animation.ANIMATIONTYPE_MATRIX:
  50246. data = BABYLON.Matrix.FromArray(key.values);
  50247. break;
  50248. case Animation.ANIMATIONTYPE_COLOR3:
  50249. data = BABYLON.Color3.FromArray(key.values);
  50250. break;
  50251. case Animation.ANIMATIONTYPE_VECTOR3:
  50252. default:
  50253. data = BABYLON.Vector3.FromArray(key.values);
  50254. break;
  50255. }
  50256. var keyData = {};
  50257. keyData.frame = key.frame;
  50258. keyData.value = data;
  50259. if (inTangent != undefined) {
  50260. keyData.inTangent = inTangent;
  50261. }
  50262. if (outTangent != undefined) {
  50263. keyData.outTangent = outTangent;
  50264. }
  50265. keys.push(keyData);
  50266. }
  50267. animation.setKeys(keys);
  50268. if (parsedAnimation.ranges) {
  50269. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50270. data = parsedAnimation.ranges[index];
  50271. animation.createRange(data.name, data.from, data.to);
  50272. }
  50273. }
  50274. return animation;
  50275. };
  50276. /**
  50277. * Appends the serialized animations from the source animations
  50278. * @param source Source containing the animations
  50279. * @param destination Target to store the animations
  50280. */
  50281. Animation.AppendSerializedAnimations = function (source, destination) {
  50282. if (source.animations) {
  50283. destination.animations = [];
  50284. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50285. var animation = source.animations[animationIndex];
  50286. destination.animations.push(animation.serialize());
  50287. }
  50288. }
  50289. };
  50290. /**
  50291. * Use matrix interpolation instead of using direct key value when animating matrices
  50292. */
  50293. Animation.AllowMatricesInterpolation = false;
  50294. /**
  50295. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50296. */
  50297. Animation.AllowMatrixDecomposeForInterpolation = true;
  50298. // Statics
  50299. /**
  50300. * Float animation type
  50301. */
  50302. Animation._ANIMATIONTYPE_FLOAT = 0;
  50303. /**
  50304. * Vector3 animation type
  50305. */
  50306. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50307. /**
  50308. * Quaternion animation type
  50309. */
  50310. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50311. /**
  50312. * Matrix animation type
  50313. */
  50314. Animation._ANIMATIONTYPE_MATRIX = 3;
  50315. /**
  50316. * Color3 animation type
  50317. */
  50318. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50319. /**
  50320. * Vector2 animation type
  50321. */
  50322. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50323. /**
  50324. * Size animation type
  50325. */
  50326. Animation._ANIMATIONTYPE_SIZE = 6;
  50327. /**
  50328. * Relative Loop Mode
  50329. */
  50330. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50331. /**
  50332. * Cycle Loop Mode
  50333. */
  50334. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50335. /**
  50336. * Constant Loop Mode
  50337. */
  50338. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50339. return Animation;
  50340. }());
  50341. BABYLON.Animation = Animation;
  50342. })(BABYLON || (BABYLON = {}));
  50343. //# sourceMappingURL=babylon.animation.js.map
  50344. var BABYLON;
  50345. (function (BABYLON) {
  50346. /**
  50347. * This class defines the direct association between an animation and a target
  50348. */
  50349. var TargetedAnimation = /** @class */ (function () {
  50350. function TargetedAnimation() {
  50351. }
  50352. return TargetedAnimation;
  50353. }());
  50354. BABYLON.TargetedAnimation = TargetedAnimation;
  50355. /**
  50356. * Use this class to create coordinated animations on multiple targets
  50357. */
  50358. var AnimationGroup = /** @class */ (function () {
  50359. function AnimationGroup(name, scene) {
  50360. if (scene === void 0) { scene = null; }
  50361. this.name = name;
  50362. this._targetedAnimations = new Array();
  50363. this._animatables = new Array();
  50364. this._from = Number.MAX_VALUE;
  50365. this._to = -Number.MAX_VALUE;
  50366. this._speedRatio = 1;
  50367. this.onAnimationEndObservable = new BABYLON.Observable();
  50368. /**
  50369. * This observable will notify when all animations have ended.
  50370. */
  50371. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50372. /**
  50373. * This observable will notify when all animations have paused.
  50374. */
  50375. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50376. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50377. this._scene.animationGroups.push(this);
  50378. }
  50379. Object.defineProperty(AnimationGroup.prototype, "from", {
  50380. /**
  50381. * Gets the first frame
  50382. */
  50383. get: function () {
  50384. return this._from;
  50385. },
  50386. enumerable: true,
  50387. configurable: true
  50388. });
  50389. Object.defineProperty(AnimationGroup.prototype, "to", {
  50390. /**
  50391. * Gets the last frame
  50392. */
  50393. get: function () {
  50394. return this._to;
  50395. },
  50396. enumerable: true,
  50397. configurable: true
  50398. });
  50399. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50400. /**
  50401. * Define if the animations are started
  50402. */
  50403. get: function () {
  50404. return this._isStarted;
  50405. },
  50406. enumerable: true,
  50407. configurable: true
  50408. });
  50409. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50410. /**
  50411. * Gets or sets the speed ratio to use for all animations
  50412. */
  50413. get: function () {
  50414. return this._speedRatio;
  50415. },
  50416. /**
  50417. * Gets or sets the speed ratio to use for all animations
  50418. */
  50419. set: function (value) {
  50420. if (this._speedRatio === value) {
  50421. return;
  50422. }
  50423. this._speedRatio = value;
  50424. for (var index = 0; index < this._animatables.length; index++) {
  50425. var animatable = this._animatables[index];
  50426. animatable.speedRatio = this._speedRatio;
  50427. }
  50428. },
  50429. enumerable: true,
  50430. configurable: true
  50431. });
  50432. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50433. /**
  50434. * Gets the targeted animations for this animation group
  50435. */
  50436. get: function () {
  50437. return this._targetedAnimations;
  50438. },
  50439. enumerable: true,
  50440. configurable: true
  50441. });
  50442. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50443. /**
  50444. * returning the list of animatables controlled by this animation group.
  50445. */
  50446. get: function () {
  50447. return this._animatables;
  50448. },
  50449. enumerable: true,
  50450. configurable: true
  50451. });
  50452. /**
  50453. * Add an animation (with its target) in the group
  50454. * @param animation defines the animation we want to add
  50455. * @param target defines the target of the animation
  50456. * @returns the {BABYLON.TargetedAnimation} object
  50457. */
  50458. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50459. var targetedAnimation = {
  50460. animation: animation,
  50461. target: target
  50462. };
  50463. var keys = animation.getKeys();
  50464. if (this._from > keys[0].frame) {
  50465. this._from = keys[0].frame;
  50466. }
  50467. if (this._to < keys[keys.length - 1].frame) {
  50468. this._to = keys[keys.length - 1].frame;
  50469. }
  50470. this._targetedAnimations.push(targetedAnimation);
  50471. return targetedAnimation;
  50472. };
  50473. /**
  50474. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50475. * It can add constant keys at begin or end
  50476. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50477. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50478. */
  50479. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50480. if (beginFrame === void 0) { beginFrame = null; }
  50481. if (endFrame === void 0) { endFrame = null; }
  50482. if (beginFrame == null)
  50483. beginFrame = this._from;
  50484. if (endFrame == null)
  50485. endFrame = this._to;
  50486. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50487. var targetedAnimation = this._targetedAnimations[index];
  50488. var keys = targetedAnimation.animation.getKeys();
  50489. var startKey = keys[0];
  50490. var endKey = keys[keys.length - 1];
  50491. if (startKey.frame > beginFrame) {
  50492. var newKey = {
  50493. frame: beginFrame,
  50494. value: startKey.value,
  50495. inTangent: startKey.inTangent,
  50496. outTangent: startKey.outTangent,
  50497. interpolation: startKey.interpolation
  50498. };
  50499. keys.splice(0, 0, newKey);
  50500. }
  50501. if (endKey.frame < endFrame) {
  50502. var newKey = {
  50503. frame: endFrame,
  50504. value: endKey.value,
  50505. inTangent: endKey.outTangent,
  50506. outTangent: endKey.outTangent,
  50507. interpolation: endKey.interpolation
  50508. };
  50509. keys.push(newKey);
  50510. }
  50511. }
  50512. this._from = beginFrame;
  50513. this._to = endFrame;
  50514. return this;
  50515. };
  50516. /**
  50517. * Start all animations on given targets
  50518. * @param loop defines if animations must loop
  50519. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50520. * @param from defines the from key (optional)
  50521. * @param to defines the to key (optional)
  50522. * @returns the current animation group
  50523. */
  50524. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50525. var _this = this;
  50526. if (loop === void 0) { loop = false; }
  50527. if (speedRatio === void 0) { speedRatio = 1; }
  50528. if (this._isStarted || this._targetedAnimations.length === 0) {
  50529. return this;
  50530. }
  50531. var _loop_1 = function (targetedAnimation) {
  50532. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50533. animatable.onAnimationEnd = function () {
  50534. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50535. _this._checkAnimationGroupEnded(animatable);
  50536. };
  50537. this_1._animatables.push(animatable);
  50538. };
  50539. var this_1 = this;
  50540. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50541. var targetedAnimation = _a[_i];
  50542. _loop_1(targetedAnimation);
  50543. }
  50544. this._speedRatio = speedRatio;
  50545. this._isStarted = true;
  50546. return this;
  50547. };
  50548. /**
  50549. * Pause all animations
  50550. */
  50551. AnimationGroup.prototype.pause = function () {
  50552. if (!this._isStarted) {
  50553. return this;
  50554. }
  50555. for (var index = 0; index < this._animatables.length; index++) {
  50556. var animatable = this._animatables[index];
  50557. animatable.pause();
  50558. }
  50559. this.onAnimationGroupPauseObservable.notifyObservers(this);
  50560. return this;
  50561. };
  50562. /**
  50563. * Play all animations to initial state
  50564. * This function will start() the animations if they were not started or will restart() them if they were paused
  50565. * @param loop defines if animations must loop
  50566. */
  50567. AnimationGroup.prototype.play = function (loop) {
  50568. // only if all animatables are ready and exist
  50569. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50570. if (loop !== undefined) {
  50571. for (var index = 0; index < this._animatables.length; index++) {
  50572. var animatable = this._animatables[index];
  50573. animatable.loopAnimation = loop;
  50574. }
  50575. }
  50576. this.restart();
  50577. }
  50578. else {
  50579. this.stop();
  50580. this.start(loop, this._speedRatio);
  50581. }
  50582. return this;
  50583. };
  50584. /**
  50585. * Reset all animations to initial state
  50586. */
  50587. AnimationGroup.prototype.reset = function () {
  50588. if (!this._isStarted) {
  50589. return this;
  50590. }
  50591. for (var index = 0; index < this._animatables.length; index++) {
  50592. var animatable = this._animatables[index];
  50593. animatable.reset();
  50594. }
  50595. return this;
  50596. };
  50597. /**
  50598. * Restart animations from key 0
  50599. */
  50600. AnimationGroup.prototype.restart = function () {
  50601. if (!this._isStarted) {
  50602. return this;
  50603. }
  50604. for (var index = 0; index < this._animatables.length; index++) {
  50605. var animatable = this._animatables[index];
  50606. animatable.restart();
  50607. }
  50608. return this;
  50609. };
  50610. /**
  50611. * Stop all animations
  50612. */
  50613. AnimationGroup.prototype.stop = function () {
  50614. if (!this._isStarted) {
  50615. return this;
  50616. }
  50617. var list = this._animatables.slice();
  50618. for (var index = 0; index < list.length; index++) {
  50619. list[index].stop();
  50620. }
  50621. this._isStarted = false;
  50622. return this;
  50623. };
  50624. /**
  50625. * Set animation weight for all animatables
  50626. * @param weight defines the weight to use
  50627. * @return the animationGroup
  50628. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50629. */
  50630. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50631. for (var index = 0; index < this._animatables.length; index++) {
  50632. var animatable = this._animatables[index];
  50633. animatable.weight = weight;
  50634. }
  50635. return this;
  50636. };
  50637. /**
  50638. * Synchronize and normalize all animatables with a source animatable
  50639. * @param root defines the root animatable to synchronize with
  50640. * @return the animationGroup
  50641. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50642. */
  50643. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50644. for (var index = 0; index < this._animatables.length; index++) {
  50645. var animatable = this._animatables[index];
  50646. animatable.syncWith(root);
  50647. }
  50648. return this;
  50649. };
  50650. /**
  50651. * Goes to a specific frame in this animation group
  50652. * @param frame the frame number to go to
  50653. * @return the animationGroup
  50654. */
  50655. AnimationGroup.prototype.goToFrame = function (frame) {
  50656. if (!this._isStarted) {
  50657. return this;
  50658. }
  50659. for (var index = 0; index < this._animatables.length; index++) {
  50660. var animatable = this._animatables[index];
  50661. animatable.goToFrame(frame);
  50662. }
  50663. return this;
  50664. };
  50665. /**
  50666. * Dispose all associated resources
  50667. */
  50668. AnimationGroup.prototype.dispose = function () {
  50669. this._targetedAnimations = [];
  50670. this._animatables = [];
  50671. var index = this._scene.animationGroups.indexOf(this);
  50672. if (index > -1) {
  50673. this._scene.animationGroups.splice(index, 1);
  50674. }
  50675. };
  50676. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50677. // animatable should be taken out of the array
  50678. var idx = this._animatables.indexOf(animatable);
  50679. if (idx > -1) {
  50680. this._animatables.splice(idx, 1);
  50681. }
  50682. // all animatables were removed? animation group ended!
  50683. if (this._animatables.length === 0) {
  50684. this._isStarted = false;
  50685. this.onAnimationGroupEndObservable.notifyObservers(this);
  50686. }
  50687. };
  50688. // Statics
  50689. /**
  50690. * Returns a new AnimationGroup object parsed from the source provided.
  50691. * @param parsedAnimationGroup defines the source
  50692. * @param scene defines the scene that will receive the animationGroup
  50693. * @returns a new AnimationGroup
  50694. */
  50695. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  50696. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  50697. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  50698. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  50699. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  50700. var id = targetedAnimation.targetId;
  50701. var targetNode = scene.getNodeByID(id);
  50702. if (targetNode != null)
  50703. animationGroup.addTargetedAnimation(animation, targetNode);
  50704. }
  50705. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  50706. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  50707. return animationGroup;
  50708. };
  50709. /**
  50710. * Returns the string "AnimationGroup"
  50711. * @returns "AnimationGroup"
  50712. */
  50713. AnimationGroup.prototype.getClassName = function () {
  50714. return "AnimationGroup";
  50715. };
  50716. /**
  50717. * Creates a detailled string about the object
  50718. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  50719. * @returns a string representing the object
  50720. */
  50721. AnimationGroup.prototype.toString = function (fullDetails) {
  50722. var ret = "Name: " + this.name;
  50723. ret += ", type: " + this.getClassName();
  50724. if (fullDetails) {
  50725. ret += ", from: " + this._from;
  50726. ret += ", to: " + this._to;
  50727. ret += ", isStarted: " + this._isStarted;
  50728. ret += ", speedRatio: " + this._speedRatio;
  50729. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  50730. ret += ", animatables length: " + this._animatables;
  50731. }
  50732. return ret;
  50733. };
  50734. return AnimationGroup;
  50735. }());
  50736. BABYLON.AnimationGroup = AnimationGroup;
  50737. })(BABYLON || (BABYLON = {}));
  50738. //# sourceMappingURL=babylon.animationGroup.js.map
  50739. var BABYLON;
  50740. (function (BABYLON) {
  50741. // Static values to help the garbage collector
  50742. // Quaternion
  50743. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  50744. // Vector3
  50745. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  50746. // Vector2
  50747. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  50748. // Size
  50749. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  50750. // Color3
  50751. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  50752. /**
  50753. * Defines a runtime animation
  50754. */
  50755. var RuntimeAnimation = /** @class */ (function () {
  50756. /**
  50757. * Create a new RuntimeAnimation object
  50758. * @param target defines the target of the animation
  50759. * @param animation defines the source animation object
  50760. * @param scene defines the hosting scene
  50761. * @param host defines the initiating Animatable
  50762. */
  50763. function RuntimeAnimation(target, animation, scene, host) {
  50764. var _this = this;
  50765. this._events = new Array();
  50766. /**
  50767. * The current frame of the runtime animation
  50768. */
  50769. this._currentFrame = 0;
  50770. /**
  50771. * The original value of the runtime animation
  50772. */
  50773. this._originalValue = new Array();
  50774. /**
  50775. * The offsets cache of the runtime animation
  50776. */
  50777. this._offsetsCache = {};
  50778. /**
  50779. * The high limits cache of the runtime animation
  50780. */
  50781. this._highLimitsCache = {};
  50782. /**
  50783. * Specifies if the runtime animation has been stopped
  50784. */
  50785. this._stopped = false;
  50786. /**
  50787. * The blending factor of the runtime animation
  50788. */
  50789. this._blendingFactor = 0;
  50790. /**
  50791. * The target path of the runtime animation
  50792. */
  50793. this._targetPath = "";
  50794. /**
  50795. * The weight of the runtime animation
  50796. */
  50797. this._weight = 1.0;
  50798. /**
  50799. * The ratio offset of the runtime animation
  50800. */
  50801. this._ratioOffset = 0;
  50802. /**
  50803. * The previous delay of the runtime animation
  50804. */
  50805. this._previousDelay = 0;
  50806. /**
  50807. * The previous ratio of the runtime animation
  50808. */
  50809. this._previousRatio = 0;
  50810. this._animation = animation;
  50811. this._target = target;
  50812. this._scene = scene;
  50813. this._host = host;
  50814. animation._runtimeAnimations.push(this);
  50815. // Cloning events locally
  50816. var events = animation.getEvents();
  50817. if (events && events.length > 0) {
  50818. events.forEach(function (e) {
  50819. _this._events.push(e._clone());
  50820. });
  50821. }
  50822. }
  50823. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50824. /**
  50825. * Gets the current frame of the runtime animation
  50826. */
  50827. get: function () {
  50828. return this._currentFrame;
  50829. },
  50830. enumerable: true,
  50831. configurable: true
  50832. });
  50833. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50834. /**
  50835. * Gets the weight of the runtime animation
  50836. */
  50837. get: function () {
  50838. return this._weight;
  50839. },
  50840. enumerable: true,
  50841. configurable: true
  50842. });
  50843. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50844. /**
  50845. * Gets the current value of the runtime animation
  50846. */
  50847. get: function () {
  50848. return this._currentValue;
  50849. },
  50850. enumerable: true,
  50851. configurable: true
  50852. });
  50853. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50854. /**
  50855. * Gets the target path of the runtime animation
  50856. */
  50857. get: function () {
  50858. return this._targetPath;
  50859. },
  50860. enumerable: true,
  50861. configurable: true
  50862. });
  50863. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50864. /**
  50865. * Gets the actual target of the runtime animation
  50866. */
  50867. get: function () {
  50868. return this._activeTarget;
  50869. },
  50870. enumerable: true,
  50871. configurable: true
  50872. });
  50873. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50874. /**
  50875. * Gets the animation from the runtime animation
  50876. */
  50877. get: function () {
  50878. return this._animation;
  50879. },
  50880. enumerable: true,
  50881. configurable: true
  50882. });
  50883. /**
  50884. * Resets the runtime animation to the beginning
  50885. * @param restoreOriginal defines whether to restore the target property to the original value
  50886. */
  50887. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50888. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50889. if (restoreOriginal) {
  50890. if (this._target instanceof Array) {
  50891. var index = 0;
  50892. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50893. var target = _a[_i];
  50894. if (this._originalValue[index] !== undefined) {
  50895. this._setValue(target, this._originalValue[index], -1);
  50896. }
  50897. index++;
  50898. }
  50899. }
  50900. else {
  50901. if (this._originalValue[0] !== undefined) {
  50902. this._setValue(this._target, this._originalValue[0], -1);
  50903. }
  50904. }
  50905. }
  50906. this._offsetsCache = {};
  50907. this._highLimitsCache = {};
  50908. this._currentFrame = 0;
  50909. this._blendingFactor = 0;
  50910. this._originalValue = new Array();
  50911. // Events
  50912. for (var index = 0; index < this._events.length; index++) {
  50913. this._events[index].isDone = false;
  50914. }
  50915. };
  50916. /**
  50917. * Specifies if the runtime animation is stopped
  50918. * @returns Boolean specifying if the runtime animation is stopped
  50919. */
  50920. RuntimeAnimation.prototype.isStopped = function () {
  50921. return this._stopped;
  50922. };
  50923. /**
  50924. * Disposes of the runtime animation
  50925. */
  50926. RuntimeAnimation.prototype.dispose = function () {
  50927. var index = this._animation.runtimeAnimations.indexOf(this);
  50928. if (index > -1) {
  50929. this._animation.runtimeAnimations.splice(index, 1);
  50930. }
  50931. };
  50932. /**
  50933. * Interpolates the animation from the current frame
  50934. * @param currentFrame The frame to interpolate the animation to
  50935. * @param repeatCount The number of times that the animation should loop
  50936. * @param loopMode The type of looping mode to use
  50937. * @param offsetValue Animation offset value
  50938. * @param highLimitValue The high limit value
  50939. * @returns The interpolated value
  50940. */
  50941. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50942. this._currentFrame = currentFrame;
  50943. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50944. this._workValue = BABYLON.Matrix.Zero();
  50945. }
  50946. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50947. };
  50948. /**
  50949. * Apply the interpolated value to the target
  50950. * @param currentValue defines the value computed by the animation
  50951. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50952. */
  50953. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50954. if (weight === void 0) { weight = 1.0; }
  50955. if (this._target instanceof Array) {
  50956. var index = 0;
  50957. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50958. var target = _a[_i];
  50959. this._setValue(target, currentValue, weight, index);
  50960. index++;
  50961. }
  50962. }
  50963. else {
  50964. this._setValue(this._target, currentValue, weight);
  50965. }
  50966. };
  50967. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50968. if (targetIndex === void 0) { targetIndex = 0; }
  50969. // Set value
  50970. var path;
  50971. var destination;
  50972. var targetPropertyPath = this._animation.targetPropertyPath;
  50973. if (targetPropertyPath.length > 1) {
  50974. var property = target[targetPropertyPath[0]];
  50975. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50976. property = property[targetPropertyPath[index]];
  50977. }
  50978. path = targetPropertyPath[targetPropertyPath.length - 1];
  50979. destination = property;
  50980. }
  50981. else {
  50982. path = targetPropertyPath[0];
  50983. destination = target;
  50984. }
  50985. this._targetPath = path;
  50986. this._activeTarget = destination;
  50987. this._weight = weight;
  50988. if (this._originalValue[targetIndex] === undefined) {
  50989. var originalValue = void 0;
  50990. if (destination.getRestPose && path === "_matrix") { // For bones
  50991. originalValue = destination.getRestPose();
  50992. }
  50993. else {
  50994. originalValue = destination[path];
  50995. }
  50996. if (originalValue && originalValue.clone) {
  50997. this._originalValue[targetIndex] = originalValue.clone();
  50998. }
  50999. else {
  51000. this._originalValue[targetIndex] = originalValue;
  51001. }
  51002. }
  51003. // Blending
  51004. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51005. if (enableBlending && this._blendingFactor <= 1.0) {
  51006. if (!this._originalBlendValue) {
  51007. var originalValue = destination[path];
  51008. if (originalValue.clone) {
  51009. this._originalBlendValue = originalValue.clone();
  51010. }
  51011. else {
  51012. this._originalBlendValue = originalValue;
  51013. }
  51014. }
  51015. if (this._originalBlendValue.m) { // Matrix
  51016. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51017. if (this._currentValue) {
  51018. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51019. }
  51020. else {
  51021. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51022. }
  51023. }
  51024. else {
  51025. if (this._currentValue) {
  51026. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51027. }
  51028. else {
  51029. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51030. }
  51031. }
  51032. }
  51033. else {
  51034. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51035. }
  51036. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51037. this._blendingFactor += blendingSpeed;
  51038. }
  51039. else {
  51040. this._currentValue = currentValue;
  51041. }
  51042. if (weight !== -1.0) {
  51043. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51044. }
  51045. else {
  51046. destination[path] = this._currentValue;
  51047. }
  51048. if (target.markAsDirty) {
  51049. target.markAsDirty(this._animation.targetProperty);
  51050. }
  51051. };
  51052. /**
  51053. * Gets the loop pmode of the runtime animation
  51054. * @returns Loop Mode
  51055. */
  51056. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51057. if (this._target && this._target.animationPropertiesOverride) {
  51058. return this._target.animationPropertiesOverride.loopMode;
  51059. }
  51060. return this._animation.loopMode;
  51061. };
  51062. /**
  51063. * Move the current animation to a given frame
  51064. * @param frame defines the frame to move to
  51065. */
  51066. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51067. var keys = this._animation.getKeys();
  51068. if (frame < keys[0].frame) {
  51069. frame = keys[0].frame;
  51070. }
  51071. else if (frame > keys[keys.length - 1].frame) {
  51072. frame = keys[keys.length - 1].frame;
  51073. }
  51074. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51075. this.setValue(currentValue, -1);
  51076. };
  51077. /**
  51078. * @hidden Internal use only
  51079. */
  51080. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51081. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51082. this._ratioOffset = this._previousRatio - newRatio;
  51083. };
  51084. /**
  51085. * Execute the current animation
  51086. * @param delay defines the delay to add to the current frame
  51087. * @param from defines the lower bound of the animation range
  51088. * @param to defines the upper bound of the animation range
  51089. * @param loop defines if the current animation must loop
  51090. * @param speedRatio defines the current speed ratio
  51091. * @param weight defines the weight of the animation (default is -1 so no weight)
  51092. * @returns a boolean indicating if the animation is running
  51093. */
  51094. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51095. if (weight === void 0) { weight = -1.0; }
  51096. var targetPropertyPath = this._animation.targetPropertyPath;
  51097. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51098. this._stopped = true;
  51099. return false;
  51100. }
  51101. var returnValue = true;
  51102. var keys = this._animation.getKeys();
  51103. // Adding a start key at frame 0 if missing
  51104. if (keys[0].frame !== 0) {
  51105. var newKey = { frame: 0, value: keys[0].value };
  51106. keys.splice(0, 0, newKey);
  51107. }
  51108. // Adding a duplicate key when there is only one key at frame zero
  51109. else if (keys.length === 1) {
  51110. var newKey = { frame: 0.001, value: keys[0].value };
  51111. keys.push(newKey);
  51112. }
  51113. // Check limits
  51114. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51115. from = keys[0].frame;
  51116. }
  51117. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51118. to = keys[keys.length - 1].frame;
  51119. }
  51120. //to and from cannot be the same key
  51121. if (from === to) {
  51122. if (from > keys[0].frame) {
  51123. from--;
  51124. }
  51125. else if (to < keys[keys.length - 1].frame) {
  51126. to++;
  51127. }
  51128. }
  51129. // Compute ratio
  51130. var range = to - from;
  51131. var offsetValue;
  51132. // ratio represents the frame delta between from and to
  51133. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51134. var highLimitValue = 0;
  51135. this._previousDelay = delay;
  51136. this._previousRatio = ratio;
  51137. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51138. returnValue = false;
  51139. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51140. }
  51141. else {
  51142. // Get max value if required
  51143. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51144. var keyOffset = to.toString() + from.toString();
  51145. if (!this._offsetsCache[keyOffset]) {
  51146. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51147. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51148. switch (this._animation.dataType) {
  51149. // Float
  51150. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51151. this._offsetsCache[keyOffset] = toValue - fromValue;
  51152. break;
  51153. // Quaternion
  51154. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51155. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51156. break;
  51157. // Vector3
  51158. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51159. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51160. // Vector2
  51161. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51162. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51163. // Size
  51164. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51165. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51166. // Color3
  51167. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51168. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51169. default:
  51170. break;
  51171. }
  51172. this._highLimitsCache[keyOffset] = toValue;
  51173. }
  51174. highLimitValue = this._highLimitsCache[keyOffset];
  51175. offsetValue = this._offsetsCache[keyOffset];
  51176. }
  51177. }
  51178. if (offsetValue === undefined) {
  51179. switch (this._animation.dataType) {
  51180. // Float
  51181. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51182. offsetValue = 0;
  51183. break;
  51184. // Quaternion
  51185. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51186. offsetValue = _staticOffsetValueQuaternion;
  51187. break;
  51188. // Vector3
  51189. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51190. offsetValue = _staticOffsetValueVector3;
  51191. break;
  51192. // Vector2
  51193. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51194. offsetValue = _staticOffsetValueVector2;
  51195. break;
  51196. // Size
  51197. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51198. offsetValue = _staticOffsetValueSize;
  51199. break;
  51200. // Color3
  51201. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51202. offsetValue = _staticOffsetValueColor3;
  51203. }
  51204. }
  51205. // Compute value
  51206. var repeatCount = (ratio / range) >> 0;
  51207. var currentFrame = returnValue ? from + ratio % range : to;
  51208. // Need to normalize?
  51209. if (this._host && this._host.syncRoot) {
  51210. var syncRoot = this._host.syncRoot;
  51211. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51212. currentFrame = from + (to - from) * hostNormalizedFrame;
  51213. }
  51214. // Reset events if looping
  51215. var events = this._events;
  51216. if (range > 0 && this.currentFrame > currentFrame ||
  51217. range < 0 && this.currentFrame < currentFrame) {
  51218. // Need to reset animation events
  51219. for (var index = 0; index < events.length; index++) {
  51220. if (!events[index].onlyOnce) {
  51221. // reset event, the animation is looping
  51222. events[index].isDone = false;
  51223. }
  51224. }
  51225. }
  51226. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51227. // Set value
  51228. this.setValue(currentValue, weight);
  51229. // Check events
  51230. for (var index = 0; index < events.length; index++) {
  51231. // Make sure current frame has passed event frame and that event frame is within the current range
  51232. // Also, handle both forward and reverse animations
  51233. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51234. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51235. var event = events[index];
  51236. if (!event.isDone) {
  51237. // If event should be done only once, remove it.
  51238. if (event.onlyOnce) {
  51239. events.splice(index, 1);
  51240. index--;
  51241. }
  51242. event.isDone = true;
  51243. event.action(currentFrame);
  51244. } // Don't do anything if the event has already be done.
  51245. }
  51246. }
  51247. if (!returnValue) {
  51248. this._stopped = true;
  51249. }
  51250. return returnValue;
  51251. };
  51252. return RuntimeAnimation;
  51253. }());
  51254. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51255. })(BABYLON || (BABYLON = {}));
  51256. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51257. var BABYLON;
  51258. (function (BABYLON) {
  51259. /**
  51260. * Class used to store an actual running animation
  51261. */
  51262. var Animatable = /** @class */ (function () {
  51263. /**
  51264. * Creates a new Animatable
  51265. * @param scene defines the hosting scene
  51266. * @param target defines the target object
  51267. * @param fromFrame defines the starting frame number (default is 0)
  51268. * @param toFrame defines the ending frame number (default is 100)
  51269. * @param loopAnimation defines if the animation must loop (default is false)
  51270. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51271. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51272. * @param animations defines a group of animation to add to the new Animatable
  51273. */
  51274. function Animatable(scene,
  51275. /** defines the target object */
  51276. target,
  51277. /** defines the starting frame number (default is 0) */
  51278. fromFrame,
  51279. /** defines the ending frame number (default is 100) */
  51280. toFrame,
  51281. /** defines if the animation must loop (default is false) */
  51282. loopAnimation, speedRatio,
  51283. /** defines a callback to call when animation ends if it is not looping */
  51284. onAnimationEnd, animations) {
  51285. if (fromFrame === void 0) { fromFrame = 0; }
  51286. if (toFrame === void 0) { toFrame = 100; }
  51287. if (loopAnimation === void 0) { loopAnimation = false; }
  51288. if (speedRatio === void 0) { speedRatio = 1.0; }
  51289. this.target = target;
  51290. this.fromFrame = fromFrame;
  51291. this.toFrame = toFrame;
  51292. this.loopAnimation = loopAnimation;
  51293. this.onAnimationEnd = onAnimationEnd;
  51294. this._localDelayOffset = null;
  51295. this._pausedDelay = null;
  51296. this._runtimeAnimations = new Array();
  51297. this._paused = false;
  51298. this._speedRatio = 1;
  51299. this._weight = -1.0;
  51300. /**
  51301. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51302. * This will only apply for non looping animation (default is true)
  51303. */
  51304. this.disposeOnEnd = true;
  51305. /**
  51306. * Gets a boolean indicating if the animation has started
  51307. */
  51308. this.animationStarted = false;
  51309. /**
  51310. * Observer raised when the animation ends
  51311. */
  51312. this.onAnimationEndObservable = new BABYLON.Observable();
  51313. this._scene = scene;
  51314. if (animations) {
  51315. this.appendAnimations(target, animations);
  51316. }
  51317. this._speedRatio = speedRatio;
  51318. scene._activeAnimatables.push(this);
  51319. }
  51320. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51321. /**
  51322. * Gets the root Animatable used to synchronize and normalize animations
  51323. */
  51324. get: function () {
  51325. return this._syncRoot;
  51326. },
  51327. enumerable: true,
  51328. configurable: true
  51329. });
  51330. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51331. /**
  51332. * Gets the current frame of the first RuntimeAnimation
  51333. * Used to synchronize Animatables
  51334. */
  51335. get: function () {
  51336. if (this._runtimeAnimations.length === 0) {
  51337. return 0;
  51338. }
  51339. return this._runtimeAnimations[0].currentFrame;
  51340. },
  51341. enumerable: true,
  51342. configurable: true
  51343. });
  51344. Object.defineProperty(Animatable.prototype, "weight", {
  51345. /**
  51346. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51347. */
  51348. get: function () {
  51349. return this._weight;
  51350. },
  51351. set: function (value) {
  51352. if (value === -1) { // -1 is ok and means no weight
  51353. this._weight = -1;
  51354. return;
  51355. }
  51356. // Else weight must be in [0, 1] range
  51357. this._weight = Math.min(Math.max(value, 0), 1.0);
  51358. },
  51359. enumerable: true,
  51360. configurable: true
  51361. });
  51362. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51363. /**
  51364. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51365. */
  51366. get: function () {
  51367. return this._speedRatio;
  51368. },
  51369. set: function (value) {
  51370. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51371. var animation = this._runtimeAnimations[index];
  51372. animation._prepareForSpeedRatioChange(value);
  51373. }
  51374. this._speedRatio = value;
  51375. },
  51376. enumerable: true,
  51377. configurable: true
  51378. });
  51379. // Methods
  51380. /**
  51381. * Synchronize and normalize current Animatable with a source Animatable
  51382. * This is useful when using animation weights and when animations are not of the same length
  51383. * @param root defines the root Animatable to synchronize with
  51384. * @returns the current Animatable
  51385. */
  51386. Animatable.prototype.syncWith = function (root) {
  51387. this._syncRoot = root;
  51388. if (root) {
  51389. // Make sure this animatable will animate after the root
  51390. var index = this._scene._activeAnimatables.indexOf(this);
  51391. if (index > -1) {
  51392. this._scene._activeAnimatables.splice(index, 1);
  51393. this._scene._activeAnimatables.push(this);
  51394. }
  51395. }
  51396. return this;
  51397. };
  51398. /**
  51399. * Gets the list of runtime animations
  51400. * @returns an array of RuntimeAnimation
  51401. */
  51402. Animatable.prototype.getAnimations = function () {
  51403. return this._runtimeAnimations;
  51404. };
  51405. /**
  51406. * Adds more animations to the current animatable
  51407. * @param target defines the target of the animations
  51408. * @param animations defines the new animations to add
  51409. */
  51410. Animatable.prototype.appendAnimations = function (target, animations) {
  51411. for (var index = 0; index < animations.length; index++) {
  51412. var animation = animations[index];
  51413. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51414. }
  51415. };
  51416. /**
  51417. * Gets the source animation for a specific property
  51418. * @param property defines the propertyu to look for
  51419. * @returns null or the source animation for the given property
  51420. */
  51421. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51422. var runtimeAnimations = this._runtimeAnimations;
  51423. for (var index = 0; index < runtimeAnimations.length; index++) {
  51424. if (runtimeAnimations[index].animation.targetProperty === property) {
  51425. return runtimeAnimations[index].animation;
  51426. }
  51427. }
  51428. return null;
  51429. };
  51430. /**
  51431. * Gets the runtime animation for a specific property
  51432. * @param property defines the propertyu to look for
  51433. * @returns null or the runtime animation for the given property
  51434. */
  51435. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51436. var runtimeAnimations = this._runtimeAnimations;
  51437. for (var index = 0; index < runtimeAnimations.length; index++) {
  51438. if (runtimeAnimations[index].animation.targetProperty === property) {
  51439. return runtimeAnimations[index];
  51440. }
  51441. }
  51442. return null;
  51443. };
  51444. /**
  51445. * Resets the animatable to its original state
  51446. */
  51447. Animatable.prototype.reset = function () {
  51448. var runtimeAnimations = this._runtimeAnimations;
  51449. for (var index = 0; index < runtimeAnimations.length; index++) {
  51450. runtimeAnimations[index].reset(true);
  51451. }
  51452. this._localDelayOffset = null;
  51453. this._pausedDelay = null;
  51454. };
  51455. /**
  51456. * Allows the animatable to blend with current running animations
  51457. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51458. * @param blendingSpeed defines the blending speed to use
  51459. */
  51460. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51461. var runtimeAnimations = this._runtimeAnimations;
  51462. for (var index = 0; index < runtimeAnimations.length; index++) {
  51463. runtimeAnimations[index].animation.enableBlending = true;
  51464. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51465. }
  51466. };
  51467. /**
  51468. * Disable animation blending
  51469. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51470. */
  51471. Animatable.prototype.disableBlending = function () {
  51472. var runtimeAnimations = this._runtimeAnimations;
  51473. for (var index = 0; index < runtimeAnimations.length; index++) {
  51474. runtimeAnimations[index].animation.enableBlending = false;
  51475. }
  51476. };
  51477. /**
  51478. * Jump directly to a given frame
  51479. * @param frame defines the frame to jump to
  51480. */
  51481. Animatable.prototype.goToFrame = function (frame) {
  51482. var runtimeAnimations = this._runtimeAnimations;
  51483. if (runtimeAnimations[0]) {
  51484. var fps = runtimeAnimations[0].animation.framePerSecond;
  51485. var currentFrame = runtimeAnimations[0].currentFrame;
  51486. var adjustTime = frame - currentFrame;
  51487. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51488. if (this._localDelayOffset === null) {
  51489. this._localDelayOffset = 0;
  51490. }
  51491. this._localDelayOffset -= delay;
  51492. }
  51493. for (var index = 0; index < runtimeAnimations.length; index++) {
  51494. runtimeAnimations[index].goToFrame(frame);
  51495. }
  51496. };
  51497. /**
  51498. * Pause the animation
  51499. */
  51500. Animatable.prototype.pause = function () {
  51501. if (this._paused) {
  51502. return;
  51503. }
  51504. this._paused = true;
  51505. };
  51506. /**
  51507. * Restart the animation
  51508. */
  51509. Animatable.prototype.restart = function () {
  51510. this._paused = false;
  51511. };
  51512. Animatable.prototype._raiseOnAnimationEnd = function () {
  51513. if (this.onAnimationEnd) {
  51514. this.onAnimationEnd();
  51515. }
  51516. this.onAnimationEndObservable.notifyObservers(this);
  51517. };
  51518. /**
  51519. * Stop and delete the current animation
  51520. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51521. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  51522. */
  51523. Animatable.prototype.stop = function (animationName, targetMask) {
  51524. if (animationName || targetMask) {
  51525. var idx = this._scene._activeAnimatables.indexOf(this);
  51526. if (idx > -1) {
  51527. var runtimeAnimations = this._runtimeAnimations;
  51528. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51529. var runtimeAnimation = runtimeAnimations[index];
  51530. if (animationName && runtimeAnimation.animation.name != animationName) {
  51531. continue;
  51532. }
  51533. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51534. continue;
  51535. }
  51536. runtimeAnimation.dispose();
  51537. runtimeAnimations.splice(index, 1);
  51538. }
  51539. if (runtimeAnimations.length == 0) {
  51540. this._scene._activeAnimatables.splice(idx, 1);
  51541. this._raiseOnAnimationEnd();
  51542. }
  51543. }
  51544. }
  51545. else {
  51546. var index = this._scene._activeAnimatables.indexOf(this);
  51547. if (index > -1) {
  51548. this._scene._activeAnimatables.splice(index, 1);
  51549. var runtimeAnimations = this._runtimeAnimations;
  51550. for (var index = 0; index < runtimeAnimations.length; index++) {
  51551. runtimeAnimations[index].dispose();
  51552. }
  51553. this._raiseOnAnimationEnd();
  51554. }
  51555. }
  51556. };
  51557. /**
  51558. * Wait asynchronously for the animation to end
  51559. * @returns a promise which will be fullfilled when the animation ends
  51560. */
  51561. Animatable.prototype.waitAsync = function () {
  51562. var _this = this;
  51563. return new Promise(function (resolve, reject) {
  51564. _this.onAnimationEndObservable.add(function () {
  51565. resolve(_this);
  51566. }, undefined, undefined, _this, true);
  51567. });
  51568. };
  51569. /** @hidden */
  51570. Animatable.prototype._animate = function (delay) {
  51571. if (this._paused) {
  51572. this.animationStarted = false;
  51573. if (this._pausedDelay === null) {
  51574. this._pausedDelay = delay;
  51575. }
  51576. return true;
  51577. }
  51578. if (this._localDelayOffset === null) {
  51579. this._localDelayOffset = delay;
  51580. this._pausedDelay = null;
  51581. }
  51582. else if (this._pausedDelay !== null) {
  51583. this._localDelayOffset += delay - this._pausedDelay;
  51584. this._pausedDelay = null;
  51585. }
  51586. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51587. return true;
  51588. }
  51589. // Animating
  51590. var running = false;
  51591. var runtimeAnimations = this._runtimeAnimations;
  51592. var index;
  51593. for (index = 0; index < runtimeAnimations.length; index++) {
  51594. var animation = runtimeAnimations[index];
  51595. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51596. running = running || isRunning;
  51597. }
  51598. this.animationStarted = running;
  51599. if (!running) {
  51600. if (this.disposeOnEnd) {
  51601. // Remove from active animatables
  51602. index = this._scene._activeAnimatables.indexOf(this);
  51603. this._scene._activeAnimatables.splice(index, 1);
  51604. // Dispose all runtime animations
  51605. for (index = 0; index < runtimeAnimations.length; index++) {
  51606. runtimeAnimations[index].dispose();
  51607. }
  51608. }
  51609. this._raiseOnAnimationEnd();
  51610. if (this.disposeOnEnd) {
  51611. this.onAnimationEnd = null;
  51612. this.onAnimationEndObservable.clear();
  51613. }
  51614. }
  51615. return running;
  51616. };
  51617. return Animatable;
  51618. }());
  51619. BABYLON.Animatable = Animatable;
  51620. })(BABYLON || (BABYLON = {}));
  51621. //# sourceMappingURL=babylon.animatable.js.map
  51622. var BABYLON;
  51623. (function (BABYLON) {
  51624. var EasingFunction = /** @class */ (function () {
  51625. function EasingFunction() {
  51626. // Properties
  51627. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51628. }
  51629. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51630. get: function () {
  51631. return EasingFunction._EASINGMODE_EASEIN;
  51632. },
  51633. enumerable: true,
  51634. configurable: true
  51635. });
  51636. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51637. get: function () {
  51638. return EasingFunction._EASINGMODE_EASEOUT;
  51639. },
  51640. enumerable: true,
  51641. configurable: true
  51642. });
  51643. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51644. get: function () {
  51645. return EasingFunction._EASINGMODE_EASEINOUT;
  51646. },
  51647. enumerable: true,
  51648. configurable: true
  51649. });
  51650. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51651. var n = Math.min(Math.max(easingMode, 0), 2);
  51652. this._easingMode = n;
  51653. };
  51654. EasingFunction.prototype.getEasingMode = function () {
  51655. return this._easingMode;
  51656. };
  51657. EasingFunction.prototype.easeInCore = function (gradient) {
  51658. throw new Error('You must implement this method');
  51659. };
  51660. EasingFunction.prototype.ease = function (gradient) {
  51661. switch (this._easingMode) {
  51662. case EasingFunction.EASINGMODE_EASEIN:
  51663. return this.easeInCore(gradient);
  51664. case EasingFunction.EASINGMODE_EASEOUT:
  51665. return (1 - this.easeInCore(1 - gradient));
  51666. }
  51667. if (gradient >= 0.5) {
  51668. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51669. }
  51670. return (this.easeInCore(gradient * 2) * 0.5);
  51671. };
  51672. //Statics
  51673. EasingFunction._EASINGMODE_EASEIN = 0;
  51674. EasingFunction._EASINGMODE_EASEOUT = 1;
  51675. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51676. return EasingFunction;
  51677. }());
  51678. BABYLON.EasingFunction = EasingFunction;
  51679. var CircleEase = /** @class */ (function (_super) {
  51680. __extends(CircleEase, _super);
  51681. function CircleEase() {
  51682. return _super !== null && _super.apply(this, arguments) || this;
  51683. }
  51684. CircleEase.prototype.easeInCore = function (gradient) {
  51685. gradient = Math.max(0, Math.min(1, gradient));
  51686. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51687. };
  51688. return CircleEase;
  51689. }(EasingFunction));
  51690. BABYLON.CircleEase = CircleEase;
  51691. var BackEase = /** @class */ (function (_super) {
  51692. __extends(BackEase, _super);
  51693. function BackEase(amplitude) {
  51694. if (amplitude === void 0) { amplitude = 1; }
  51695. var _this = _super.call(this) || this;
  51696. _this.amplitude = amplitude;
  51697. return _this;
  51698. }
  51699. BackEase.prototype.easeInCore = function (gradient) {
  51700. var num = Math.max(0, this.amplitude);
  51701. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51702. };
  51703. return BackEase;
  51704. }(EasingFunction));
  51705. BABYLON.BackEase = BackEase;
  51706. var BounceEase = /** @class */ (function (_super) {
  51707. __extends(BounceEase, _super);
  51708. function BounceEase(bounces, bounciness) {
  51709. if (bounces === void 0) { bounces = 3; }
  51710. if (bounciness === void 0) { bounciness = 2; }
  51711. var _this = _super.call(this) || this;
  51712. _this.bounces = bounces;
  51713. _this.bounciness = bounciness;
  51714. return _this;
  51715. }
  51716. BounceEase.prototype.easeInCore = function (gradient) {
  51717. var y = Math.max(0.0, this.bounces);
  51718. var bounciness = this.bounciness;
  51719. if (bounciness <= 1.0) {
  51720. bounciness = 1.001;
  51721. }
  51722. var num9 = Math.pow(bounciness, y);
  51723. var num5 = 1.0 - bounciness;
  51724. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51725. var num15 = gradient * num4;
  51726. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51727. var num3 = Math.floor(num65);
  51728. var num13 = num3 + 1.0;
  51729. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51730. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51731. var num7 = (num8 + num12) * 0.5;
  51732. var num6 = gradient - num7;
  51733. var num2 = num7 - num8;
  51734. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51735. };
  51736. return BounceEase;
  51737. }(EasingFunction));
  51738. BABYLON.BounceEase = BounceEase;
  51739. var CubicEase = /** @class */ (function (_super) {
  51740. __extends(CubicEase, _super);
  51741. function CubicEase() {
  51742. return _super !== null && _super.apply(this, arguments) || this;
  51743. }
  51744. CubicEase.prototype.easeInCore = function (gradient) {
  51745. return (gradient * gradient * gradient);
  51746. };
  51747. return CubicEase;
  51748. }(EasingFunction));
  51749. BABYLON.CubicEase = CubicEase;
  51750. var ElasticEase = /** @class */ (function (_super) {
  51751. __extends(ElasticEase, _super);
  51752. function ElasticEase(oscillations, springiness) {
  51753. if (oscillations === void 0) { oscillations = 3; }
  51754. if (springiness === void 0) { springiness = 3; }
  51755. var _this = _super.call(this) || this;
  51756. _this.oscillations = oscillations;
  51757. _this.springiness = springiness;
  51758. return _this;
  51759. }
  51760. ElasticEase.prototype.easeInCore = function (gradient) {
  51761. var num2;
  51762. var num3 = Math.max(0.0, this.oscillations);
  51763. var num = Math.max(0.0, this.springiness);
  51764. if (num == 0) {
  51765. num2 = gradient;
  51766. }
  51767. else {
  51768. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51769. }
  51770. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51771. };
  51772. return ElasticEase;
  51773. }(EasingFunction));
  51774. BABYLON.ElasticEase = ElasticEase;
  51775. var ExponentialEase = /** @class */ (function (_super) {
  51776. __extends(ExponentialEase, _super);
  51777. function ExponentialEase(exponent) {
  51778. if (exponent === void 0) { exponent = 2; }
  51779. var _this = _super.call(this) || this;
  51780. _this.exponent = exponent;
  51781. return _this;
  51782. }
  51783. ExponentialEase.prototype.easeInCore = function (gradient) {
  51784. if (this.exponent <= 0) {
  51785. return gradient;
  51786. }
  51787. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51788. };
  51789. return ExponentialEase;
  51790. }(EasingFunction));
  51791. BABYLON.ExponentialEase = ExponentialEase;
  51792. var PowerEase = /** @class */ (function (_super) {
  51793. __extends(PowerEase, _super);
  51794. function PowerEase(power) {
  51795. if (power === void 0) { power = 2; }
  51796. var _this = _super.call(this) || this;
  51797. _this.power = power;
  51798. return _this;
  51799. }
  51800. PowerEase.prototype.easeInCore = function (gradient) {
  51801. var y = Math.max(0.0, this.power);
  51802. return Math.pow(gradient, y);
  51803. };
  51804. return PowerEase;
  51805. }(EasingFunction));
  51806. BABYLON.PowerEase = PowerEase;
  51807. var QuadraticEase = /** @class */ (function (_super) {
  51808. __extends(QuadraticEase, _super);
  51809. function QuadraticEase() {
  51810. return _super !== null && _super.apply(this, arguments) || this;
  51811. }
  51812. QuadraticEase.prototype.easeInCore = function (gradient) {
  51813. return (gradient * gradient);
  51814. };
  51815. return QuadraticEase;
  51816. }(EasingFunction));
  51817. BABYLON.QuadraticEase = QuadraticEase;
  51818. var QuarticEase = /** @class */ (function (_super) {
  51819. __extends(QuarticEase, _super);
  51820. function QuarticEase() {
  51821. return _super !== null && _super.apply(this, arguments) || this;
  51822. }
  51823. QuarticEase.prototype.easeInCore = function (gradient) {
  51824. return (gradient * gradient * gradient * gradient);
  51825. };
  51826. return QuarticEase;
  51827. }(EasingFunction));
  51828. BABYLON.QuarticEase = QuarticEase;
  51829. var QuinticEase = /** @class */ (function (_super) {
  51830. __extends(QuinticEase, _super);
  51831. function QuinticEase() {
  51832. return _super !== null && _super.apply(this, arguments) || this;
  51833. }
  51834. QuinticEase.prototype.easeInCore = function (gradient) {
  51835. return (gradient * gradient * gradient * gradient * gradient);
  51836. };
  51837. return QuinticEase;
  51838. }(EasingFunction));
  51839. BABYLON.QuinticEase = QuinticEase;
  51840. var SineEase = /** @class */ (function (_super) {
  51841. __extends(SineEase, _super);
  51842. function SineEase() {
  51843. return _super !== null && _super.apply(this, arguments) || this;
  51844. }
  51845. SineEase.prototype.easeInCore = function (gradient) {
  51846. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51847. };
  51848. return SineEase;
  51849. }(EasingFunction));
  51850. BABYLON.SineEase = SineEase;
  51851. var BezierCurveEase = /** @class */ (function (_super) {
  51852. __extends(BezierCurveEase, _super);
  51853. function BezierCurveEase(x1, y1, x2, y2) {
  51854. if (x1 === void 0) { x1 = 0; }
  51855. if (y1 === void 0) { y1 = 0; }
  51856. if (x2 === void 0) { x2 = 1; }
  51857. if (y2 === void 0) { y2 = 1; }
  51858. var _this = _super.call(this) || this;
  51859. _this.x1 = x1;
  51860. _this.y1 = y1;
  51861. _this.x2 = x2;
  51862. _this.y2 = y2;
  51863. return _this;
  51864. }
  51865. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51866. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51867. };
  51868. return BezierCurveEase;
  51869. }(EasingFunction));
  51870. BABYLON.BezierCurveEase = BezierCurveEase;
  51871. })(BABYLON || (BABYLON = {}));
  51872. //# sourceMappingURL=babylon.easing.js.map
  51873. var BABYLON;
  51874. (function (BABYLON) {
  51875. /**
  51876. * A Condition applied to an Action
  51877. */
  51878. var Condition = /** @class */ (function () {
  51879. /**
  51880. * Creates a new Condition
  51881. * @param actionManager the manager of the action the condition is applied to
  51882. */
  51883. function Condition(actionManager) {
  51884. this._actionManager = actionManager;
  51885. }
  51886. /**
  51887. * Check if the current condition is valid
  51888. * @returns a boolean
  51889. */
  51890. Condition.prototype.isValid = function () {
  51891. return true;
  51892. };
  51893. /**
  51894. * Internal only
  51895. * @hidden
  51896. */
  51897. Condition.prototype._getProperty = function (propertyPath) {
  51898. return this._actionManager._getProperty(propertyPath);
  51899. };
  51900. /**
  51901. * Internal only
  51902. * @hidden
  51903. */
  51904. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51905. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51906. };
  51907. /**
  51908. * Serialize placeholder for child classes
  51909. * @returns the serialized object
  51910. */
  51911. Condition.prototype.serialize = function () {
  51912. };
  51913. /**
  51914. * Internal only
  51915. * @hidden
  51916. */
  51917. Condition.prototype._serialize = function (serializedCondition) {
  51918. return {
  51919. type: 2,
  51920. children: [],
  51921. name: serializedCondition.name,
  51922. properties: serializedCondition.properties
  51923. };
  51924. };
  51925. return Condition;
  51926. }());
  51927. BABYLON.Condition = Condition;
  51928. /**
  51929. * Defines specific conditional operators as extensions of Condition
  51930. */
  51931. var ValueCondition = /** @class */ (function (_super) {
  51932. __extends(ValueCondition, _super);
  51933. /**
  51934. * Creates a new ValueCondition
  51935. * @param actionManager manager for the action the condition applies to
  51936. * @param target for the action
  51937. * @param propertyPath path to specify the property of the target the conditional operator uses
  51938. * @param value the value compared by the conditional operator against the current value of the property
  51939. * @param operator the conditional operator, default ValueCondition.IsEqual
  51940. */
  51941. function ValueCondition(actionManager, target,
  51942. /** path to specify the property of the target the conditional operator uses */
  51943. propertyPath,
  51944. /** the value compared by the conditional operator against the current value of the property */
  51945. value,
  51946. /** the conditional operator, default ValueCondition.IsEqual */
  51947. operator) {
  51948. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51949. var _this = _super.call(this, actionManager) || this;
  51950. _this.propertyPath = propertyPath;
  51951. _this.value = value;
  51952. _this.operator = operator;
  51953. _this._target = target;
  51954. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51955. _this._property = _this._getProperty(_this.propertyPath);
  51956. return _this;
  51957. }
  51958. Object.defineProperty(ValueCondition, "IsEqual", {
  51959. /**
  51960. * returns the number for IsEqual
  51961. */
  51962. get: function () {
  51963. return ValueCondition._IsEqual;
  51964. },
  51965. enumerable: true,
  51966. configurable: true
  51967. });
  51968. Object.defineProperty(ValueCondition, "IsDifferent", {
  51969. /**
  51970. * Returns the number for IsDifferent
  51971. */
  51972. get: function () {
  51973. return ValueCondition._IsDifferent;
  51974. },
  51975. enumerable: true,
  51976. configurable: true
  51977. });
  51978. Object.defineProperty(ValueCondition, "IsGreater", {
  51979. /**
  51980. * Returns the number for IsGreater
  51981. */
  51982. get: function () {
  51983. return ValueCondition._IsGreater;
  51984. },
  51985. enumerable: true,
  51986. configurable: true
  51987. });
  51988. Object.defineProperty(ValueCondition, "IsLesser", {
  51989. /**
  51990. * Returns the number for IsLesser
  51991. */
  51992. get: function () {
  51993. return ValueCondition._IsLesser;
  51994. },
  51995. enumerable: true,
  51996. configurable: true
  51997. });
  51998. /**
  51999. * Compares the given value with the property value for the specified conditional operator
  52000. * @returns the result of the comparison
  52001. */
  52002. ValueCondition.prototype.isValid = function () {
  52003. switch (this.operator) {
  52004. case ValueCondition.IsGreater:
  52005. return this._effectiveTarget[this._property] > this.value;
  52006. case ValueCondition.IsLesser:
  52007. return this._effectiveTarget[this._property] < this.value;
  52008. case ValueCondition.IsEqual:
  52009. case ValueCondition.IsDifferent:
  52010. var check;
  52011. if (this.value.equals) {
  52012. check = this.value.equals(this._effectiveTarget[this._property]);
  52013. }
  52014. else {
  52015. check = this.value === this._effectiveTarget[this._property];
  52016. }
  52017. return this.operator === ValueCondition.IsEqual ? check : !check;
  52018. }
  52019. return false;
  52020. };
  52021. /**
  52022. * Serialize the ValueCondition into a JSON compatible object
  52023. * @returns serialization object
  52024. */
  52025. ValueCondition.prototype.serialize = function () {
  52026. return this._serialize({
  52027. name: "ValueCondition",
  52028. properties: [
  52029. BABYLON.Action._GetTargetProperty(this._target),
  52030. { name: "propertyPath", value: this.propertyPath },
  52031. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52032. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52033. ]
  52034. });
  52035. };
  52036. /**
  52037. * Gets the name of the conditional operator for the ValueCondition
  52038. * @param operator the conditional operator
  52039. * @returns the name
  52040. */
  52041. ValueCondition.GetOperatorName = function (operator) {
  52042. switch (operator) {
  52043. case ValueCondition._IsEqual: return "IsEqual";
  52044. case ValueCondition._IsDifferent: return "IsDifferent";
  52045. case ValueCondition._IsGreater: return "IsGreater";
  52046. case ValueCondition._IsLesser: return "IsLesser";
  52047. default: return "";
  52048. }
  52049. };
  52050. /**
  52051. * Internal only
  52052. * @hidden
  52053. */
  52054. ValueCondition._IsEqual = 0;
  52055. /**
  52056. * Internal only
  52057. * @hidden
  52058. */
  52059. ValueCondition._IsDifferent = 1;
  52060. /**
  52061. * Internal only
  52062. * @hidden
  52063. */
  52064. ValueCondition._IsGreater = 2;
  52065. /**
  52066. * Internal only
  52067. * @hidden
  52068. */
  52069. ValueCondition._IsLesser = 3;
  52070. return ValueCondition;
  52071. }(Condition));
  52072. BABYLON.ValueCondition = ValueCondition;
  52073. /**
  52074. * Defines a predicate condition as an extension of Condition
  52075. */
  52076. var PredicateCondition = /** @class */ (function (_super) {
  52077. __extends(PredicateCondition, _super);
  52078. /**
  52079. * Creates a new PredicateCondition
  52080. * @param actionManager manager for the action the condition applies to
  52081. * @param predicate defines the predicate function used to validate the condition
  52082. */
  52083. function PredicateCondition(actionManager,
  52084. /** defines the predicate function used to validate the condition */
  52085. predicate) {
  52086. var _this = _super.call(this, actionManager) || this;
  52087. _this.predicate = predicate;
  52088. return _this;
  52089. }
  52090. /**
  52091. * @returns the validity of the predicate condition
  52092. */
  52093. PredicateCondition.prototype.isValid = function () {
  52094. return this.predicate();
  52095. };
  52096. return PredicateCondition;
  52097. }(Condition));
  52098. BABYLON.PredicateCondition = PredicateCondition;
  52099. /**
  52100. * Defines a state condition as an extension of Condition
  52101. */
  52102. var StateCondition = /** @class */ (function (_super) {
  52103. __extends(StateCondition, _super);
  52104. /**
  52105. * Creates a new StateCondition
  52106. * @param actionManager manager for the action the condition applies to
  52107. * @param target of the condition
  52108. * @param value to compare with target state
  52109. */
  52110. function StateCondition(actionManager, target, value) {
  52111. var _this = _super.call(this, actionManager) || this;
  52112. _this.value = value;
  52113. _this._target = target;
  52114. return _this;
  52115. }
  52116. /**
  52117. * @returns the validity of the state
  52118. */
  52119. StateCondition.prototype.isValid = function () {
  52120. return this._target.state === this.value;
  52121. };
  52122. /**
  52123. * Serialize the StateCondition into a JSON compatible object
  52124. * @returns serialization object
  52125. */
  52126. StateCondition.prototype.serialize = function () {
  52127. return this._serialize({
  52128. name: "StateCondition",
  52129. properties: [
  52130. BABYLON.Action._GetTargetProperty(this._target),
  52131. { name: "value", value: this.value }
  52132. ]
  52133. });
  52134. };
  52135. return StateCondition;
  52136. }(Condition));
  52137. BABYLON.StateCondition = StateCondition;
  52138. })(BABYLON || (BABYLON = {}));
  52139. //# sourceMappingURL=babylon.condition.js.map
  52140. var BABYLON;
  52141. (function (BABYLON) {
  52142. /**
  52143. * The action to be carried out following a trigger
  52144. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52145. */
  52146. var Action = /** @class */ (function () {
  52147. /**
  52148. * Creates a new Action
  52149. * @param triggerOptions the trigger, with or without parameters, for the action
  52150. * @param condition an optional determinant of action
  52151. */
  52152. function Action(
  52153. /** the trigger, with or without parameters, for the action */
  52154. triggerOptions, condition) {
  52155. this.triggerOptions = triggerOptions;
  52156. /**
  52157. * An event triggered prior to action being executed.
  52158. */
  52159. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52160. if (triggerOptions.parameter) {
  52161. this.trigger = triggerOptions.trigger;
  52162. this._triggerParameter = triggerOptions.parameter;
  52163. }
  52164. else if (triggerOptions.trigger) {
  52165. this.trigger = triggerOptions.trigger;
  52166. }
  52167. else {
  52168. this.trigger = triggerOptions;
  52169. }
  52170. this._nextActiveAction = this;
  52171. this._condition = condition;
  52172. }
  52173. /**
  52174. * Internal only
  52175. * @hidden
  52176. */
  52177. Action.prototype._prepare = function () {
  52178. };
  52179. /**
  52180. * Gets the trigger parameters
  52181. * @returns the trigger parameters
  52182. */
  52183. Action.prototype.getTriggerParameter = function () {
  52184. return this._triggerParameter;
  52185. };
  52186. /**
  52187. * Internal only - executes current action event
  52188. * @hidden
  52189. */
  52190. Action.prototype._executeCurrent = function (evt) {
  52191. if (this._nextActiveAction._condition) {
  52192. var condition = this._nextActiveAction._condition;
  52193. var currentRenderId = this._actionManager.getScene().getRenderId();
  52194. // We cache the current evaluation for the current frame
  52195. if (condition._evaluationId === currentRenderId) {
  52196. if (!condition._currentResult) {
  52197. return;
  52198. }
  52199. }
  52200. else {
  52201. condition._evaluationId = currentRenderId;
  52202. if (!condition.isValid()) {
  52203. condition._currentResult = false;
  52204. return;
  52205. }
  52206. condition._currentResult = true;
  52207. }
  52208. }
  52209. this.onBeforeExecuteObservable.notifyObservers(this);
  52210. this._nextActiveAction.execute(evt);
  52211. this.skipToNextActiveAction();
  52212. };
  52213. /**
  52214. * Execute placeholder for child classes
  52215. * @param evt optional action event
  52216. */
  52217. Action.prototype.execute = function (evt) {
  52218. };
  52219. /**
  52220. * Skips to next active action
  52221. */
  52222. Action.prototype.skipToNextActiveAction = function () {
  52223. if (this._nextActiveAction._child) {
  52224. if (!this._nextActiveAction._child._actionManager) {
  52225. this._nextActiveAction._child._actionManager = this._actionManager;
  52226. }
  52227. this._nextActiveAction = this._nextActiveAction._child;
  52228. }
  52229. else {
  52230. this._nextActiveAction = this;
  52231. }
  52232. };
  52233. /**
  52234. * Adds action to chain of actions, may be a DoNothingAction
  52235. * @param action defines the next action to execute
  52236. * @returns The action passed in
  52237. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52238. */
  52239. Action.prototype.then = function (action) {
  52240. this._child = action;
  52241. action._actionManager = this._actionManager;
  52242. action._prepare();
  52243. return action;
  52244. };
  52245. /**
  52246. * Internal only
  52247. * @hidden
  52248. */
  52249. Action.prototype._getProperty = function (propertyPath) {
  52250. return this._actionManager._getProperty(propertyPath);
  52251. };
  52252. /**
  52253. * Internal only
  52254. * @hidden
  52255. */
  52256. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52257. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52258. };
  52259. /**
  52260. * Serialize placeholder for child classes
  52261. * @param parent of child
  52262. * @returns the serialized object
  52263. */
  52264. Action.prototype.serialize = function (parent) {
  52265. };
  52266. /**
  52267. * Internal only called by serialize
  52268. * @hidden
  52269. */
  52270. Action.prototype._serialize = function (serializedAction, parent) {
  52271. var serializationObject = {
  52272. type: 1,
  52273. children: [],
  52274. name: serializedAction.name,
  52275. properties: serializedAction.properties || []
  52276. };
  52277. // Serialize child
  52278. if (this._child) {
  52279. this._child.serialize(serializationObject);
  52280. }
  52281. // Check if "this" has a condition
  52282. if (this._condition) {
  52283. var serializedCondition = this._condition.serialize();
  52284. serializedCondition.children.push(serializationObject);
  52285. if (parent) {
  52286. parent.children.push(serializedCondition);
  52287. }
  52288. return serializedCondition;
  52289. }
  52290. if (parent) {
  52291. parent.children.push(serializationObject);
  52292. }
  52293. return serializationObject;
  52294. };
  52295. /**
  52296. * Internal only
  52297. * @hidden
  52298. */
  52299. Action._SerializeValueAsString = function (value) {
  52300. if (typeof value === "number") {
  52301. return value.toString();
  52302. }
  52303. if (typeof value === "boolean") {
  52304. return value ? "true" : "false";
  52305. }
  52306. if (value instanceof BABYLON.Vector2) {
  52307. return value.x + ", " + value.y;
  52308. }
  52309. if (value instanceof BABYLON.Vector3) {
  52310. return value.x + ", " + value.y + ", " + value.z;
  52311. }
  52312. if (value instanceof BABYLON.Color3) {
  52313. return value.r + ", " + value.g + ", " + value.b;
  52314. }
  52315. if (value instanceof BABYLON.Color4) {
  52316. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52317. }
  52318. return value; // string
  52319. };
  52320. /**
  52321. * Internal only
  52322. * @hidden
  52323. */
  52324. Action._GetTargetProperty = function (target) {
  52325. return {
  52326. name: "target",
  52327. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52328. : target instanceof BABYLON.Light ? "LightProperties"
  52329. : target instanceof BABYLON.Camera ? "CameraProperties"
  52330. : "SceneProperties",
  52331. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52332. };
  52333. };
  52334. return Action;
  52335. }());
  52336. BABYLON.Action = Action;
  52337. })(BABYLON || (BABYLON = {}));
  52338. //# sourceMappingURL=babylon.action.js.map
  52339. var BABYLON;
  52340. (function (BABYLON) {
  52341. /**
  52342. * ActionEvent is the event being sent when an action is triggered.
  52343. */
  52344. var ActionEvent = /** @class */ (function () {
  52345. /**
  52346. * Creates a new ActionEvent
  52347. * @param source The mesh or sprite that triggered the action
  52348. * @param pointerX The X mouse cursor position at the time of the event
  52349. * @param pointerY The Y mouse cursor position at the time of the event
  52350. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52351. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52352. * @param additionalData additional data for the event
  52353. */
  52354. function ActionEvent(
  52355. /** The mesh or sprite that triggered the action */
  52356. source,
  52357. /** The X mouse cursor position at the time of the event */
  52358. pointerX,
  52359. /** The Y mouse cursor position at the time of the event */
  52360. pointerY,
  52361. /** The mesh that is currently pointed at (can be null) */
  52362. meshUnderPointer,
  52363. /** the original (browser) event that triggered the ActionEvent */
  52364. sourceEvent,
  52365. /** additional data for the event */
  52366. additionalData) {
  52367. this.source = source;
  52368. this.pointerX = pointerX;
  52369. this.pointerY = pointerY;
  52370. this.meshUnderPointer = meshUnderPointer;
  52371. this.sourceEvent = sourceEvent;
  52372. this.additionalData = additionalData;
  52373. }
  52374. /**
  52375. * Helper function to auto-create an ActionEvent from a source mesh.
  52376. * @param source The source mesh that triggered the event
  52377. * @param evt The original (browser) event
  52378. * @param additionalData additional data for the event
  52379. * @returns the new ActionEvent
  52380. */
  52381. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52382. var scene = source.getScene();
  52383. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52384. };
  52385. /**
  52386. * Helper function to auto-create an ActionEvent from a source sprite
  52387. * @param source The source sprite that triggered the event
  52388. * @param scene Scene associated with the sprite
  52389. * @param evt The original (browser) event
  52390. * @param additionalData additional data for the event
  52391. * @returns the new ActionEvent
  52392. */
  52393. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52394. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52395. };
  52396. /**
  52397. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52398. * @param scene the scene where the event occurred
  52399. * @param evt The original (browser) event
  52400. * @returns the new ActionEvent
  52401. */
  52402. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52403. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52404. };
  52405. /**
  52406. * Helper function to auto-create an ActionEvent from a primitive
  52407. * @param prim defines the target primitive
  52408. * @param pointerPos defines the pointer position
  52409. * @param evt The original (browser) event
  52410. * @param additionalData additional data for the event
  52411. * @returns the new ActionEvent
  52412. */
  52413. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52414. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52415. };
  52416. return ActionEvent;
  52417. }());
  52418. BABYLON.ActionEvent = ActionEvent;
  52419. /**
  52420. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52421. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52422. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52423. */
  52424. var ActionManager = /** @class */ (function () {
  52425. /**
  52426. * Creates a new action manager
  52427. * @param scene defines the hosting scene
  52428. */
  52429. function ActionManager(scene) {
  52430. // Members
  52431. /** Gets the list of actions */
  52432. this.actions = new Array();
  52433. /** Gets the cursor to use when hovering items */
  52434. this.hoverCursor = '';
  52435. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52436. scene.actionManagers.push(this);
  52437. }
  52438. Object.defineProperty(ActionManager, "NothingTrigger", {
  52439. /**
  52440. * Nothing
  52441. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52442. */
  52443. get: function () {
  52444. return ActionManager._NothingTrigger;
  52445. },
  52446. enumerable: true,
  52447. configurable: true
  52448. });
  52449. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52450. /**
  52451. * On pick
  52452. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52453. */
  52454. get: function () {
  52455. return ActionManager._OnPickTrigger;
  52456. },
  52457. enumerable: true,
  52458. configurable: true
  52459. });
  52460. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52461. /**
  52462. * On left pick
  52463. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52464. */
  52465. get: function () {
  52466. return ActionManager._OnLeftPickTrigger;
  52467. },
  52468. enumerable: true,
  52469. configurable: true
  52470. });
  52471. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52472. /**
  52473. * On right pick
  52474. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52475. */
  52476. get: function () {
  52477. return ActionManager._OnRightPickTrigger;
  52478. },
  52479. enumerable: true,
  52480. configurable: true
  52481. });
  52482. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52483. /**
  52484. * On center pick
  52485. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52486. */
  52487. get: function () {
  52488. return ActionManager._OnCenterPickTrigger;
  52489. },
  52490. enumerable: true,
  52491. configurable: true
  52492. });
  52493. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52494. /**
  52495. * On pick down
  52496. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52497. */
  52498. get: function () {
  52499. return ActionManager._OnPickDownTrigger;
  52500. },
  52501. enumerable: true,
  52502. configurable: true
  52503. });
  52504. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52505. /**
  52506. * On double pick
  52507. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52508. */
  52509. get: function () {
  52510. return ActionManager._OnDoublePickTrigger;
  52511. },
  52512. enumerable: true,
  52513. configurable: true
  52514. });
  52515. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52516. /**
  52517. * On pick up
  52518. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52519. */
  52520. get: function () {
  52521. return ActionManager._OnPickUpTrigger;
  52522. },
  52523. enumerable: true,
  52524. configurable: true
  52525. });
  52526. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52527. /**
  52528. * On pick out.
  52529. * This trigger will only be raised if you also declared a OnPickDown
  52530. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52531. */
  52532. get: function () {
  52533. return ActionManager._OnPickOutTrigger;
  52534. },
  52535. enumerable: true,
  52536. configurable: true
  52537. });
  52538. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52539. /**
  52540. * On long press
  52541. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52542. */
  52543. get: function () {
  52544. return ActionManager._OnLongPressTrigger;
  52545. },
  52546. enumerable: true,
  52547. configurable: true
  52548. });
  52549. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52550. /**
  52551. * On pointer over
  52552. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52553. */
  52554. get: function () {
  52555. return ActionManager._OnPointerOverTrigger;
  52556. },
  52557. enumerable: true,
  52558. configurable: true
  52559. });
  52560. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52561. /**
  52562. * On pointer out
  52563. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52564. */
  52565. get: function () {
  52566. return ActionManager._OnPointerOutTrigger;
  52567. },
  52568. enumerable: true,
  52569. configurable: true
  52570. });
  52571. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52572. /**
  52573. * On every frame
  52574. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52575. */
  52576. get: function () {
  52577. return ActionManager._OnEveryFrameTrigger;
  52578. },
  52579. enumerable: true,
  52580. configurable: true
  52581. });
  52582. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52583. /**
  52584. * On intersection enter
  52585. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52586. */
  52587. get: function () {
  52588. return ActionManager._OnIntersectionEnterTrigger;
  52589. },
  52590. enumerable: true,
  52591. configurable: true
  52592. });
  52593. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52594. /**
  52595. * On intersection exit
  52596. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52597. */
  52598. get: function () {
  52599. return ActionManager._OnIntersectionExitTrigger;
  52600. },
  52601. enumerable: true,
  52602. configurable: true
  52603. });
  52604. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52605. /**
  52606. * On key down
  52607. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52608. */
  52609. get: function () {
  52610. return ActionManager._OnKeyDownTrigger;
  52611. },
  52612. enumerable: true,
  52613. configurable: true
  52614. });
  52615. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52616. /**
  52617. * On key up
  52618. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52619. */
  52620. get: function () {
  52621. return ActionManager._OnKeyUpTrigger;
  52622. },
  52623. enumerable: true,
  52624. configurable: true
  52625. });
  52626. // Methods
  52627. /**
  52628. * Releases all associated resources
  52629. */
  52630. ActionManager.prototype.dispose = function () {
  52631. var index = this._scene.actionManagers.indexOf(this);
  52632. for (var i = 0; i < this.actions.length; i++) {
  52633. var action = this.actions[i];
  52634. ActionManager.Triggers[action.trigger]--;
  52635. if (ActionManager.Triggers[action.trigger] === 0) {
  52636. delete ActionManager.Triggers[action.trigger];
  52637. }
  52638. }
  52639. if (index > -1) {
  52640. this._scene.actionManagers.splice(index, 1);
  52641. }
  52642. };
  52643. /**
  52644. * Gets hosting scene
  52645. * @returns the hosting scene
  52646. */
  52647. ActionManager.prototype.getScene = function () {
  52648. return this._scene;
  52649. };
  52650. /**
  52651. * Does this action manager handles actions of any of the given triggers
  52652. * @param triggers defines the triggers to be tested
  52653. * @return a boolean indicating whether one (or more) of the triggers is handled
  52654. */
  52655. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52656. for (var index = 0; index < this.actions.length; index++) {
  52657. var action = this.actions[index];
  52658. if (triggers.indexOf(action.trigger) > -1) {
  52659. return true;
  52660. }
  52661. }
  52662. return false;
  52663. };
  52664. /**
  52665. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  52666. * speed.
  52667. * @param triggerA defines the trigger to be tested
  52668. * @param triggerB defines the trigger to be tested
  52669. * @return a boolean indicating whether one (or more) of the triggers is handled
  52670. */
  52671. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  52672. for (var index = 0; index < this.actions.length; index++) {
  52673. var action = this.actions[index];
  52674. if (triggerA == action.trigger || triggerB == action.trigger) {
  52675. return true;
  52676. }
  52677. }
  52678. return false;
  52679. };
  52680. /**
  52681. * Does this action manager handles actions of a given trigger
  52682. * @param trigger defines the trigger to be tested
  52683. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52684. * @return whether the trigger is handled
  52685. */
  52686. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52687. for (var index = 0; index < this.actions.length; index++) {
  52688. var action = this.actions[index];
  52689. if (action.trigger === trigger) {
  52690. if (parameterPredicate) {
  52691. if (parameterPredicate(action.getTriggerParameter())) {
  52692. return true;
  52693. }
  52694. }
  52695. else {
  52696. return true;
  52697. }
  52698. }
  52699. }
  52700. return false;
  52701. };
  52702. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52703. /**
  52704. * Does this action manager has pointer triggers
  52705. */
  52706. get: function () {
  52707. for (var index = 0; index < this.actions.length; index++) {
  52708. var action = this.actions[index];
  52709. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52710. return true;
  52711. }
  52712. }
  52713. return false;
  52714. },
  52715. enumerable: true,
  52716. configurable: true
  52717. });
  52718. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52719. /**
  52720. * Does this action manager has pick triggers
  52721. */
  52722. get: function () {
  52723. for (var index = 0; index < this.actions.length; index++) {
  52724. var action = this.actions[index];
  52725. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52726. return true;
  52727. }
  52728. }
  52729. return false;
  52730. },
  52731. enumerable: true,
  52732. configurable: true
  52733. });
  52734. Object.defineProperty(ActionManager, "HasTriggers", {
  52735. /**
  52736. * Does exist one action manager with at least one trigger
  52737. **/
  52738. get: function () {
  52739. for (var t in ActionManager.Triggers) {
  52740. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52741. return true;
  52742. }
  52743. }
  52744. return false;
  52745. },
  52746. enumerable: true,
  52747. configurable: true
  52748. });
  52749. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52750. /**
  52751. * Does exist one action manager with at least one pick trigger
  52752. **/
  52753. get: function () {
  52754. for (var t in ActionManager.Triggers) {
  52755. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52756. var t_int = parseInt(t);
  52757. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52758. return true;
  52759. }
  52760. }
  52761. }
  52762. return false;
  52763. },
  52764. enumerable: true,
  52765. configurable: true
  52766. });
  52767. /**
  52768. * Does exist one action manager that handles actions of a given trigger
  52769. * @param trigger defines the trigger to be tested
  52770. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52771. **/
  52772. ActionManager.HasSpecificTrigger = function (trigger) {
  52773. for (var t in ActionManager.Triggers) {
  52774. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52775. var t_int = parseInt(t);
  52776. if (t_int === trigger) {
  52777. return true;
  52778. }
  52779. }
  52780. }
  52781. return false;
  52782. };
  52783. /**
  52784. * Registers an action to this action manager
  52785. * @param action defines the action to be registered
  52786. * @return the action amended (prepared) after registration
  52787. */
  52788. ActionManager.prototype.registerAction = function (action) {
  52789. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52790. if (this.getScene().actionManager !== this) {
  52791. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52792. return null;
  52793. }
  52794. }
  52795. this.actions.push(action);
  52796. if (ActionManager.Triggers[action.trigger]) {
  52797. ActionManager.Triggers[action.trigger]++;
  52798. }
  52799. else {
  52800. ActionManager.Triggers[action.trigger] = 1;
  52801. }
  52802. action._actionManager = this;
  52803. action._prepare();
  52804. return action;
  52805. };
  52806. /**
  52807. * Unregisters an action to this action manager
  52808. * @param action defines the action to be unregistered
  52809. * @return a boolean indicating whether the action has been unregistered
  52810. */
  52811. ActionManager.prototype.unregisterAction = function (action) {
  52812. var index = this.actions.indexOf(action);
  52813. if (index !== -1) {
  52814. this.actions.splice(index, 1);
  52815. ActionManager.Triggers[action.trigger] -= 1;
  52816. if (ActionManager.Triggers[action.trigger] === 0) {
  52817. delete ActionManager.Triggers[action.trigger];
  52818. }
  52819. delete action._actionManager;
  52820. return true;
  52821. }
  52822. return false;
  52823. };
  52824. /**
  52825. * Process a specific trigger
  52826. * @param trigger defines the trigger to process
  52827. * @param evt defines the event details to be processed
  52828. */
  52829. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52830. for (var index = 0; index < this.actions.length; index++) {
  52831. var action = this.actions[index];
  52832. if (action.trigger === trigger) {
  52833. if (evt) {
  52834. if (trigger === ActionManager.OnKeyUpTrigger
  52835. || trigger === ActionManager.OnKeyDownTrigger) {
  52836. var parameter = action.getTriggerParameter();
  52837. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52838. if (!parameter.toLowerCase) {
  52839. continue;
  52840. }
  52841. var lowerCase = parameter.toLowerCase();
  52842. if (lowerCase !== evt.sourceEvent.key) {
  52843. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52844. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52845. if (actualkey !== lowerCase) {
  52846. continue;
  52847. }
  52848. }
  52849. }
  52850. }
  52851. }
  52852. action._executeCurrent(evt);
  52853. }
  52854. }
  52855. };
  52856. /** @hidden */
  52857. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52858. var properties = propertyPath.split(".");
  52859. for (var index = 0; index < properties.length - 1; index++) {
  52860. target = target[properties[index]];
  52861. }
  52862. return target;
  52863. };
  52864. /** @hidden */
  52865. ActionManager.prototype._getProperty = function (propertyPath) {
  52866. var properties = propertyPath.split(".");
  52867. return properties[properties.length - 1];
  52868. };
  52869. /**
  52870. * Serialize this manager to a JSON object
  52871. * @param name defines the property name to store this manager
  52872. * @returns a JSON representation of this manager
  52873. */
  52874. ActionManager.prototype.serialize = function (name) {
  52875. var root = {
  52876. children: new Array(),
  52877. name: name,
  52878. type: 3,
  52879. properties: new Array() // Empty for root but required
  52880. };
  52881. for (var i = 0; i < this.actions.length; i++) {
  52882. var triggerObject = {
  52883. type: 0,
  52884. children: new Array(),
  52885. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52886. properties: new Array()
  52887. };
  52888. var triggerOptions = this.actions[i].triggerOptions;
  52889. if (triggerOptions && typeof triggerOptions !== "number") {
  52890. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52891. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52892. }
  52893. else {
  52894. var parameter = {};
  52895. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52896. if (triggerOptions.parameter.mesh) {
  52897. parameter._meshId = triggerOptions.parameter.mesh.id;
  52898. }
  52899. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52900. }
  52901. }
  52902. // Serialize child action, recursively
  52903. this.actions[i].serialize(triggerObject);
  52904. // Add serialized trigger
  52905. root.children.push(triggerObject);
  52906. }
  52907. return root;
  52908. };
  52909. /**
  52910. * Creates a new ActionManager from a JSON data
  52911. * @param parsedActions defines the JSON data to read from
  52912. * @param object defines the hosting mesh
  52913. * @param scene defines the hosting scene
  52914. */
  52915. ActionManager.Parse = function (parsedActions, object, scene) {
  52916. var actionManager = new ActionManager(scene);
  52917. if (object === null)
  52918. scene.actionManager = actionManager;
  52919. else
  52920. object.actionManager = actionManager;
  52921. // instanciate a new object
  52922. var instanciate = function (name, params) {
  52923. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52924. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52925. newInstance.constructor.apply(newInstance, params);
  52926. return newInstance;
  52927. };
  52928. var parseParameter = function (name, value, target, propertyPath) {
  52929. if (propertyPath === null) {
  52930. // String, boolean or float
  52931. var floatValue = parseFloat(value);
  52932. if (value === "true" || value === "false")
  52933. return value === "true";
  52934. else
  52935. return isNaN(floatValue) ? value : floatValue;
  52936. }
  52937. var effectiveTarget = propertyPath.split(".");
  52938. var values = value.split(",");
  52939. // Get effective Target
  52940. for (var i = 0; i < effectiveTarget.length; i++) {
  52941. target = target[effectiveTarget[i]];
  52942. }
  52943. // Return appropriate value with its type
  52944. if (typeof (target) === "boolean")
  52945. return values[0] === "true";
  52946. if (typeof (target) === "string")
  52947. return values[0];
  52948. // Parameters with multiple values such as Vector3 etc.
  52949. var split = new Array();
  52950. for (var i = 0; i < values.length; i++)
  52951. split.push(parseFloat(values[i]));
  52952. if (target instanceof BABYLON.Vector3)
  52953. return BABYLON.Vector3.FromArray(split);
  52954. if (target instanceof BABYLON.Vector4)
  52955. return BABYLON.Vector4.FromArray(split);
  52956. if (target instanceof BABYLON.Color3)
  52957. return BABYLON.Color3.FromArray(split);
  52958. if (target instanceof BABYLON.Color4)
  52959. return BABYLON.Color4.FromArray(split);
  52960. return parseFloat(values[0]);
  52961. };
  52962. // traverse graph per trigger
  52963. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52964. if (combineArray === void 0) { combineArray = null; }
  52965. if (parsedAction.detached)
  52966. return;
  52967. var parameters = new Array();
  52968. var target = null;
  52969. var propertyPath = null;
  52970. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52971. // Parameters
  52972. if (parsedAction.type === 2)
  52973. parameters.push(actionManager);
  52974. else
  52975. parameters.push(trigger);
  52976. if (combine) {
  52977. var actions = new Array();
  52978. for (var j = 0; j < parsedAction.combine.length; j++) {
  52979. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52980. }
  52981. parameters.push(actions);
  52982. }
  52983. else {
  52984. for (var i = 0; i < parsedAction.properties.length; i++) {
  52985. var value = parsedAction.properties[i].value;
  52986. var name = parsedAction.properties[i].name;
  52987. var targetType = parsedAction.properties[i].targetType;
  52988. if (name === "target")
  52989. if (targetType !== null && targetType === "SceneProperties")
  52990. value = target = scene;
  52991. else
  52992. value = target = scene.getNodeByName(value);
  52993. else if (name === "parent")
  52994. value = scene.getNodeByName(value);
  52995. else if (name === "sound") {
  52996. // Can not externalize to component, so only checks for the presence off the API.
  52997. if (scene.getSoundByName) {
  52998. value = scene.getSoundByName(value);
  52999. }
  53000. }
  53001. else if (name !== "propertyPath") {
  53002. if (parsedAction.type === 2 && name === "operator")
  53003. value = BABYLON.ValueCondition[value];
  53004. else
  53005. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53006. }
  53007. else {
  53008. propertyPath = value;
  53009. }
  53010. parameters.push(value);
  53011. }
  53012. }
  53013. if (combineArray === null) {
  53014. parameters.push(condition);
  53015. }
  53016. else {
  53017. parameters.push(null);
  53018. }
  53019. // If interpolate value action
  53020. if (parsedAction.name === "InterpolateValueAction") {
  53021. var param = parameters[parameters.length - 2];
  53022. parameters[parameters.length - 1] = param;
  53023. parameters[parameters.length - 2] = condition;
  53024. }
  53025. // Action or condition(s) and not CombineAction
  53026. var newAction = instanciate(parsedAction.name, parameters);
  53027. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53028. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53029. if (action)
  53030. action.then(nothing);
  53031. else
  53032. actionManager.registerAction(nothing);
  53033. action = nothing;
  53034. }
  53035. if (combineArray === null) {
  53036. if (newAction instanceof BABYLON.Condition) {
  53037. condition = newAction;
  53038. newAction = action;
  53039. }
  53040. else {
  53041. condition = null;
  53042. if (action)
  53043. action.then(newAction);
  53044. else
  53045. actionManager.registerAction(newAction);
  53046. }
  53047. }
  53048. else {
  53049. combineArray.push(newAction);
  53050. }
  53051. for (var i = 0; i < parsedAction.children.length; i++)
  53052. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53053. };
  53054. // triggers
  53055. for (var i = 0; i < parsedActions.children.length; i++) {
  53056. var triggerParams;
  53057. var trigger = parsedActions.children[i];
  53058. if (trigger.properties.length > 0) {
  53059. var param = trigger.properties[0].value;
  53060. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53061. if (value._meshId) {
  53062. value.mesh = scene.getMeshByID(value._meshId);
  53063. }
  53064. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53065. }
  53066. else
  53067. triggerParams = ActionManager[trigger.name];
  53068. for (var j = 0; j < trigger.children.length; j++) {
  53069. if (!trigger.detached)
  53070. traverse(trigger.children[j], triggerParams, null, null);
  53071. }
  53072. }
  53073. };
  53074. /**
  53075. * Get a trigger name by index
  53076. * @param trigger defines the trigger index
  53077. * @returns a trigger name
  53078. */
  53079. ActionManager.GetTriggerName = function (trigger) {
  53080. switch (trigger) {
  53081. case 0: return "NothingTrigger";
  53082. case 1: return "OnPickTrigger";
  53083. case 2: return "OnLeftPickTrigger";
  53084. case 3: return "OnRightPickTrigger";
  53085. case 4: return "OnCenterPickTrigger";
  53086. case 5: return "OnPickDownTrigger";
  53087. case 6: return "OnPickUpTrigger";
  53088. case 7: return "OnLongPressTrigger";
  53089. case 8: return "OnPointerOverTrigger";
  53090. case 9: return "OnPointerOutTrigger";
  53091. case 10: return "OnEveryFrameTrigger";
  53092. case 11: return "OnIntersectionEnterTrigger";
  53093. case 12: return "OnIntersectionExitTrigger";
  53094. case 13: return "OnKeyDownTrigger";
  53095. case 14: return "OnKeyUpTrigger";
  53096. case 15: return "OnPickOutTrigger";
  53097. default: return "";
  53098. }
  53099. };
  53100. // Statics
  53101. ActionManager._NothingTrigger = 0;
  53102. ActionManager._OnPickTrigger = 1;
  53103. ActionManager._OnLeftPickTrigger = 2;
  53104. ActionManager._OnRightPickTrigger = 3;
  53105. ActionManager._OnCenterPickTrigger = 4;
  53106. ActionManager._OnPickDownTrigger = 5;
  53107. ActionManager._OnDoublePickTrigger = 6;
  53108. ActionManager._OnPickUpTrigger = 7;
  53109. ActionManager._OnLongPressTrigger = 8;
  53110. ActionManager._OnPointerOverTrigger = 9;
  53111. ActionManager._OnPointerOutTrigger = 10;
  53112. ActionManager._OnEveryFrameTrigger = 11;
  53113. ActionManager._OnIntersectionEnterTrigger = 12;
  53114. ActionManager._OnIntersectionExitTrigger = 13;
  53115. ActionManager._OnKeyDownTrigger = 14;
  53116. ActionManager._OnKeyUpTrigger = 15;
  53117. ActionManager._OnPickOutTrigger = 16;
  53118. /** Gets the list of active triggers */
  53119. ActionManager.Triggers = {};
  53120. return ActionManager;
  53121. }());
  53122. BABYLON.ActionManager = ActionManager;
  53123. })(BABYLON || (BABYLON = {}));
  53124. //# sourceMappingURL=babylon.actionManager.js.map
  53125. var BABYLON;
  53126. (function (BABYLON) {
  53127. var InterpolateValueAction = /** @class */ (function (_super) {
  53128. __extends(InterpolateValueAction, _super);
  53129. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53130. if (duration === void 0) { duration = 1000; }
  53131. var _this = _super.call(this, triggerOptions, condition) || this;
  53132. _this.propertyPath = propertyPath;
  53133. _this.value = value;
  53134. _this.duration = duration;
  53135. _this.stopOtherAnimations = stopOtherAnimations;
  53136. _this.onInterpolationDone = onInterpolationDone;
  53137. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53138. _this._target = _this._effectiveTarget = target;
  53139. return _this;
  53140. }
  53141. /** @hidden */
  53142. InterpolateValueAction.prototype._prepare = function () {
  53143. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53144. this._property = this._getProperty(this.propertyPath);
  53145. };
  53146. InterpolateValueAction.prototype.execute = function () {
  53147. var _this = this;
  53148. var scene = this._actionManager.getScene();
  53149. var keys = [
  53150. {
  53151. frame: 0,
  53152. value: this._effectiveTarget[this._property]
  53153. }, {
  53154. frame: 100,
  53155. value: this.value
  53156. }
  53157. ];
  53158. var dataType;
  53159. if (typeof this.value === "number") {
  53160. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53161. }
  53162. else if (this.value instanceof BABYLON.Color3) {
  53163. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53164. }
  53165. else if (this.value instanceof BABYLON.Vector3) {
  53166. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53167. }
  53168. else if (this.value instanceof BABYLON.Matrix) {
  53169. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53170. }
  53171. else if (this.value instanceof BABYLON.Quaternion) {
  53172. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53173. }
  53174. else {
  53175. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53176. return;
  53177. }
  53178. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53179. animation.setKeys(keys);
  53180. if (this.stopOtherAnimations) {
  53181. scene.stopAnimation(this._effectiveTarget);
  53182. }
  53183. var wrapper = function () {
  53184. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53185. if (_this.onInterpolationDone) {
  53186. _this.onInterpolationDone();
  53187. }
  53188. };
  53189. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53190. };
  53191. InterpolateValueAction.prototype.serialize = function (parent) {
  53192. return _super.prototype._serialize.call(this, {
  53193. name: "InterpolateValueAction",
  53194. properties: [
  53195. BABYLON.Action._GetTargetProperty(this._target),
  53196. { name: "propertyPath", value: this.propertyPath },
  53197. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53198. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53199. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53200. ]
  53201. }, parent);
  53202. };
  53203. return InterpolateValueAction;
  53204. }(BABYLON.Action));
  53205. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53206. })(BABYLON || (BABYLON = {}));
  53207. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53208. var BABYLON;
  53209. (function (BABYLON) {
  53210. var SwitchBooleanAction = /** @class */ (function (_super) {
  53211. __extends(SwitchBooleanAction, _super);
  53212. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53213. var _this = _super.call(this, triggerOptions, condition) || this;
  53214. _this.propertyPath = propertyPath;
  53215. _this._target = _this._effectiveTarget = target;
  53216. return _this;
  53217. }
  53218. /** @hidden */
  53219. SwitchBooleanAction.prototype._prepare = function () {
  53220. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53221. this._property = this._getProperty(this.propertyPath);
  53222. };
  53223. SwitchBooleanAction.prototype.execute = function () {
  53224. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53225. };
  53226. SwitchBooleanAction.prototype.serialize = function (parent) {
  53227. return _super.prototype._serialize.call(this, {
  53228. name: "SwitchBooleanAction",
  53229. properties: [
  53230. BABYLON.Action._GetTargetProperty(this._target),
  53231. { name: "propertyPath", value: this.propertyPath }
  53232. ]
  53233. }, parent);
  53234. };
  53235. return SwitchBooleanAction;
  53236. }(BABYLON.Action));
  53237. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53238. var SetStateAction = /** @class */ (function (_super) {
  53239. __extends(SetStateAction, _super);
  53240. function SetStateAction(triggerOptions, target, value, condition) {
  53241. var _this = _super.call(this, triggerOptions, condition) || this;
  53242. _this.value = value;
  53243. _this._target = target;
  53244. return _this;
  53245. }
  53246. SetStateAction.prototype.execute = function () {
  53247. this._target.state = this.value;
  53248. };
  53249. SetStateAction.prototype.serialize = function (parent) {
  53250. return _super.prototype._serialize.call(this, {
  53251. name: "SetStateAction",
  53252. properties: [
  53253. BABYLON.Action._GetTargetProperty(this._target),
  53254. { name: "value", value: this.value }
  53255. ]
  53256. }, parent);
  53257. };
  53258. return SetStateAction;
  53259. }(BABYLON.Action));
  53260. BABYLON.SetStateAction = SetStateAction;
  53261. var SetValueAction = /** @class */ (function (_super) {
  53262. __extends(SetValueAction, _super);
  53263. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53264. var _this = _super.call(this, triggerOptions, condition) || this;
  53265. _this.propertyPath = propertyPath;
  53266. _this.value = value;
  53267. _this._target = _this._effectiveTarget = target;
  53268. return _this;
  53269. }
  53270. /** @hidden */
  53271. SetValueAction.prototype._prepare = function () {
  53272. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53273. this._property = this._getProperty(this.propertyPath);
  53274. };
  53275. SetValueAction.prototype.execute = function () {
  53276. this._effectiveTarget[this._property] = this.value;
  53277. if (this._target.markAsDirty) {
  53278. this._target.markAsDirty(this._property);
  53279. }
  53280. };
  53281. SetValueAction.prototype.serialize = function (parent) {
  53282. return _super.prototype._serialize.call(this, {
  53283. name: "SetValueAction",
  53284. properties: [
  53285. BABYLON.Action._GetTargetProperty(this._target),
  53286. { name: "propertyPath", value: this.propertyPath },
  53287. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53288. ]
  53289. }, parent);
  53290. };
  53291. return SetValueAction;
  53292. }(BABYLON.Action));
  53293. BABYLON.SetValueAction = SetValueAction;
  53294. var IncrementValueAction = /** @class */ (function (_super) {
  53295. __extends(IncrementValueAction, _super);
  53296. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53297. var _this = _super.call(this, triggerOptions, condition) || this;
  53298. _this.propertyPath = propertyPath;
  53299. _this.value = value;
  53300. _this._target = _this._effectiveTarget = target;
  53301. return _this;
  53302. }
  53303. /** @hidden */
  53304. IncrementValueAction.prototype._prepare = function () {
  53305. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53306. this._property = this._getProperty(this.propertyPath);
  53307. if (typeof this._effectiveTarget[this._property] !== "number") {
  53308. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53309. }
  53310. };
  53311. IncrementValueAction.prototype.execute = function () {
  53312. this._effectiveTarget[this._property] += this.value;
  53313. if (this._target.markAsDirty) {
  53314. this._target.markAsDirty(this._property);
  53315. }
  53316. };
  53317. IncrementValueAction.prototype.serialize = function (parent) {
  53318. return _super.prototype._serialize.call(this, {
  53319. name: "IncrementValueAction",
  53320. properties: [
  53321. BABYLON.Action._GetTargetProperty(this._target),
  53322. { name: "propertyPath", value: this.propertyPath },
  53323. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53324. ]
  53325. }, parent);
  53326. };
  53327. return IncrementValueAction;
  53328. }(BABYLON.Action));
  53329. BABYLON.IncrementValueAction = IncrementValueAction;
  53330. var PlayAnimationAction = /** @class */ (function (_super) {
  53331. __extends(PlayAnimationAction, _super);
  53332. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53333. var _this = _super.call(this, triggerOptions, condition) || this;
  53334. _this.from = from;
  53335. _this.to = to;
  53336. _this.loop = loop;
  53337. _this._target = target;
  53338. return _this;
  53339. }
  53340. /** @hidden */
  53341. PlayAnimationAction.prototype._prepare = function () {
  53342. };
  53343. PlayAnimationAction.prototype.execute = function () {
  53344. var scene = this._actionManager.getScene();
  53345. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53346. };
  53347. PlayAnimationAction.prototype.serialize = function (parent) {
  53348. return _super.prototype._serialize.call(this, {
  53349. name: "PlayAnimationAction",
  53350. properties: [
  53351. BABYLON.Action._GetTargetProperty(this._target),
  53352. { name: "from", value: String(this.from) },
  53353. { name: "to", value: String(this.to) },
  53354. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53355. ]
  53356. }, parent);
  53357. };
  53358. return PlayAnimationAction;
  53359. }(BABYLON.Action));
  53360. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53361. var StopAnimationAction = /** @class */ (function (_super) {
  53362. __extends(StopAnimationAction, _super);
  53363. function StopAnimationAction(triggerOptions, target, condition) {
  53364. var _this = _super.call(this, triggerOptions, condition) || this;
  53365. _this._target = target;
  53366. return _this;
  53367. }
  53368. /** @hidden */
  53369. StopAnimationAction.prototype._prepare = function () {
  53370. };
  53371. StopAnimationAction.prototype.execute = function () {
  53372. var scene = this._actionManager.getScene();
  53373. scene.stopAnimation(this._target);
  53374. };
  53375. StopAnimationAction.prototype.serialize = function (parent) {
  53376. return _super.prototype._serialize.call(this, {
  53377. name: "StopAnimationAction",
  53378. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53379. }, parent);
  53380. };
  53381. return StopAnimationAction;
  53382. }(BABYLON.Action));
  53383. BABYLON.StopAnimationAction = StopAnimationAction;
  53384. var DoNothingAction = /** @class */ (function (_super) {
  53385. __extends(DoNothingAction, _super);
  53386. function DoNothingAction(triggerOptions, condition) {
  53387. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53388. return _super.call(this, triggerOptions, condition) || this;
  53389. }
  53390. DoNothingAction.prototype.execute = function () {
  53391. };
  53392. DoNothingAction.prototype.serialize = function (parent) {
  53393. return _super.prototype._serialize.call(this, {
  53394. name: "DoNothingAction",
  53395. properties: []
  53396. }, parent);
  53397. };
  53398. return DoNothingAction;
  53399. }(BABYLON.Action));
  53400. BABYLON.DoNothingAction = DoNothingAction;
  53401. var CombineAction = /** @class */ (function (_super) {
  53402. __extends(CombineAction, _super);
  53403. function CombineAction(triggerOptions, children, condition) {
  53404. var _this = _super.call(this, triggerOptions, condition) || this;
  53405. _this.children = children;
  53406. return _this;
  53407. }
  53408. /** @hidden */
  53409. CombineAction.prototype._prepare = function () {
  53410. for (var index = 0; index < this.children.length; index++) {
  53411. this.children[index]._actionManager = this._actionManager;
  53412. this.children[index]._prepare();
  53413. }
  53414. };
  53415. CombineAction.prototype.execute = function (evt) {
  53416. for (var index = 0; index < this.children.length; index++) {
  53417. this.children[index].execute(evt);
  53418. }
  53419. };
  53420. CombineAction.prototype.serialize = function (parent) {
  53421. var serializationObject = _super.prototype._serialize.call(this, {
  53422. name: "CombineAction",
  53423. properties: [],
  53424. combine: []
  53425. }, parent);
  53426. for (var i = 0; i < this.children.length; i++) {
  53427. serializationObject.combine.push(this.children[i].serialize(null));
  53428. }
  53429. return serializationObject;
  53430. };
  53431. return CombineAction;
  53432. }(BABYLON.Action));
  53433. BABYLON.CombineAction = CombineAction;
  53434. var ExecuteCodeAction = /** @class */ (function (_super) {
  53435. __extends(ExecuteCodeAction, _super);
  53436. function ExecuteCodeAction(triggerOptions, func, condition) {
  53437. var _this = _super.call(this, triggerOptions, condition) || this;
  53438. _this.func = func;
  53439. return _this;
  53440. }
  53441. ExecuteCodeAction.prototype.execute = function (evt) {
  53442. this.func(evt);
  53443. };
  53444. return ExecuteCodeAction;
  53445. }(BABYLON.Action));
  53446. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53447. var SetParentAction = /** @class */ (function (_super) {
  53448. __extends(SetParentAction, _super);
  53449. function SetParentAction(triggerOptions, target, parent, condition) {
  53450. var _this = _super.call(this, triggerOptions, condition) || this;
  53451. _this._target = target;
  53452. _this._parent = parent;
  53453. return _this;
  53454. }
  53455. /** @hidden */
  53456. SetParentAction.prototype._prepare = function () {
  53457. };
  53458. SetParentAction.prototype.execute = function () {
  53459. if (this._target.parent === this._parent) {
  53460. return;
  53461. }
  53462. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53463. invertParentWorldMatrix.invert();
  53464. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53465. this._target.parent = this._parent;
  53466. };
  53467. SetParentAction.prototype.serialize = function (parent) {
  53468. return _super.prototype._serialize.call(this, {
  53469. name: "SetParentAction",
  53470. properties: [
  53471. BABYLON.Action._GetTargetProperty(this._target),
  53472. BABYLON.Action._GetTargetProperty(this._parent),
  53473. ]
  53474. }, parent);
  53475. };
  53476. return SetParentAction;
  53477. }(BABYLON.Action));
  53478. BABYLON.SetParentAction = SetParentAction;
  53479. })(BABYLON || (BABYLON = {}));
  53480. //# sourceMappingURL=babylon.directActions.js.map
  53481. var BABYLON;
  53482. (function (BABYLON) {
  53483. var SpriteManager = /** @class */ (function () {
  53484. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53485. if (epsilon === void 0) { epsilon = 0.01; }
  53486. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53487. this.name = name;
  53488. this.sprites = new Array();
  53489. this.renderingGroupId = 0;
  53490. this.layerMask = 0x0FFFFFFF;
  53491. this.fogEnabled = true;
  53492. this.isPickable = false;
  53493. /**
  53494. * An event triggered when the manager is disposed.
  53495. */
  53496. this.onDisposeObservable = new BABYLON.Observable();
  53497. this._vertexBuffers = {};
  53498. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  53499. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  53500. }
  53501. this._capacity = capacity;
  53502. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53503. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53504. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53505. if (cellSize.width && cellSize.height) {
  53506. this.cellWidth = cellSize.width;
  53507. this.cellHeight = cellSize.height;
  53508. }
  53509. else if (cellSize !== undefined) {
  53510. this.cellWidth = cellSize;
  53511. this.cellHeight = cellSize;
  53512. }
  53513. else {
  53514. return;
  53515. }
  53516. this._epsilon = epsilon;
  53517. this._scene = scene;
  53518. this._scene.spriteManagers.push(this);
  53519. var indices = [];
  53520. var index = 0;
  53521. for (var count = 0; count < capacity; count++) {
  53522. indices.push(index);
  53523. indices.push(index + 1);
  53524. indices.push(index + 2);
  53525. indices.push(index);
  53526. indices.push(index + 2);
  53527. indices.push(index + 3);
  53528. index += 4;
  53529. }
  53530. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53531. // VBO
  53532. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53533. this._vertexData = new Float32Array(capacity * 16 * 4);
  53534. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53535. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53536. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53537. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53538. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53539. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53540. this._vertexBuffers["options"] = options;
  53541. this._vertexBuffers["cellInfo"] = cellInfo;
  53542. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53543. // Effects
  53544. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53545. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53546. }
  53547. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53548. set: function (callback) {
  53549. if (this._onDisposeObserver) {
  53550. this.onDisposeObservable.remove(this._onDisposeObserver);
  53551. }
  53552. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53553. },
  53554. enumerable: true,
  53555. configurable: true
  53556. });
  53557. Object.defineProperty(SpriteManager.prototype, "texture", {
  53558. get: function () {
  53559. return this._spriteTexture;
  53560. },
  53561. set: function (value) {
  53562. this._spriteTexture = value;
  53563. },
  53564. enumerable: true,
  53565. configurable: true
  53566. });
  53567. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53568. var arrayOffset = index * 16;
  53569. if (offsetX === 0)
  53570. offsetX = this._epsilon;
  53571. else if (offsetX === 1)
  53572. offsetX = 1 - this._epsilon;
  53573. if (offsetY === 0)
  53574. offsetY = this._epsilon;
  53575. else if (offsetY === 1)
  53576. offsetY = 1 - this._epsilon;
  53577. this._vertexData[arrayOffset] = sprite.position.x;
  53578. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53579. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53580. this._vertexData[arrayOffset + 3] = sprite.angle;
  53581. this._vertexData[arrayOffset + 4] = sprite.width;
  53582. this._vertexData[arrayOffset + 5] = sprite.height;
  53583. this._vertexData[arrayOffset + 6] = offsetX;
  53584. this._vertexData[arrayOffset + 7] = offsetY;
  53585. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53586. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53587. var offset = (sprite.cellIndex / rowSize) >> 0;
  53588. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53589. this._vertexData[arrayOffset + 11] = offset;
  53590. // Color
  53591. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53592. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53593. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53594. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53595. };
  53596. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53597. var count = Math.min(this._capacity, this.sprites.length);
  53598. var min = BABYLON.Vector3.Zero();
  53599. var max = BABYLON.Vector3.Zero();
  53600. var distance = Number.MAX_VALUE;
  53601. var currentSprite = null;
  53602. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53603. var cameraView = camera.getViewMatrix();
  53604. for (var index = 0; index < count; index++) {
  53605. var sprite = this.sprites[index];
  53606. if (!sprite) {
  53607. continue;
  53608. }
  53609. if (predicate) {
  53610. if (!predicate(sprite)) {
  53611. continue;
  53612. }
  53613. }
  53614. else if (!sprite.isPickable) {
  53615. continue;
  53616. }
  53617. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53618. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53619. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53620. if (ray.intersectsBoxMinMax(min, max)) {
  53621. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53622. if (distance > currentDistance) {
  53623. distance = currentDistance;
  53624. currentSprite = sprite;
  53625. if (fastCheck) {
  53626. break;
  53627. }
  53628. }
  53629. }
  53630. }
  53631. if (currentSprite) {
  53632. var result = new BABYLON.PickingInfo();
  53633. result.hit = true;
  53634. result.pickedSprite = currentSprite;
  53635. result.distance = distance;
  53636. return result;
  53637. }
  53638. return null;
  53639. };
  53640. SpriteManager.prototype.render = function () {
  53641. // Check
  53642. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53643. return;
  53644. var engine = this._scene.getEngine();
  53645. var baseSize = this._spriteTexture.getBaseSize();
  53646. // Sprites
  53647. var deltaTime = engine.getDeltaTime();
  53648. var max = Math.min(this._capacity, this.sprites.length);
  53649. var rowSize = baseSize.width / this.cellWidth;
  53650. var offset = 0;
  53651. for (var index = 0; index < max; index++) {
  53652. var sprite = this.sprites[index];
  53653. if (!sprite || !sprite.isVisible) {
  53654. continue;
  53655. }
  53656. sprite._animate(deltaTime);
  53657. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53658. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53659. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53660. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53661. }
  53662. this._buffer.update(this._vertexData);
  53663. // Render
  53664. var effect = this._effectBase;
  53665. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53666. effect = this._effectFog;
  53667. }
  53668. engine.enableEffect(effect);
  53669. var viewMatrix = this._scene.getViewMatrix();
  53670. effect.setTexture("diffuseSampler", this._spriteTexture);
  53671. effect.setMatrix("view", viewMatrix);
  53672. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53673. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53674. // Fog
  53675. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53676. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53677. effect.setColor3("vFogColor", this._scene.fogColor);
  53678. }
  53679. // VBOs
  53680. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53681. // Draw order
  53682. engine.setDepthFunctionToLessOrEqual();
  53683. effect.setBool("alphaTest", true);
  53684. engine.setColorWrite(false);
  53685. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53686. engine.setColorWrite(true);
  53687. effect.setBool("alphaTest", false);
  53688. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53689. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53690. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53691. };
  53692. SpriteManager.prototype.dispose = function () {
  53693. if (this._buffer) {
  53694. this._buffer.dispose();
  53695. this._buffer = null;
  53696. }
  53697. if (this._indexBuffer) {
  53698. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53699. this._indexBuffer = null;
  53700. }
  53701. if (this._spriteTexture) {
  53702. this._spriteTexture.dispose();
  53703. this._spriteTexture = null;
  53704. }
  53705. // Remove from scene
  53706. var index = this._scene.spriteManagers.indexOf(this);
  53707. this._scene.spriteManagers.splice(index, 1);
  53708. // Callback
  53709. this.onDisposeObservable.notifyObservers(this);
  53710. this.onDisposeObservable.clear();
  53711. };
  53712. return SpriteManager;
  53713. }());
  53714. BABYLON.SpriteManager = SpriteManager;
  53715. })(BABYLON || (BABYLON = {}));
  53716. //# sourceMappingURL=babylon.spriteManager.js.map
  53717. var BABYLON;
  53718. (function (BABYLON) {
  53719. var Sprite = /** @class */ (function () {
  53720. function Sprite(name, manager) {
  53721. this.name = name;
  53722. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53723. this.width = 1.0;
  53724. this.height = 1.0;
  53725. this.angle = 0;
  53726. this.cellIndex = 0;
  53727. this.invertU = 0;
  53728. this.invertV = 0;
  53729. this.animations = new Array();
  53730. this.isPickable = false;
  53731. this._animationStarted = false;
  53732. this._loopAnimation = false;
  53733. this._fromIndex = 0;
  53734. this._toIndex = 0;
  53735. this._delay = 0;
  53736. this._direction = 1;
  53737. this._time = 0;
  53738. /**
  53739. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53740. */
  53741. this.isVisible = true;
  53742. this._manager = manager;
  53743. this._manager.sprites.push(this);
  53744. this.position = BABYLON.Vector3.Zero();
  53745. }
  53746. Object.defineProperty(Sprite.prototype, "size", {
  53747. get: function () {
  53748. return this.width;
  53749. },
  53750. set: function (value) {
  53751. this.width = value;
  53752. this.height = value;
  53753. },
  53754. enumerable: true,
  53755. configurable: true
  53756. });
  53757. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53758. this._fromIndex = from;
  53759. this._toIndex = to;
  53760. this._loopAnimation = loop;
  53761. this._delay = delay;
  53762. this._animationStarted = true;
  53763. this._direction = from < to ? 1 : -1;
  53764. this.cellIndex = from;
  53765. this._time = 0;
  53766. this._onAnimationEnd = onAnimationEnd;
  53767. };
  53768. Sprite.prototype.stopAnimation = function () {
  53769. this._animationStarted = false;
  53770. };
  53771. /** @hidden */
  53772. Sprite.prototype._animate = function (deltaTime) {
  53773. if (!this._animationStarted)
  53774. return;
  53775. this._time += deltaTime;
  53776. if (this._time > this._delay) {
  53777. this._time = this._time % this._delay;
  53778. this.cellIndex += this._direction;
  53779. if (this.cellIndex > this._toIndex) {
  53780. if (this._loopAnimation) {
  53781. this.cellIndex = this._fromIndex;
  53782. }
  53783. else {
  53784. this.cellIndex = this._toIndex;
  53785. this._animationStarted = false;
  53786. if (this._onAnimationEnd) {
  53787. this._onAnimationEnd();
  53788. }
  53789. if (this.disposeWhenFinishedAnimating) {
  53790. this.dispose();
  53791. }
  53792. }
  53793. }
  53794. }
  53795. };
  53796. Sprite.prototype.dispose = function () {
  53797. for (var i = 0; i < this._manager.sprites.length; i++) {
  53798. if (this._manager.sprites[i] == this) {
  53799. this._manager.sprites.splice(i, 1);
  53800. }
  53801. }
  53802. };
  53803. return Sprite;
  53804. }());
  53805. BABYLON.Sprite = Sprite;
  53806. })(BABYLON || (BABYLON = {}));
  53807. //# sourceMappingURL=babylon.sprite.js.map
  53808. var BABYLON;
  53809. (function (BABYLON) {
  53810. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  53811. if (!BABYLON.PickingInfo) {
  53812. return null;
  53813. }
  53814. var pickingInfo = null;
  53815. if (!camera) {
  53816. if (!this.activeCamera) {
  53817. return null;
  53818. }
  53819. camera = this.activeCamera;
  53820. }
  53821. if (this.spriteManagers.length > 0) {
  53822. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  53823. var spriteManager = this.spriteManagers[spriteIndex];
  53824. if (!spriteManager.isPickable) {
  53825. continue;
  53826. }
  53827. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  53828. if (!result || !result.hit)
  53829. continue;
  53830. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  53831. continue;
  53832. pickingInfo = result;
  53833. if (fastCheck) {
  53834. break;
  53835. }
  53836. }
  53837. }
  53838. return pickingInfo || new BABYLON.PickingInfo();
  53839. };
  53840. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  53841. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  53842. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  53843. };
  53844. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  53845. if (!this._tempSpritePickingRay) {
  53846. return null;
  53847. }
  53848. if (!camera) {
  53849. if (!this.activeCamera) {
  53850. return null;
  53851. }
  53852. camera = this.activeCamera;
  53853. }
  53854. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  53855. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  53856. };
  53857. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  53858. if (this._pointerOverSprite === sprite) {
  53859. return;
  53860. }
  53861. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  53862. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  53863. }
  53864. this._pointerOverSprite = sprite;
  53865. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  53866. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  53867. }
  53868. };
  53869. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  53870. return this._pointerOverSprite;
  53871. };
  53872. /**
  53873. * Defines the sprite scene component responsible to manage sprites
  53874. * in a given scene.
  53875. */
  53876. var SpriteSceneComponent = /** @class */ (function () {
  53877. /**
  53878. * Creates a new instance of the component for the given scene
  53879. * @param scene Defines the scene to register the component in
  53880. */
  53881. function SpriteSceneComponent(scene) {
  53882. /**
  53883. * The component name helpfull to identify the component in the list of scene components.
  53884. */
  53885. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  53886. this.scene = scene;
  53887. this.scene.spriteManagers = new Array();
  53888. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  53889. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  53890. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  53891. this._spritePredicate = function (sprite) {
  53892. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  53893. };
  53894. }
  53895. /**
  53896. * Registers the component in a given scene
  53897. */
  53898. SpriteSceneComponent.prototype.register = function () {
  53899. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  53900. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  53901. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  53902. };
  53903. /**
  53904. * Rebuilds the elements related to this component in case of
  53905. * context lost for instance.
  53906. */
  53907. SpriteSceneComponent.prototype.rebuild = function () {
  53908. /** Nothing to do for sprites */
  53909. };
  53910. /**
  53911. * Disposes the component and the associated ressources.
  53912. */
  53913. SpriteSceneComponent.prototype.dispose = function () {
  53914. this.scene.onBeforeSpritesRenderingObservable.clear();
  53915. this.scene.onAfterSpritesRenderingObservable.clear();
  53916. var spriteManagers = this.scene.spriteManagers;
  53917. while (spriteManagers.length) {
  53918. spriteManagers[0].dispose();
  53919. }
  53920. };
  53921. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  53922. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  53923. if (result) {
  53924. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  53925. }
  53926. return result;
  53927. };
  53928. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  53929. var scene = this.scene;
  53930. if (isMeshPicked) {
  53931. scene.setPointerOverSprite(null);
  53932. }
  53933. else {
  53934. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  53935. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  53936. scene.setPointerOverSprite(pickResult.pickedSprite);
  53937. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  53938. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  53939. }
  53940. else {
  53941. canvas.style.cursor = scene.hoverCursor;
  53942. }
  53943. }
  53944. else {
  53945. scene.setPointerOverSprite(null);
  53946. }
  53947. }
  53948. return pickResult;
  53949. };
  53950. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  53951. var scene = this.scene;
  53952. scene._pickedDownSprite = null;
  53953. if (scene.spriteManagers.length > 0) {
  53954. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  53955. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  53956. if (pickResult.pickedSprite.actionManager) {
  53957. scene._pickedDownSprite = pickResult.pickedSprite;
  53958. switch (evt.button) {
  53959. case 0:
  53960. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  53961. break;
  53962. case 1:
  53963. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  53964. break;
  53965. case 2:
  53966. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  53967. break;
  53968. }
  53969. if (pickResult.pickedSprite.actionManager) {
  53970. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  53971. }
  53972. }
  53973. }
  53974. }
  53975. return pickResult;
  53976. };
  53977. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  53978. var scene = this.scene;
  53979. if (scene.spriteManagers.length > 0) {
  53980. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  53981. if (spritePickResult) {
  53982. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  53983. if (spritePickResult.pickedSprite.actionManager) {
  53984. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  53985. if (spritePickResult.pickedSprite.actionManager) {
  53986. if (!this.scene._isPointerSwiping()) {
  53987. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  53988. }
  53989. }
  53990. }
  53991. }
  53992. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  53993. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  53994. }
  53995. }
  53996. }
  53997. return pickResult;
  53998. };
  53999. return SpriteSceneComponent;
  54000. }());
  54001. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  54002. })(BABYLON || (BABYLON = {}));
  54003. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  54004. var BABYLON;
  54005. (function (BABYLON) {
  54006. var IntersectionInfo = /** @class */ (function () {
  54007. function IntersectionInfo(bu, bv, distance) {
  54008. this.bu = bu;
  54009. this.bv = bv;
  54010. this.distance = distance;
  54011. this.faceId = 0;
  54012. this.subMeshId = 0;
  54013. }
  54014. return IntersectionInfo;
  54015. }());
  54016. BABYLON.IntersectionInfo = IntersectionInfo;
  54017. /**
  54018. * Information about the result of picking within a scene
  54019. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54020. */
  54021. var PickingInfo = /** @class */ (function () {
  54022. function PickingInfo() {
  54023. /**
  54024. * If the pick collided with an object
  54025. */
  54026. this.hit = false;
  54027. /**
  54028. * Distance away where the pick collided
  54029. */
  54030. this.distance = 0;
  54031. /**
  54032. * The location of pick collision
  54033. */
  54034. this.pickedPoint = null;
  54035. /**
  54036. * The mesh corresponding the the pick collision
  54037. */
  54038. this.pickedMesh = null;
  54039. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54040. this.bu = 0;
  54041. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54042. this.bv = 0;
  54043. /** The id of the face on the mesh that was picked */
  54044. this.faceId = -1;
  54045. /** Id of the the submesh that was picked */
  54046. this.subMeshId = 0;
  54047. /** If a sprite was picked, this will be the sprite the pick collided with */
  54048. this.pickedSprite = null;
  54049. /**
  54050. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54051. */
  54052. this.originMesh = null;
  54053. /**
  54054. * The ray that was used to perform the picking.
  54055. */
  54056. this.ray = null;
  54057. }
  54058. /**
  54059. * Gets the normal correspodning to the face the pick collided with
  54060. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54061. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54062. * @returns The normal correspodning to the face the pick collided with
  54063. */
  54064. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54065. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54066. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54067. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54068. return null;
  54069. }
  54070. var indices = this.pickedMesh.getIndices();
  54071. if (!indices) {
  54072. return null;
  54073. }
  54074. var result;
  54075. if (useVerticesNormals) {
  54076. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54077. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54078. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54079. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54080. normal0 = normal0.scale(this.bu);
  54081. normal1 = normal1.scale(this.bv);
  54082. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54083. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54084. }
  54085. else {
  54086. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54087. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54088. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54089. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54090. var p1p2 = vertex1.subtract(vertex2);
  54091. var p3p2 = vertex3.subtract(vertex2);
  54092. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54093. }
  54094. if (useWorldCoordinates) {
  54095. var wm = this.pickedMesh.getWorldMatrix();
  54096. if (this.pickedMesh.nonUniformScaling) {
  54097. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54098. wm = BABYLON.Tmp.Matrix[0];
  54099. wm.setTranslationFromFloats(0, 0, 0);
  54100. wm.invert();
  54101. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54102. wm = BABYLON.Tmp.Matrix[1];
  54103. }
  54104. result = BABYLON.Vector3.TransformNormal(result, wm);
  54105. }
  54106. result.normalize();
  54107. return result;
  54108. };
  54109. /**
  54110. * Gets the texture coordinates of where the pick occured
  54111. * @returns the vector containing the coordnates of the texture
  54112. */
  54113. PickingInfo.prototype.getTextureCoordinates = function () {
  54114. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54115. return null;
  54116. }
  54117. var indices = this.pickedMesh.getIndices();
  54118. if (!indices) {
  54119. return null;
  54120. }
  54121. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54122. if (!uvs) {
  54123. return null;
  54124. }
  54125. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54126. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54127. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54128. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54129. uv1 = uv1.scale(this.bu);
  54130. uv2 = uv2.scale(this.bv);
  54131. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54132. };
  54133. return PickingInfo;
  54134. }());
  54135. BABYLON.PickingInfo = PickingInfo;
  54136. })(BABYLON || (BABYLON = {}));
  54137. //# sourceMappingURL=babylon.pickingInfo.js.map
  54138. var BABYLON;
  54139. (function (BABYLON) {
  54140. var Ray = /** @class */ (function () {
  54141. function Ray(origin, direction, length) {
  54142. if (length === void 0) { length = Number.MAX_VALUE; }
  54143. this.origin = origin;
  54144. this.direction = direction;
  54145. this.length = length;
  54146. }
  54147. // Methods
  54148. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54149. var d = 0.0;
  54150. var maxValue = Number.MAX_VALUE;
  54151. var inv;
  54152. var min;
  54153. var max;
  54154. var temp;
  54155. if (Math.abs(this.direction.x) < 0.0000001) {
  54156. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54157. return false;
  54158. }
  54159. }
  54160. else {
  54161. inv = 1.0 / this.direction.x;
  54162. min = (minimum.x - this.origin.x) * inv;
  54163. max = (maximum.x - this.origin.x) * inv;
  54164. if (max === -Infinity) {
  54165. max = Infinity;
  54166. }
  54167. if (min > max) {
  54168. temp = min;
  54169. min = max;
  54170. max = temp;
  54171. }
  54172. d = Math.max(min, d);
  54173. maxValue = Math.min(max, maxValue);
  54174. if (d > maxValue) {
  54175. return false;
  54176. }
  54177. }
  54178. if (Math.abs(this.direction.y) < 0.0000001) {
  54179. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54180. return false;
  54181. }
  54182. }
  54183. else {
  54184. inv = 1.0 / this.direction.y;
  54185. min = (minimum.y - this.origin.y) * inv;
  54186. max = (maximum.y - this.origin.y) * inv;
  54187. if (max === -Infinity) {
  54188. max = Infinity;
  54189. }
  54190. if (min > max) {
  54191. temp = min;
  54192. min = max;
  54193. max = temp;
  54194. }
  54195. d = Math.max(min, d);
  54196. maxValue = Math.min(max, maxValue);
  54197. if (d > maxValue) {
  54198. return false;
  54199. }
  54200. }
  54201. if (Math.abs(this.direction.z) < 0.0000001) {
  54202. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54203. return false;
  54204. }
  54205. }
  54206. else {
  54207. inv = 1.0 / this.direction.z;
  54208. min = (minimum.z - this.origin.z) * inv;
  54209. max = (maximum.z - this.origin.z) * inv;
  54210. if (max === -Infinity) {
  54211. max = Infinity;
  54212. }
  54213. if (min > max) {
  54214. temp = min;
  54215. min = max;
  54216. max = temp;
  54217. }
  54218. d = Math.max(min, d);
  54219. maxValue = Math.min(max, maxValue);
  54220. if (d > maxValue) {
  54221. return false;
  54222. }
  54223. }
  54224. return true;
  54225. };
  54226. Ray.prototype.intersectsBox = function (box) {
  54227. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54228. };
  54229. Ray.prototype.intersectsSphere = function (sphere) {
  54230. var x = sphere.center.x - this.origin.x;
  54231. var y = sphere.center.y - this.origin.y;
  54232. var z = sphere.center.z - this.origin.z;
  54233. var pyth = (x * x) + (y * y) + (z * z);
  54234. var rr = sphere.radius * sphere.radius;
  54235. if (pyth <= rr) {
  54236. return true;
  54237. }
  54238. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54239. if (dot < 0.0) {
  54240. return false;
  54241. }
  54242. var temp = pyth - (dot * dot);
  54243. return temp <= rr;
  54244. };
  54245. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54246. if (!this._edge1) {
  54247. this._edge1 = BABYLON.Vector3.Zero();
  54248. this._edge2 = BABYLON.Vector3.Zero();
  54249. this._pvec = BABYLON.Vector3.Zero();
  54250. this._tvec = BABYLON.Vector3.Zero();
  54251. this._qvec = BABYLON.Vector3.Zero();
  54252. }
  54253. vertex1.subtractToRef(vertex0, this._edge1);
  54254. vertex2.subtractToRef(vertex0, this._edge2);
  54255. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54256. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54257. if (det === 0) {
  54258. return null;
  54259. }
  54260. var invdet = 1 / det;
  54261. this.origin.subtractToRef(vertex0, this._tvec);
  54262. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54263. if (bu < 0 || bu > 1.0) {
  54264. return null;
  54265. }
  54266. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54267. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54268. if (bv < 0 || bu + bv > 1.0) {
  54269. return null;
  54270. }
  54271. //check if the distance is longer than the predefined length.
  54272. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54273. if (distance > this.length) {
  54274. return null;
  54275. }
  54276. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54277. };
  54278. Ray.prototype.intersectsPlane = function (plane) {
  54279. var distance;
  54280. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54281. if (Math.abs(result1) < 9.99999997475243E-07) {
  54282. return null;
  54283. }
  54284. else {
  54285. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54286. distance = (-plane.d - result2) / result1;
  54287. if (distance < 0.0) {
  54288. if (distance < -9.99999997475243E-07) {
  54289. return null;
  54290. }
  54291. else {
  54292. return 0;
  54293. }
  54294. }
  54295. return distance;
  54296. }
  54297. };
  54298. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54299. var tm = BABYLON.Tmp.Matrix[0];
  54300. mesh.getWorldMatrix().invertToRef(tm);
  54301. if (this._tmpRay) {
  54302. Ray.TransformToRef(this, tm, this._tmpRay);
  54303. }
  54304. else {
  54305. this._tmpRay = Ray.Transform(this, tm);
  54306. }
  54307. return mesh.intersects(this._tmpRay, fastCheck);
  54308. };
  54309. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54310. if (results) {
  54311. results.length = 0;
  54312. }
  54313. else {
  54314. results = [];
  54315. }
  54316. for (var i = 0; i < meshes.length; i++) {
  54317. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54318. if (pickInfo.hit) {
  54319. results.push(pickInfo);
  54320. }
  54321. }
  54322. results.sort(this._comparePickingInfo);
  54323. return results;
  54324. };
  54325. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54326. if (pickingInfoA.distance < pickingInfoB.distance) {
  54327. return -1;
  54328. }
  54329. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54330. return 1;
  54331. }
  54332. else {
  54333. return 0;
  54334. }
  54335. };
  54336. /**
  54337. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54338. * @param sega the first point of the segment to test the intersection against
  54339. * @param segb the second point of the segment to test the intersection against
  54340. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54341. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54342. */
  54343. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54344. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54345. var u = segb.subtract(sega);
  54346. var v = rsegb.subtract(this.origin);
  54347. var w = sega.subtract(this.origin);
  54348. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54349. var b = BABYLON.Vector3.Dot(u, v);
  54350. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54351. var d = BABYLON.Vector3.Dot(u, w);
  54352. var e = BABYLON.Vector3.Dot(v, w);
  54353. var D = a * c - b * b; // always >= 0
  54354. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54355. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54356. // compute the line parameters of the two closest points
  54357. if (D < Ray.smallnum) { // the lines are almost parallel
  54358. sN = 0.0; // force using point P0 on segment S1
  54359. sD = 1.0; // to prevent possible division by 0.0 later
  54360. tN = e;
  54361. tD = c;
  54362. }
  54363. else { // get the closest points on the infinite lines
  54364. sN = (b * e - c * d);
  54365. tN = (a * e - b * d);
  54366. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54367. sN = 0.0;
  54368. tN = e;
  54369. tD = c;
  54370. }
  54371. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54372. sN = sD;
  54373. tN = e + b;
  54374. tD = c;
  54375. }
  54376. }
  54377. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54378. tN = 0.0;
  54379. // recompute sc for this edge
  54380. if (-d < 0.0) {
  54381. sN = 0.0;
  54382. }
  54383. else if (-d > a)
  54384. sN = sD;
  54385. else {
  54386. sN = -d;
  54387. sD = a;
  54388. }
  54389. }
  54390. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54391. tN = tD;
  54392. // recompute sc for this edge
  54393. if ((-d + b) < 0.0) {
  54394. sN = 0;
  54395. }
  54396. else if ((-d + b) > a) {
  54397. sN = sD;
  54398. }
  54399. else {
  54400. sN = (-d + b);
  54401. sD = a;
  54402. }
  54403. }
  54404. // finally do the division to get sc and tc
  54405. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54406. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54407. // get the difference of the two closest points
  54408. var qtc = v.multiplyByFloats(tc, tc, tc);
  54409. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54410. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54411. if (isIntersected) {
  54412. return qtc.length();
  54413. }
  54414. return -1;
  54415. };
  54416. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54417. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54418. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54419. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54420. this.direction.normalize();
  54421. return this;
  54422. };
  54423. // Statics
  54424. Ray.Zero = function () {
  54425. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54426. };
  54427. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54428. var result = Ray.Zero();
  54429. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54430. };
  54431. /**
  54432. * 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
  54433. * transformed to the given world matrix.
  54434. * @param origin The origin point
  54435. * @param end The end point
  54436. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54437. */
  54438. Ray.CreateNewFromTo = function (origin, end, world) {
  54439. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54440. var direction = end.subtract(origin);
  54441. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54442. direction.normalize();
  54443. return Ray.Transform(new Ray(origin, direction, length), world);
  54444. };
  54445. Ray.Transform = function (ray, matrix) {
  54446. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54447. Ray.TransformToRef(ray, matrix, result);
  54448. return result;
  54449. };
  54450. Ray.TransformToRef = function (ray, matrix, result) {
  54451. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54452. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54453. result.length = ray.length;
  54454. var dir = result.direction;
  54455. var len = dir.length();
  54456. if (!(len === 0 || len === 1)) {
  54457. var num = 1.0 / len;
  54458. dir.x *= num;
  54459. dir.y *= num;
  54460. dir.z *= num;
  54461. result.length *= len;
  54462. }
  54463. };
  54464. Ray.smallnum = 0.00000001;
  54465. Ray.rayl = 10e8;
  54466. return Ray;
  54467. }());
  54468. BABYLON.Ray = Ray;
  54469. })(BABYLON || (BABYLON = {}));
  54470. //# sourceMappingURL=babylon.ray.js.map
  54471. var BABYLON;
  54472. (function (BABYLON) {
  54473. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54474. if (boxMin.x > sphereCenter.x + sphereRadius)
  54475. return false;
  54476. if (sphereCenter.x - sphereRadius > boxMax.x)
  54477. return false;
  54478. if (boxMin.y > sphereCenter.y + sphereRadius)
  54479. return false;
  54480. if (sphereCenter.y - sphereRadius > boxMax.y)
  54481. return false;
  54482. if (boxMin.z > sphereCenter.z + sphereRadius)
  54483. return false;
  54484. if (sphereCenter.z - sphereRadius > boxMax.z)
  54485. return false;
  54486. return true;
  54487. };
  54488. var getLowestRoot = (function () {
  54489. var result = { root: 0, found: false };
  54490. return function (a, b, c, maxR) {
  54491. result.root = 0;
  54492. result.found = false;
  54493. var determinant = b * b - 4.0 * a * c;
  54494. if (determinant < 0)
  54495. return result;
  54496. var sqrtD = Math.sqrt(determinant);
  54497. var r1 = (-b - sqrtD) / (2.0 * a);
  54498. var r2 = (-b + sqrtD) / (2.0 * a);
  54499. if (r1 > r2) {
  54500. var temp = r2;
  54501. r2 = r1;
  54502. r1 = temp;
  54503. }
  54504. if (r1 > 0 && r1 < maxR) {
  54505. result.root = r1;
  54506. result.found = true;
  54507. return result;
  54508. }
  54509. if (r2 > 0 && r2 < maxR) {
  54510. result.root = r2;
  54511. result.found = true;
  54512. return result;
  54513. }
  54514. return result;
  54515. };
  54516. })();
  54517. var Collider = /** @class */ (function () {
  54518. function Collider() {
  54519. this._collisionPoint = BABYLON.Vector3.Zero();
  54520. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54521. this._tempVector = BABYLON.Vector3.Zero();
  54522. this._tempVector2 = BABYLON.Vector3.Zero();
  54523. this._tempVector3 = BABYLON.Vector3.Zero();
  54524. this._tempVector4 = BABYLON.Vector3.Zero();
  54525. this._edge = BABYLON.Vector3.Zero();
  54526. this._baseToVertex = BABYLON.Vector3.Zero();
  54527. this._destinationPoint = BABYLON.Vector3.Zero();
  54528. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54529. this._displacementVector = BABYLON.Vector3.Zero();
  54530. /** @hidden */
  54531. this._radius = BABYLON.Vector3.One();
  54532. /** @hidden */
  54533. this._retry = 0;
  54534. /** @hidden */
  54535. this._basePointWorld = BABYLON.Vector3.Zero();
  54536. this._velocityWorld = BABYLON.Vector3.Zero();
  54537. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54538. this._collisionMask = -1;
  54539. }
  54540. Object.defineProperty(Collider.prototype, "collisionMask", {
  54541. get: function () {
  54542. return this._collisionMask;
  54543. },
  54544. set: function (mask) {
  54545. this._collisionMask = !isNaN(mask) ? mask : -1;
  54546. },
  54547. enumerable: true,
  54548. configurable: true
  54549. });
  54550. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54551. /**
  54552. * Gets the plane normal used to compute the sliding response (in local space)
  54553. */
  54554. get: function () {
  54555. return this._slidePlaneNormal;
  54556. },
  54557. enumerable: true,
  54558. configurable: true
  54559. });
  54560. // Methods
  54561. /** @hidden */
  54562. Collider.prototype._initialize = function (source, dir, e) {
  54563. this._velocity = dir;
  54564. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54565. this._basePoint = source;
  54566. source.multiplyToRef(this._radius, this._basePointWorld);
  54567. dir.multiplyToRef(this._radius, this._velocityWorld);
  54568. this._velocityWorldLength = this._velocityWorld.length();
  54569. this._epsilon = e;
  54570. this.collisionFound = false;
  54571. };
  54572. /** @hidden */
  54573. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54574. pa.subtractToRef(point, this._tempVector);
  54575. pb.subtractToRef(point, this._tempVector2);
  54576. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54577. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54578. if (d < 0)
  54579. return false;
  54580. pc.subtractToRef(point, this._tempVector3);
  54581. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54582. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54583. if (d < 0)
  54584. return false;
  54585. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54586. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54587. return d >= 0;
  54588. };
  54589. /** @hidden */
  54590. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54591. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54592. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54593. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54594. return false;
  54595. }
  54596. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54597. return false;
  54598. return true;
  54599. };
  54600. /** @hidden */
  54601. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54602. var t0;
  54603. var embeddedInPlane = false;
  54604. //defensive programming, actually not needed.
  54605. if (!trianglePlaneArray) {
  54606. trianglePlaneArray = [];
  54607. }
  54608. if (!trianglePlaneArray[faceIndex]) {
  54609. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54610. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54611. }
  54612. var trianglePlane = trianglePlaneArray[faceIndex];
  54613. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54614. return;
  54615. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54616. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54617. if (normalDotVelocity == 0) {
  54618. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54619. return;
  54620. embeddedInPlane = true;
  54621. t0 = 0;
  54622. }
  54623. else {
  54624. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54625. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54626. if (t0 > t1) {
  54627. var temp = t1;
  54628. t1 = t0;
  54629. t0 = temp;
  54630. }
  54631. if (t0 > 1.0 || t1 < 0.0)
  54632. return;
  54633. if (t0 < 0)
  54634. t0 = 0;
  54635. if (t0 > 1.0)
  54636. t0 = 1.0;
  54637. }
  54638. this._collisionPoint.copyFromFloats(0, 0, 0);
  54639. var found = false;
  54640. var t = 1.0;
  54641. if (!embeddedInPlane) {
  54642. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54643. this._velocity.scaleToRef(t0, this._tempVector);
  54644. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54645. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54646. found = true;
  54647. t = t0;
  54648. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54649. }
  54650. }
  54651. if (!found) {
  54652. var velocitySquaredLength = this._velocity.lengthSquared();
  54653. var a = velocitySquaredLength;
  54654. this._basePoint.subtractToRef(p1, this._tempVector);
  54655. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54656. var c = this._tempVector.lengthSquared() - 1.0;
  54657. var lowestRoot = getLowestRoot(a, b, c, t);
  54658. if (lowestRoot.found) {
  54659. t = lowestRoot.root;
  54660. found = true;
  54661. this._collisionPoint.copyFrom(p1);
  54662. }
  54663. this._basePoint.subtractToRef(p2, this._tempVector);
  54664. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54665. c = this._tempVector.lengthSquared() - 1.0;
  54666. lowestRoot = getLowestRoot(a, b, c, t);
  54667. if (lowestRoot.found) {
  54668. t = lowestRoot.root;
  54669. found = true;
  54670. this._collisionPoint.copyFrom(p2);
  54671. }
  54672. this._basePoint.subtractToRef(p3, this._tempVector);
  54673. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54674. c = this._tempVector.lengthSquared() - 1.0;
  54675. lowestRoot = getLowestRoot(a, b, c, t);
  54676. if (lowestRoot.found) {
  54677. t = lowestRoot.root;
  54678. found = true;
  54679. this._collisionPoint.copyFrom(p3);
  54680. }
  54681. p2.subtractToRef(p1, this._edge);
  54682. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54683. var edgeSquaredLength = this._edge.lengthSquared();
  54684. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54685. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54686. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54687. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54688. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54689. lowestRoot = getLowestRoot(a, b, c, t);
  54690. if (lowestRoot.found) {
  54691. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54692. if (f >= 0.0 && f <= 1.0) {
  54693. t = lowestRoot.root;
  54694. found = true;
  54695. this._edge.scaleInPlace(f);
  54696. p1.addToRef(this._edge, this._collisionPoint);
  54697. }
  54698. }
  54699. p3.subtractToRef(p2, this._edge);
  54700. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54701. edgeSquaredLength = this._edge.lengthSquared();
  54702. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54703. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54704. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54705. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54706. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54707. lowestRoot = getLowestRoot(a, b, c, t);
  54708. if (lowestRoot.found) {
  54709. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54710. if (f >= 0.0 && f <= 1.0) {
  54711. t = lowestRoot.root;
  54712. found = true;
  54713. this._edge.scaleInPlace(f);
  54714. p2.addToRef(this._edge, this._collisionPoint);
  54715. }
  54716. }
  54717. p1.subtractToRef(p3, this._edge);
  54718. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54719. edgeSquaredLength = this._edge.lengthSquared();
  54720. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54721. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54722. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54723. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54724. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54725. lowestRoot = getLowestRoot(a, b, c, t);
  54726. if (lowestRoot.found) {
  54727. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54728. if (f >= 0.0 && f <= 1.0) {
  54729. t = lowestRoot.root;
  54730. found = true;
  54731. this._edge.scaleInPlace(f);
  54732. p3.addToRef(this._edge, this._collisionPoint);
  54733. }
  54734. }
  54735. }
  54736. if (found) {
  54737. var distToCollision = t * this._velocity.length();
  54738. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54739. if (!this.intersectionPoint) {
  54740. this.intersectionPoint = this._collisionPoint.clone();
  54741. }
  54742. else {
  54743. this.intersectionPoint.copyFrom(this._collisionPoint);
  54744. }
  54745. this._nearestDistance = distToCollision;
  54746. this.collisionFound = true;
  54747. }
  54748. }
  54749. };
  54750. /** @hidden */
  54751. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54752. for (var i = indexStart; i < indexEnd; i += 3) {
  54753. var p1 = pts[indices[i] - decal];
  54754. var p2 = pts[indices[i + 1] - decal];
  54755. var p3 = pts[indices[i + 2] - decal];
  54756. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54757. }
  54758. };
  54759. /** @hidden */
  54760. Collider.prototype._getResponse = function (pos, vel) {
  54761. pos.addToRef(vel, this._destinationPoint);
  54762. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54763. this._basePoint.addToRef(vel, pos);
  54764. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54765. this._slidePlaneNormal.normalize();
  54766. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54767. pos.addInPlace(this._displacementVector);
  54768. this.intersectionPoint.addInPlace(this._displacementVector);
  54769. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54770. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54771. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54772. };
  54773. return Collider;
  54774. }());
  54775. BABYLON.Collider = Collider;
  54776. })(BABYLON || (BABYLON = {}));
  54777. //# sourceMappingURL=babylon.collider.js.map
  54778. var BABYLON;
  54779. (function (BABYLON) {
  54780. //WebWorker code will be inserted to this variable.
  54781. BABYLON.CollisionWorker = "";
  54782. /** Defines supported task for worker process */
  54783. var WorkerTaskType;
  54784. (function (WorkerTaskType) {
  54785. /** Initialization */
  54786. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54787. /** Update of geometry */
  54788. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54789. /** Evaluate collision */
  54790. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54791. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54792. /** Defines kind of replies returned by worker */
  54793. var WorkerReplyType;
  54794. (function (WorkerReplyType) {
  54795. /** Success */
  54796. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54797. /** Unkown error */
  54798. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54799. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54800. var CollisionCoordinatorWorker = /** @class */ (function () {
  54801. function CollisionCoordinatorWorker() {
  54802. var _this = this;
  54803. this._scaledPosition = BABYLON.Vector3.Zero();
  54804. this._scaledVelocity = BABYLON.Vector3.Zero();
  54805. this.onMeshUpdated = function (transformNode) {
  54806. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54807. };
  54808. this.onGeometryUpdated = function (geometry) {
  54809. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54810. };
  54811. this._afterRender = function () {
  54812. if (!_this._init)
  54813. return;
  54814. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54815. return;
  54816. }
  54817. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54818. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54819. if (_this._runningUpdated > 4) {
  54820. return;
  54821. }
  54822. ++_this._runningUpdated;
  54823. var payload = {
  54824. updatedMeshes: _this._addUpdateMeshesList,
  54825. updatedGeometries: _this._addUpdateGeometriesList,
  54826. removedGeometries: _this._toRemoveGeometryArray,
  54827. removedMeshes: _this._toRemoveMeshesArray
  54828. };
  54829. var message = {
  54830. payload: payload,
  54831. taskType: WorkerTaskType.UPDATE
  54832. };
  54833. var serializable = [];
  54834. for (var id in payload.updatedGeometries) {
  54835. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54836. //prepare transferables
  54837. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54838. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54839. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54840. }
  54841. }
  54842. _this._worker.postMessage(message, serializable);
  54843. _this._addUpdateMeshesList = {};
  54844. _this._addUpdateGeometriesList = {};
  54845. _this._toRemoveGeometryArray = [];
  54846. _this._toRemoveMeshesArray = [];
  54847. };
  54848. this._onMessageFromWorker = function (e) {
  54849. var returnData = e.data;
  54850. if (returnData.error != WorkerReplyType.SUCCESS) {
  54851. //TODO what errors can be returned from the worker?
  54852. BABYLON.Tools.Warn("error returned from worker!");
  54853. return;
  54854. }
  54855. switch (returnData.taskType) {
  54856. case WorkerTaskType.INIT:
  54857. _this._init = true;
  54858. //Update the worked with ALL of the scene's current state
  54859. _this._scene.meshes.forEach(function (mesh) {
  54860. _this.onMeshAdded(mesh);
  54861. });
  54862. _this._scene.getGeometries().forEach(function (geometry) {
  54863. _this.onGeometryAdded(geometry);
  54864. });
  54865. break;
  54866. case WorkerTaskType.UPDATE:
  54867. _this._runningUpdated--;
  54868. break;
  54869. case WorkerTaskType.COLLIDE:
  54870. var returnPayload = returnData.payload;
  54871. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54872. return;
  54873. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54874. if (callback) {
  54875. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54876. if (mesh) {
  54877. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54878. }
  54879. }
  54880. //cleanup
  54881. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54882. break;
  54883. }
  54884. };
  54885. this._collisionsCallbackArray = [];
  54886. this._init = false;
  54887. this._runningUpdated = 0;
  54888. this._addUpdateMeshesList = {};
  54889. this._addUpdateGeometriesList = {};
  54890. this._toRemoveGeometryArray = [];
  54891. this._toRemoveMeshesArray = [];
  54892. }
  54893. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54894. if (!this._init)
  54895. return;
  54896. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54897. return;
  54898. position.divideToRef(collider._radius, this._scaledPosition);
  54899. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54900. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54901. var payload = {
  54902. collider: {
  54903. position: this._scaledPosition.asArray(),
  54904. velocity: this._scaledVelocity.asArray(),
  54905. radius: collider._radius.asArray()
  54906. },
  54907. collisionId: collisionIndex,
  54908. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54909. maximumRetry: maximumRetry
  54910. };
  54911. var message = {
  54912. payload: payload,
  54913. taskType: WorkerTaskType.COLLIDE
  54914. };
  54915. this._worker.postMessage(message);
  54916. };
  54917. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54918. this._scene = scene;
  54919. this._scene.registerAfterRender(this._afterRender);
  54920. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54921. this._worker = new Worker(workerUrl);
  54922. this._worker.onmessage = this._onMessageFromWorker;
  54923. var message = {
  54924. payload: {},
  54925. taskType: WorkerTaskType.INIT
  54926. };
  54927. this._worker.postMessage(message);
  54928. };
  54929. CollisionCoordinatorWorker.prototype.destroy = function () {
  54930. this._scene.unregisterAfterRender(this._afterRender);
  54931. this._worker.terminate();
  54932. };
  54933. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54934. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54935. this.onMeshUpdated(mesh);
  54936. };
  54937. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54938. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54939. };
  54940. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54941. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54942. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54943. this.onGeometryUpdated(geometry);
  54944. };
  54945. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54946. this._toRemoveGeometryArray.push(geometry.id);
  54947. };
  54948. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54949. var submeshes = [];
  54950. if (mesh.subMeshes) {
  54951. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54952. var boundingInfo = sm.getBoundingInfo();
  54953. return {
  54954. position: idx,
  54955. verticesStart: sm.verticesStart,
  54956. verticesCount: sm.verticesCount,
  54957. indexStart: sm.indexStart,
  54958. indexCount: sm.indexCount,
  54959. hasMaterial: !!sm.getMaterial(),
  54960. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54961. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54962. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54963. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54964. };
  54965. });
  54966. }
  54967. var geometryId = null;
  54968. if (mesh instanceof BABYLON.Mesh) {
  54969. var geometry = mesh.geometry;
  54970. geometryId = geometry ? geometry.id : null;
  54971. }
  54972. else if (mesh instanceof BABYLON.InstancedMesh) {
  54973. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54974. geometryId = geometry ? geometry.id : null;
  54975. }
  54976. var boundingInfo = mesh.getBoundingInfo();
  54977. return {
  54978. uniqueId: mesh.uniqueId,
  54979. id: mesh.id,
  54980. name: mesh.name,
  54981. geometryId: geometryId,
  54982. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54983. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54984. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54985. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54986. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54987. subMeshes: submeshes,
  54988. checkCollisions: mesh.checkCollisions
  54989. };
  54990. };
  54991. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54992. return {
  54993. id: geometry.id,
  54994. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54995. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54996. indices: new Uint32Array(geometry.getIndices() || []),
  54997. };
  54998. };
  54999. return CollisionCoordinatorWorker;
  55000. }());
  55001. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55002. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55003. function CollisionCoordinatorLegacy() {
  55004. this._scaledPosition = BABYLON.Vector3.Zero();
  55005. this._scaledVelocity = BABYLON.Vector3.Zero();
  55006. this._finalPosition = BABYLON.Vector3.Zero();
  55007. }
  55008. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55009. position.divideToRef(collider._radius, this._scaledPosition);
  55010. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55011. collider.collidedMesh = null;
  55012. collider._retry = 0;
  55013. collider._initialVelocity = this._scaledVelocity;
  55014. collider._initialPosition = this._scaledPosition;
  55015. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55016. this._finalPosition.multiplyInPlace(collider._radius);
  55017. //run the callback
  55018. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55019. };
  55020. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55021. this._scene = scene;
  55022. };
  55023. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55024. //Legacy need no destruction method.
  55025. };
  55026. //No update in legacy mode
  55027. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55028. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55029. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55030. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55031. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55032. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55033. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55034. if (excludedMesh === void 0) { excludedMesh = null; }
  55035. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55036. if (collider._retry >= maximumRetry) {
  55037. finalPosition.copyFrom(position);
  55038. return;
  55039. }
  55040. // Check if this is a mesh else camera or -1
  55041. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55042. collider._initialize(position, velocity, closeDistance);
  55043. // Check all meshes
  55044. for (var index = 0; index < this._scene.meshes.length; index++) {
  55045. var mesh = this._scene.meshes[index];
  55046. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55047. mesh._checkCollision(collider);
  55048. }
  55049. }
  55050. if (!collider.collisionFound) {
  55051. position.addToRef(velocity, finalPosition);
  55052. return;
  55053. }
  55054. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55055. collider._getResponse(position, velocity);
  55056. }
  55057. if (velocity.length() <= closeDistance) {
  55058. finalPosition.copyFrom(position);
  55059. return;
  55060. }
  55061. collider._retry++;
  55062. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55063. };
  55064. return CollisionCoordinatorLegacy;
  55065. }());
  55066. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55067. })(BABYLON || (BABYLON = {}));
  55068. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55069. var BABYLON;
  55070. (function (BABYLON) {
  55071. /**
  55072. * A particle represents one of the element emitted by a particle system.
  55073. * This is mainly define by its coordinates, direction, velocity and age.
  55074. */
  55075. var Particle = /** @class */ (function () {
  55076. /**
  55077. * Creates a new instance Particle
  55078. * @param particleSystem the particle system the particle belongs to
  55079. */
  55080. function Particle(
  55081. /**
  55082. * The particle system the particle belongs to.
  55083. */
  55084. particleSystem) {
  55085. this.particleSystem = particleSystem;
  55086. /**
  55087. * The world position of the particle in the scene.
  55088. */
  55089. this.position = BABYLON.Vector3.Zero();
  55090. /**
  55091. * The world direction of the particle in the scene.
  55092. */
  55093. this.direction = BABYLON.Vector3.Zero();
  55094. /**
  55095. * The color of the particle.
  55096. */
  55097. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55098. /**
  55099. * The color change of the particle per step.
  55100. */
  55101. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55102. /**
  55103. * Defines how long will the life of the particle be.
  55104. */
  55105. this.lifeTime = 1.0;
  55106. /**
  55107. * The current age of the particle.
  55108. */
  55109. this.age = 0;
  55110. /**
  55111. * The current size of the particle.
  55112. */
  55113. this.size = 0;
  55114. /**
  55115. * The current scale of the particle.
  55116. */
  55117. this.scale = new BABYLON.Vector2(1, 1);
  55118. /**
  55119. * The current angle of the particle.
  55120. */
  55121. this.angle = 0;
  55122. /**
  55123. * Defines how fast is the angle changing.
  55124. */
  55125. this.angularSpeed = 0;
  55126. /**
  55127. * Defines the cell index used by the particle to be rendered from a sprite.
  55128. */
  55129. this.cellIndex = 0;
  55130. /** @hidden */
  55131. this._attachedSubEmitters = null;
  55132. /** @hidden */
  55133. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55134. /** @hidden */
  55135. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55136. /** @hidden */
  55137. this._currentSize1 = 0;
  55138. /** @hidden */
  55139. this._currentSize2 = 0;
  55140. /** @hidden */
  55141. this._currentAngularSpeed1 = 0;
  55142. /** @hidden */
  55143. this._currentAngularSpeed2 = 0;
  55144. /** @hidden */
  55145. this._currentVelocity1 = 0;
  55146. /** @hidden */
  55147. this._currentVelocity2 = 0;
  55148. /** @hidden */
  55149. this._currentLimitVelocity1 = 0;
  55150. /** @hidden */
  55151. this._currentLimitVelocity2 = 0;
  55152. /** @hidden */
  55153. this._currentDrag1 = 0;
  55154. /** @hidden */
  55155. this._currentDrag2 = 0;
  55156. this.id = Particle._Count++;
  55157. if (!this.particleSystem.isAnimationSheetEnabled) {
  55158. return;
  55159. }
  55160. this.updateCellInfoFromSystem();
  55161. }
  55162. Particle.prototype.updateCellInfoFromSystem = function () {
  55163. this.cellIndex = this.particleSystem.startSpriteCellID;
  55164. };
  55165. /**
  55166. * Defines how the sprite cell index is updated for the particle
  55167. */
  55168. Particle.prototype.updateCellIndex = function () {
  55169. var offsetAge = this.age;
  55170. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  55171. if (this.particleSystem.spriteRandomStartCell) {
  55172. if (this._randomCellOffset === undefined) {
  55173. this._randomCellOffset = Math.random() * this.lifeTime;
  55174. }
  55175. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  55176. changeSpeed = 1;
  55177. offsetAge = this._randomCellOffset;
  55178. }
  55179. else {
  55180. offsetAge += this._randomCellOffset;
  55181. }
  55182. }
  55183. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55184. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  55185. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55186. };
  55187. /** @hidden */
  55188. Particle.prototype._reset = function () {
  55189. this.age = 0;
  55190. this._currentColorGradient = null;
  55191. this._currentSizeGradient = null;
  55192. this._currentAngularSpeedGradient = null;
  55193. this._currentVelocityGradient = null;
  55194. this._currentLimitVelocityGradient = null;
  55195. this._currentDragGradient = null;
  55196. this.cellIndex = this.particleSystem.startSpriteCellID;
  55197. this._randomCellOffset = undefined;
  55198. };
  55199. /**
  55200. * Copy the properties of particle to another one.
  55201. * @param other the particle to copy the information to.
  55202. */
  55203. Particle.prototype.copyTo = function (other) {
  55204. other.position.copyFrom(this.position);
  55205. if (this._initialDirection) {
  55206. if (other._initialDirection) {
  55207. other._initialDirection.copyFrom(this._initialDirection);
  55208. }
  55209. else {
  55210. other._initialDirection = this._initialDirection.clone();
  55211. }
  55212. }
  55213. else {
  55214. other._initialDirection = null;
  55215. }
  55216. other.direction.copyFrom(this.direction);
  55217. other.color.copyFrom(this.color);
  55218. other.colorStep.copyFrom(this.colorStep);
  55219. other.lifeTime = this.lifeTime;
  55220. other.age = this.age;
  55221. other._randomCellOffset = undefined;
  55222. other.size = this.size;
  55223. other.scale.copyFrom(this.scale);
  55224. other.angle = this.angle;
  55225. other.angularSpeed = this.angularSpeed;
  55226. other.particleSystem = this.particleSystem;
  55227. other.cellIndex = this.cellIndex;
  55228. other.id = this.id;
  55229. other._attachedSubEmitters = this._attachedSubEmitters;
  55230. if (this._currentColorGradient) {
  55231. other._currentColorGradient = this._currentColorGradient;
  55232. other._currentColor1.copyFrom(this._currentColor1);
  55233. other._currentColor2.copyFrom(this._currentColor2);
  55234. }
  55235. if (this._currentSizeGradient) {
  55236. other._currentSizeGradient = this._currentSizeGradient;
  55237. other._currentSize1 = this._currentSize1;
  55238. other._currentSize2 = this._currentSize2;
  55239. }
  55240. if (this._currentAngularSpeedGradient) {
  55241. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55242. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55243. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55244. }
  55245. if (this._currentVelocityGradient) {
  55246. other._currentVelocityGradient = this._currentVelocityGradient;
  55247. other._currentVelocity1 = this._currentVelocity1;
  55248. other._currentVelocity2 = this._currentVelocity2;
  55249. }
  55250. if (this._currentLimitVelocityGradient) {
  55251. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55252. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55253. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55254. }
  55255. if (this._currentDragGradient) {
  55256. other._currentDragGradient = this._currentDragGradient;
  55257. other._currentDrag1 = this._currentDrag1;
  55258. other._currentDrag2 = this._currentDrag2;
  55259. }
  55260. if (this.particleSystem.isAnimationSheetEnabled) {
  55261. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55262. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55263. }
  55264. if (this.particleSystem.useRampGradients) {
  55265. other.remapData.copyFrom(this.remapData);
  55266. }
  55267. if (this._randomNoiseCoordinates1) {
  55268. if (other._randomNoiseCoordinates1) {
  55269. other._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  55270. other._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  55271. }
  55272. else {
  55273. other._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  55274. other._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  55275. }
  55276. }
  55277. };
  55278. Particle._Count = 0;
  55279. return Particle;
  55280. }());
  55281. BABYLON.Particle = Particle;
  55282. })(BABYLON || (BABYLON = {}));
  55283. //# sourceMappingURL=babylon.particle.js.map
  55284. var BABYLON;
  55285. (function (BABYLON) {
  55286. /**
  55287. * This represents the base class for particle system in Babylon.
  55288. * 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.
  55289. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55290. * @example https://doc.babylonjs.com/babylon101/particles
  55291. */
  55292. var BaseParticleSystem = /** @class */ (function () {
  55293. /**
  55294. * Instantiates a particle system.
  55295. * 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.
  55296. * @param name The name of the particle system
  55297. */
  55298. function BaseParticleSystem(name) {
  55299. /**
  55300. * List of animations used by the particle system.
  55301. */
  55302. this.animations = [];
  55303. /**
  55304. * The rendering group used by the Particle system to chose when to render.
  55305. */
  55306. this.renderingGroupId = 0;
  55307. /**
  55308. * The emitter represents the Mesh or position we are attaching the particle system to.
  55309. */
  55310. this.emitter = null;
  55311. /**
  55312. * The maximum number of particles to emit per frame
  55313. */
  55314. this.emitRate = 10;
  55315. /**
  55316. * If you want to launch only a few particles at once, that can be done, as well.
  55317. */
  55318. this.manualEmitCount = -1;
  55319. /**
  55320. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55321. */
  55322. this.updateSpeed = 0.01;
  55323. /**
  55324. * The amount of time the particle system is running (depends of the overall update speed).
  55325. */
  55326. this.targetStopDuration = 0;
  55327. /**
  55328. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55329. */
  55330. this.disposeOnStop = false;
  55331. /**
  55332. * Minimum power of emitting particles.
  55333. */
  55334. this.minEmitPower = 1;
  55335. /**
  55336. * Maximum power of emitting particles.
  55337. */
  55338. this.maxEmitPower = 1;
  55339. /**
  55340. * Minimum life time of emitting particles.
  55341. */
  55342. this.minLifeTime = 1;
  55343. /**
  55344. * Maximum life time of emitting particles.
  55345. */
  55346. this.maxLifeTime = 1;
  55347. /**
  55348. * Minimum Size of emitting particles.
  55349. */
  55350. this.minSize = 1;
  55351. /**
  55352. * Maximum Size of emitting particles.
  55353. */
  55354. this.maxSize = 1;
  55355. /**
  55356. * Minimum scale of emitting particles on X axis.
  55357. */
  55358. this.minScaleX = 1;
  55359. /**
  55360. * Maximum scale of emitting particles on X axis.
  55361. */
  55362. this.maxScaleX = 1;
  55363. /**
  55364. * Minimum scale of emitting particles on Y axis.
  55365. */
  55366. this.minScaleY = 1;
  55367. /**
  55368. * Maximum scale of emitting particles on Y axis.
  55369. */
  55370. this.maxScaleY = 1;
  55371. /**
  55372. * Gets or sets the minimal initial rotation in radians.
  55373. */
  55374. this.minInitialRotation = 0;
  55375. /**
  55376. * Gets or sets the maximal initial rotation in radians.
  55377. */
  55378. this.maxInitialRotation = 0;
  55379. /**
  55380. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55381. */
  55382. this.minAngularSpeed = 0;
  55383. /**
  55384. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55385. */
  55386. this.maxAngularSpeed = 0;
  55387. /**
  55388. * The layer mask we are rendering the particles through.
  55389. */
  55390. this.layerMask = 0x0FFFFFFF;
  55391. /**
  55392. * This can help using your own shader to render the particle system.
  55393. * The according effect will be created
  55394. */
  55395. this.customShader = null;
  55396. /**
  55397. * By default particle system starts as soon as they are created. This prevents the
  55398. * automatic start to happen and let you decide when to start emitting particles.
  55399. */
  55400. this.preventAutoStart = false;
  55401. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55402. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55403. /**
  55404. * Callback triggered when the particle animation is ending.
  55405. */
  55406. this.onAnimationEnd = null;
  55407. /**
  55408. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55409. */
  55410. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55411. /**
  55412. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55413. * to override the particles.
  55414. */
  55415. this.forceDepthWrite = false;
  55416. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  55417. this.preWarmCycles = 0;
  55418. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55419. this.preWarmStepOffset = 1;
  55420. /**
  55421. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  55422. */
  55423. this.spriteCellChangeSpeed = 1;
  55424. /**
  55425. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55426. */
  55427. this.startSpriteCellID = 0;
  55428. /**
  55429. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55430. */
  55431. this.endSpriteCellID = 0;
  55432. /**
  55433. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55434. */
  55435. this.spriteCellWidth = 0;
  55436. /**
  55437. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55438. */
  55439. this.spriteCellHeight = 0;
  55440. /**
  55441. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  55442. */
  55443. this.spriteRandomStartCell = false;
  55444. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55445. this.translationPivot = new BABYLON.Vector2(0, 0);
  55446. /**
  55447. * You can use gravity if you want to give an orientation to your particles.
  55448. */
  55449. this.gravity = BABYLON.Vector3.Zero();
  55450. this._colorGradients = null;
  55451. this._sizeGradients = null;
  55452. this._lifeTimeGradients = null;
  55453. this._angularSpeedGradients = null;
  55454. this._velocityGradients = null;
  55455. this._limitVelocityGradients = null;
  55456. this._dragGradients = null;
  55457. this._emitRateGradients = null;
  55458. this._startSizeGradients = null;
  55459. this._rampGradients = null;
  55460. this._colorRemapGradients = null;
  55461. this._alphaRemapGradients = null;
  55462. /**
  55463. * Defines the delay in milliseconds before starting the system (0 by default)
  55464. */
  55465. this.startDelay = 0;
  55466. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55467. this.limitVelocityDamping = 0.4;
  55468. /**
  55469. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55470. */
  55471. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55472. /**
  55473. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55474. */
  55475. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55476. /**
  55477. * Color the particle will have at the end of its lifetime
  55478. */
  55479. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55480. /**
  55481. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55482. */
  55483. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55484. /**
  55485. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55486. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55487. */
  55488. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55489. this._isBillboardBased = true;
  55490. /**
  55491. * Local cache of defines for image processing.
  55492. */
  55493. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55494. this.id = name;
  55495. this.name = name;
  55496. }
  55497. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55498. /**
  55499. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55500. */
  55501. get: function () {
  55502. return this._isAnimationSheetEnabled;
  55503. },
  55504. set: function (value) {
  55505. if (this._isAnimationSheetEnabled == value) {
  55506. return;
  55507. }
  55508. this._isAnimationSheetEnabled = value;
  55509. this._reset();
  55510. },
  55511. enumerable: true,
  55512. configurable: true
  55513. });
  55514. /**
  55515. * Get hosting scene
  55516. * @returns the scene
  55517. */
  55518. BaseParticleSystem.prototype.getScene = function () {
  55519. return this._scene;
  55520. };
  55521. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  55522. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  55523. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  55524. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  55525. };
  55526. /**
  55527. * Gets the current list of drag gradients.
  55528. * You must use addDragGradient and removeDragGradient to udpate this list
  55529. * @returns the list of drag gradients
  55530. */
  55531. BaseParticleSystem.prototype.getDragGradients = function () {
  55532. return this._dragGradients;
  55533. };
  55534. /**
  55535. * Gets the current list of limit velocity gradients.
  55536. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55537. * @returns the list of limit velocity gradients
  55538. */
  55539. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55540. return this._limitVelocityGradients;
  55541. };
  55542. /**
  55543. * Gets the current list of color gradients.
  55544. * You must use addColorGradient and removeColorGradient to udpate this list
  55545. * @returns the list of color gradients
  55546. */
  55547. BaseParticleSystem.prototype.getColorGradients = function () {
  55548. return this._colorGradients;
  55549. };
  55550. /**
  55551. * Gets the current list of size gradients.
  55552. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55553. * @returns the list of size gradients
  55554. */
  55555. BaseParticleSystem.prototype.getSizeGradients = function () {
  55556. return this._sizeGradients;
  55557. };
  55558. /**
  55559. * Gets the current list of color remap gradients.
  55560. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  55561. * @returns the list of color remap gradients
  55562. */
  55563. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  55564. return this._colorRemapGradients;
  55565. };
  55566. /**
  55567. * Gets the current list of alpha remap gradients.
  55568. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  55569. * @returns the list of alpha remap gradients
  55570. */
  55571. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  55572. return this._alphaRemapGradients;
  55573. };
  55574. /**
  55575. * Gets the current list of life time gradients.
  55576. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55577. * @returns the list of life time gradients
  55578. */
  55579. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55580. return this._lifeTimeGradients;
  55581. };
  55582. /**
  55583. * Gets the current list of angular speed gradients.
  55584. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55585. * @returns the list of angular speed gradients
  55586. */
  55587. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55588. return this._angularSpeedGradients;
  55589. };
  55590. /**
  55591. * Gets the current list of velocity gradients.
  55592. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55593. * @returns the list of velocity gradients
  55594. */
  55595. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55596. return this._velocityGradients;
  55597. };
  55598. /**
  55599. * Gets the current list of start size gradients.
  55600. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  55601. * @returns the list of start size gradients
  55602. */
  55603. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  55604. return this._startSizeGradients;
  55605. };
  55606. /**
  55607. * Gets the current list of emit rate gradients.
  55608. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  55609. * @returns the list of emit rate gradients
  55610. */
  55611. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  55612. return this._emitRateGradients;
  55613. };
  55614. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55615. /**
  55616. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55617. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55618. */
  55619. get: function () {
  55620. if (this.particleEmitterType.direction1) {
  55621. return this.particleEmitterType.direction1;
  55622. }
  55623. return BABYLON.Vector3.Zero();
  55624. },
  55625. set: function (value) {
  55626. if (this.particleEmitterType.direction1) {
  55627. this.particleEmitterType.direction1 = value;
  55628. }
  55629. },
  55630. enumerable: true,
  55631. configurable: true
  55632. });
  55633. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55634. /**
  55635. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55636. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55637. */
  55638. get: function () {
  55639. if (this.particleEmitterType.direction2) {
  55640. return this.particleEmitterType.direction2;
  55641. }
  55642. return BABYLON.Vector3.Zero();
  55643. },
  55644. set: function (value) {
  55645. if (this.particleEmitterType.direction2) {
  55646. this.particleEmitterType.direction2 = value;
  55647. }
  55648. },
  55649. enumerable: true,
  55650. configurable: true
  55651. });
  55652. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55653. /**
  55654. * 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.
  55655. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55656. */
  55657. get: function () {
  55658. if (this.particleEmitterType.minEmitBox) {
  55659. return this.particleEmitterType.minEmitBox;
  55660. }
  55661. return BABYLON.Vector3.Zero();
  55662. },
  55663. set: function (value) {
  55664. if (this.particleEmitterType.minEmitBox) {
  55665. this.particleEmitterType.minEmitBox = value;
  55666. }
  55667. },
  55668. enumerable: true,
  55669. configurable: true
  55670. });
  55671. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55672. /**
  55673. * 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.
  55674. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55675. */
  55676. get: function () {
  55677. if (this.particleEmitterType.maxEmitBox) {
  55678. return this.particleEmitterType.maxEmitBox;
  55679. }
  55680. return BABYLON.Vector3.Zero();
  55681. },
  55682. set: function (value) {
  55683. if (this.particleEmitterType.maxEmitBox) {
  55684. this.particleEmitterType.maxEmitBox = value;
  55685. }
  55686. },
  55687. enumerable: true,
  55688. configurable: true
  55689. });
  55690. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  55691. /**
  55692. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55693. */
  55694. get: function () {
  55695. return this._isBillboardBased;
  55696. },
  55697. set: function (value) {
  55698. if (this._isBillboardBased === value) {
  55699. return;
  55700. }
  55701. this._isBillboardBased = value;
  55702. this._reset();
  55703. },
  55704. enumerable: true,
  55705. configurable: true
  55706. });
  55707. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  55708. /**
  55709. * Gets the image processing configuration used either in this material.
  55710. */
  55711. get: function () {
  55712. return this._imageProcessingConfiguration;
  55713. },
  55714. /**
  55715. * Sets the Default image processing configuration used either in the this material.
  55716. *
  55717. * If sets to null, the scene one is in use.
  55718. */
  55719. set: function (value) {
  55720. this._attachImageProcessingConfiguration(value);
  55721. },
  55722. enumerable: true,
  55723. configurable: true
  55724. });
  55725. /**
  55726. * Attaches a new image processing configuration to the Standard Material.
  55727. * @param configuration
  55728. */
  55729. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  55730. if (configuration === this._imageProcessingConfiguration) {
  55731. return;
  55732. }
  55733. // Pick the scene configuration if needed.
  55734. if (!configuration) {
  55735. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  55736. }
  55737. else {
  55738. this._imageProcessingConfiguration = configuration;
  55739. }
  55740. };
  55741. /** @hidden */
  55742. BaseParticleSystem.prototype._reset = function () {
  55743. };
  55744. /** @hidden */
  55745. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  55746. if (!gradients) {
  55747. return this;
  55748. }
  55749. var index = 0;
  55750. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  55751. var valueGradient = gradients_1[_i];
  55752. if (valueGradient.gradient === gradient) {
  55753. gradients.splice(index, 1);
  55754. break;
  55755. }
  55756. index++;
  55757. }
  55758. if (texture) {
  55759. texture.dispose();
  55760. }
  55761. return this;
  55762. };
  55763. /**
  55764. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  55765. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55766. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55767. * @returns the emitter
  55768. */
  55769. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  55770. var particleEmitter = new BABYLON.PointParticleEmitter();
  55771. particleEmitter.direction1 = direction1;
  55772. particleEmitter.direction2 = direction2;
  55773. this.particleEmitterType = particleEmitter;
  55774. return particleEmitter;
  55775. };
  55776. /**
  55777. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  55778. * @param radius The radius of the hemisphere to emit from
  55779. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55780. * @returns the emitter
  55781. */
  55782. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  55783. if (radius === void 0) { radius = 1; }
  55784. if (radiusRange === void 0) { radiusRange = 1; }
  55785. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  55786. this.particleEmitterType = particleEmitter;
  55787. return particleEmitter;
  55788. };
  55789. /**
  55790. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  55791. * @param radius The radius of the sphere to emit from
  55792. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55793. * @returns the emitter
  55794. */
  55795. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  55796. if (radius === void 0) { radius = 1; }
  55797. if (radiusRange === void 0) { radiusRange = 1; }
  55798. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  55799. this.particleEmitterType = particleEmitter;
  55800. return particleEmitter;
  55801. };
  55802. /**
  55803. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  55804. * @param radius The radius of the sphere to emit from
  55805. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55806. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55807. * @returns the emitter
  55808. */
  55809. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55810. if (radius === void 0) { radius = 1; }
  55811. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55812. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55813. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55814. this.particleEmitterType = particleEmitter;
  55815. return particleEmitter;
  55816. };
  55817. /**
  55818. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  55819. * @param radius The radius of the emission cylinder
  55820. * @param height The height of the emission cylinder
  55821. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  55822. * @param directionRandomizer How much to randomize the particle direction [0-1]
  55823. * @returns the emitter
  55824. */
  55825. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  55826. if (radius === void 0) { radius = 1; }
  55827. if (height === void 0) { height = 1; }
  55828. if (radiusRange === void 0) { radiusRange = 1; }
  55829. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55830. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  55831. this.particleEmitterType = particleEmitter;
  55832. return particleEmitter;
  55833. };
  55834. /**
  55835. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  55836. * @param radius The radius of the cylinder to emit from
  55837. * @param height The height of the emission cylinder
  55838. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  55839. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  55840. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  55841. * @returns the emitter
  55842. */
  55843. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  55844. if (radius === void 0) { radius = 1; }
  55845. if (height === void 0) { height = 1; }
  55846. if (radiusRange === void 0) { radiusRange = 1; }
  55847. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55848. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55849. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  55850. this.particleEmitterType = particleEmitter;
  55851. return particleEmitter;
  55852. };
  55853. /**
  55854. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  55855. * @param radius The radius of the cone to emit from
  55856. * @param angle The base angle of the cone
  55857. * @returns the emitter
  55858. */
  55859. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55860. if (radius === void 0) { radius = 1; }
  55861. if (angle === void 0) { angle = Math.PI / 4; }
  55862. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55863. this.particleEmitterType = particleEmitter;
  55864. return particleEmitter;
  55865. };
  55866. /**
  55867. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55868. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55869. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55870. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55871. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55872. * @returns the emitter
  55873. */
  55874. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55875. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55876. this.particleEmitterType = particleEmitter;
  55877. this.direction1 = direction1;
  55878. this.direction2 = direction2;
  55879. this.minEmitBox = minEmitBox;
  55880. this.maxEmitBox = maxEmitBox;
  55881. return particleEmitter;
  55882. };
  55883. /**
  55884. * Source color is added to the destination color without alpha affecting the result
  55885. */
  55886. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  55887. /**
  55888. * Blend current color and particle color using particle’s alpha
  55889. */
  55890. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  55891. /**
  55892. * Add current color and particle color multiplied by particle’s alpha
  55893. */
  55894. BaseParticleSystem.BLENDMODE_ADD = 2;
  55895. /**
  55896. * Multiply current color with particle color
  55897. */
  55898. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  55899. /**
  55900. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  55901. */
  55902. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  55903. return BaseParticleSystem;
  55904. }());
  55905. BABYLON.BaseParticleSystem = BaseParticleSystem;
  55906. })(BABYLON || (BABYLON = {}));
  55907. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  55908. var BABYLON;
  55909. (function (BABYLON) {
  55910. /**
  55911. * This represents a particle system in Babylon.
  55912. * 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.
  55913. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55914. * @example https://doc.babylonjs.com/babylon101/particles
  55915. */
  55916. var ParticleSystem = /** @class */ (function (_super) {
  55917. __extends(ParticleSystem, _super);
  55918. /**
  55919. * Instantiates a particle system.
  55920. * 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.
  55921. * @param name The name of the particle system
  55922. * @param capacity The max number of particles alive at the same time
  55923. * @param scene The scene the particle system belongs to
  55924. * @param customEffect a custom effect used to change the way particles are rendered by default
  55925. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55926. * @param epsilon Offset used to render the particles
  55927. */
  55928. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55929. if (customEffect === void 0) { customEffect = null; }
  55930. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55931. if (epsilon === void 0) { epsilon = 0.01; }
  55932. var _this = _super.call(this, name) || this;
  55933. /**
  55934. * @hidden
  55935. */
  55936. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  55937. /**
  55938. * An event triggered when the system is disposed
  55939. */
  55940. _this.onDisposeObservable = new BABYLON.Observable();
  55941. _this._particles = new Array();
  55942. _this._stockParticles = new Array();
  55943. _this._newPartsExcess = 0;
  55944. _this._vertexBuffers = {};
  55945. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55946. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55947. _this._scaledDirection = BABYLON.Vector3.Zero();
  55948. _this._scaledGravity = BABYLON.Vector3.Zero();
  55949. _this._currentRenderId = -1;
  55950. _this._useInstancing = false;
  55951. _this._started = false;
  55952. _this._stopped = false;
  55953. _this._actualFrame = 0;
  55954. /** @hidden */
  55955. _this._currentEmitRate1 = 0;
  55956. /** @hidden */
  55957. _this._currentEmitRate2 = 0;
  55958. /** @hidden */
  55959. _this._currentStartSize1 = 0;
  55960. /** @hidden */
  55961. _this._currentStartSize2 = 0;
  55962. _this._rawTextureWidth = 256;
  55963. _this._useRampGradients = false;
  55964. /**
  55965. * @hidden
  55966. * If the particle systems emitter should be disposed when the particle system is disposed
  55967. */
  55968. _this._disposeEmitterOnDispose = false;
  55969. // start of sub system methods
  55970. /**
  55971. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55972. * Its lifetime will start back at 0.
  55973. */
  55974. _this.recycleParticle = function (particle) {
  55975. // move particle from activeParticle list to stock particles
  55976. var lastParticle = _this._particles.pop();
  55977. if (lastParticle !== particle) {
  55978. lastParticle.copyTo(particle);
  55979. }
  55980. _this._stockParticles.push(lastParticle);
  55981. };
  55982. _this._createParticle = function () {
  55983. var particle;
  55984. if (_this._stockParticles.length !== 0) {
  55985. particle = _this._stockParticles.pop();
  55986. particle._reset();
  55987. }
  55988. else {
  55989. particle = new BABYLON.Particle(_this);
  55990. }
  55991. // Attach emitters
  55992. if (_this._subEmitters && _this._subEmitters.length > 0) {
  55993. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  55994. particle._attachedSubEmitters = [];
  55995. subEmitters.forEach(function (subEmitter) {
  55996. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  55997. var newEmitter = subEmitter.clone();
  55998. particle._attachedSubEmitters.push(newEmitter);
  55999. newEmitter.particleSystem.start();
  56000. }
  56001. });
  56002. }
  56003. return particle;
  56004. };
  56005. _this._emitFromParticle = function (particle) {
  56006. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  56007. return;
  56008. }
  56009. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  56010. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  56011. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  56012. var subSystem = subEmitter.clone();
  56013. ParticleSystem._InheritParticleInfoToSubEmitter(subSystem, particle);
  56014. subSystem.particleSystem._rootParticleSystem = _this;
  56015. _this.activeSubSystems.push(subSystem.particleSystem);
  56016. subSystem.particleSystem.start();
  56017. }
  56018. });
  56019. };
  56020. _this._capacity = capacity;
  56021. _this._epsilon = epsilon;
  56022. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56023. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56024. // Setup the default processing configuration to the scene.
  56025. _this._attachImageProcessingConfiguration(null);
  56026. _this._customEffect = customEffect;
  56027. _this._scene.particleSystems.push(_this);
  56028. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  56029. _this._createIndexBuffer();
  56030. _this._createVertexBuffers();
  56031. // Default emitter type
  56032. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56033. // Update
  56034. _this.updateFunction = function (particles) {
  56035. var noiseTextureSize = null;
  56036. var noiseTextureData = null;
  56037. if (_this.noiseTexture) { // We need to get texture data back to CPU
  56038. noiseTextureSize = _this.noiseTexture.getSize();
  56039. noiseTextureData = (_this.noiseTexture.getContent());
  56040. }
  56041. var _loop_1 = function () {
  56042. particle = particles[index];
  56043. particle.age += _this._scaledUpdateSpeed;
  56044. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56045. _this._emitFromParticle(particle);
  56046. if (particle._attachedSubEmitters) {
  56047. particle._attachedSubEmitters.forEach(function (subEmitter) {
  56048. subEmitter.particleSystem.disposeOnStop = true;
  56049. subEmitter.particleSystem.stop();
  56050. });
  56051. particle._attachedSubEmitters = null;
  56052. }
  56053. _this.recycleParticle(particle);
  56054. index--;
  56055. return "continue";
  56056. }
  56057. else {
  56058. var ratio = particle.age / particle.lifeTime;
  56059. // Color
  56060. if (_this._colorGradients && _this._colorGradients.length > 0) {
  56061. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  56062. if (currentGradient !== particle._currentColorGradient) {
  56063. particle._currentColor1.copyFrom(particle._currentColor2);
  56064. nextGradient.getColorToRef(particle._currentColor2);
  56065. particle._currentColorGradient = currentGradient;
  56066. }
  56067. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  56068. });
  56069. }
  56070. else {
  56071. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56072. particle.color.addInPlace(_this._scaledColorStep);
  56073. if (particle.color.a < 0) {
  56074. particle.color.a = 0;
  56075. }
  56076. }
  56077. // Angular speed
  56078. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  56079. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  56080. if (currentGradient !== particle._currentAngularSpeedGradient) {
  56081. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  56082. particle._currentAngularSpeed2 = nextGradient.getFactor();
  56083. particle._currentAngularSpeedGradient = currentGradient;
  56084. }
  56085. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  56086. });
  56087. }
  56088. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56089. // Direction
  56090. var directionScale_1 = _this._scaledUpdateSpeed;
  56091. /// Velocity
  56092. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  56093. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  56094. if (currentGradient !== particle._currentVelocityGradient) {
  56095. particle._currentVelocity1 = particle._currentVelocity2;
  56096. particle._currentVelocity2 = nextGradient.getFactor();
  56097. particle._currentVelocityGradient = currentGradient;
  56098. }
  56099. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  56100. });
  56101. }
  56102. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  56103. /// Limit velocity
  56104. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  56105. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  56106. if (currentGradient !== particle._currentLimitVelocityGradient) {
  56107. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  56108. particle._currentLimitVelocity2 = nextGradient.getFactor();
  56109. particle._currentLimitVelocityGradient = currentGradient;
  56110. }
  56111. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  56112. var currentVelocity = particle.direction.length();
  56113. if (currentVelocity > limitVelocity) {
  56114. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  56115. }
  56116. });
  56117. }
  56118. /// Drag
  56119. if (_this._dragGradients && _this._dragGradients.length > 0) {
  56120. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  56121. if (currentGradient !== particle._currentDragGradient) {
  56122. particle._currentDrag1 = particle._currentDrag2;
  56123. particle._currentDrag2 = nextGradient.getFactor();
  56124. particle._currentDragGradient = currentGradient;
  56125. }
  56126. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  56127. _this._scaledDirection.scaleInPlace(1.0 - drag);
  56128. });
  56129. }
  56130. particle.position.addInPlace(_this._scaledDirection);
  56131. // Noise
  56132. if (noiseTextureData && noiseTextureSize) {
  56133. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56134. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56135. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56136. var force = BABYLON.Tmp.Vector3[0];
  56137. var scaledForce = BABYLON.Tmp.Vector3[1];
  56138. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  56139. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  56140. particle.direction.addInPlace(scaledForce);
  56141. }
  56142. // Gravity
  56143. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56144. particle.direction.addInPlace(_this._scaledGravity);
  56145. // Size
  56146. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  56147. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  56148. if (currentGradient !== particle._currentSizeGradient) {
  56149. particle._currentSize1 = particle._currentSize2;
  56150. particle._currentSize2 = nextGradient.getFactor();
  56151. particle._currentSizeGradient = currentGradient;
  56152. }
  56153. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  56154. });
  56155. }
  56156. // Remap data
  56157. if (_this._useRampGradients) {
  56158. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  56159. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  56160. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  56161. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  56162. particle.remapData.x = min;
  56163. particle.remapData.y = max - min;
  56164. });
  56165. }
  56166. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  56167. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  56168. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  56169. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  56170. particle.remapData.z = min;
  56171. particle.remapData.w = max - min;
  56172. });
  56173. }
  56174. }
  56175. if (_this._isAnimationSheetEnabled) {
  56176. particle.updateCellIndex();
  56177. }
  56178. // Update the position of the attached sub-emitters to match their attached particle
  56179. if (particle._attachedSubEmitters && particle._attachedSubEmitters.length > 0) {
  56180. particle._attachedSubEmitters.forEach(function (subEmitter) {
  56181. ParticleSystem._InheritParticleInfoToSubEmitter(subEmitter, particle);
  56182. });
  56183. }
  56184. }
  56185. };
  56186. var particle;
  56187. for (var index = 0; index < particles.length; index++) {
  56188. _loop_1();
  56189. }
  56190. };
  56191. return _this;
  56192. }
  56193. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56194. /**
  56195. * Sets a callback that will be triggered when the system is disposed
  56196. */
  56197. set: function (callback) {
  56198. if (this._onDisposeObserver) {
  56199. this.onDisposeObservable.remove(this._onDisposeObserver);
  56200. }
  56201. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56202. },
  56203. enumerable: true,
  56204. configurable: true
  56205. });
  56206. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  56207. /** Gets or sets a boolean indicating that ramp gradients must be used
  56208. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  56209. */
  56210. get: function () {
  56211. return this._useRampGradients;
  56212. },
  56213. set: function (value) {
  56214. if (this._useRampGradients === value) {
  56215. return;
  56216. }
  56217. this._useRampGradients = value;
  56218. this._resetEffect();
  56219. },
  56220. enumerable: true,
  56221. configurable: true
  56222. });
  56223. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56224. //end of Sub-emitter
  56225. /**
  56226. * Gets the current list of active particles
  56227. */
  56228. get: function () {
  56229. return this._particles;
  56230. },
  56231. enumerable: true,
  56232. configurable: true
  56233. });
  56234. /**
  56235. * Returns the string "ParticleSystem"
  56236. * @returns a string containing the class name
  56237. */
  56238. ParticleSystem.prototype.getClassName = function () {
  56239. return "ParticleSystem";
  56240. };
  56241. ParticleSystem._InheritParticleInfoToSubEmitter = function (subEmitter, particle) {
  56242. if (subEmitter.particleSystem.emitter.position) {
  56243. var emitterMesh = subEmitter.particleSystem.emitter;
  56244. emitterMesh.position.copyFrom(particle.position);
  56245. if (subEmitter.inheritDirection) {
  56246. emitterMesh.position.subtractToRef(particle.direction, BABYLON.Tmp.Vector3[0]);
  56247. // Look at using Y as forward
  56248. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  56249. }
  56250. }
  56251. else {
  56252. var emitterPosition = subEmitter.particleSystem.emitter;
  56253. emitterPosition.copyFrom(particle.position);
  56254. }
  56255. // Set inheritedVelocityOffset to be used when new particles are created
  56256. particle.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  56257. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  56258. };
  56259. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56260. var newGradient = new BABYLON.FactorGradient();
  56261. newGradient.gradient = gradient;
  56262. newGradient.factor1 = factor;
  56263. newGradient.factor2 = factor2;
  56264. factorGradients.push(newGradient);
  56265. factorGradients.sort(function (a, b) {
  56266. if (a.gradient < b.gradient) {
  56267. return -1;
  56268. }
  56269. else if (a.gradient > b.gradient) {
  56270. return 1;
  56271. }
  56272. return 0;
  56273. });
  56274. };
  56275. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56276. if (!factorGradients) {
  56277. return;
  56278. }
  56279. var index = 0;
  56280. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56281. var factorGradient = factorGradients_1[_i];
  56282. if (factorGradient.gradient === gradient) {
  56283. factorGradients.splice(index, 1);
  56284. break;
  56285. }
  56286. index++;
  56287. }
  56288. };
  56289. /**
  56290. * Adds a new life time gradient
  56291. * @param gradient defines the gradient to use (between 0 and 1)
  56292. * @param factor defines the life time factor to affect to the specified gradient
  56293. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56294. * @returns the current particle system
  56295. */
  56296. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56297. if (!this._lifeTimeGradients) {
  56298. this._lifeTimeGradients = [];
  56299. }
  56300. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56301. return this;
  56302. };
  56303. /**
  56304. * Remove a specific life time gradient
  56305. * @param gradient defines the gradient to remove
  56306. * @returns the current particle system
  56307. */
  56308. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56309. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56310. return this;
  56311. };
  56312. /**
  56313. * Adds a new size gradient
  56314. * @param gradient defines the gradient to use (between 0 and 1)
  56315. * @param factor defines the size factor to affect to the specified gradient
  56316. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56317. * @returns the current particle system
  56318. */
  56319. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56320. if (!this._sizeGradients) {
  56321. this._sizeGradients = [];
  56322. }
  56323. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56324. return this;
  56325. };
  56326. /**
  56327. * Remove a specific size gradient
  56328. * @param gradient defines the gradient to remove
  56329. * @returns the current particle system
  56330. */
  56331. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56332. this._removeFactorGradient(this._sizeGradients, gradient);
  56333. return this;
  56334. };
  56335. /**
  56336. * Adds a new color remap gradient
  56337. * @param gradient defines the gradient to use (between 0 and 1)
  56338. * @param min defines the color remap minimal range
  56339. * @param max defines the color remap maximal range
  56340. * @returns the current particle system
  56341. */
  56342. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  56343. if (!this._colorRemapGradients) {
  56344. this._colorRemapGradients = [];
  56345. }
  56346. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  56347. return this;
  56348. };
  56349. /**
  56350. * Remove a specific color remap gradient
  56351. * @param gradient defines the gradient to remove
  56352. * @returns the current particle system
  56353. */
  56354. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  56355. this._removeFactorGradient(this._colorRemapGradients, gradient);
  56356. return this;
  56357. };
  56358. /**
  56359. * Adds a new alpha remap gradient
  56360. * @param gradient defines the gradient to use (between 0 and 1)
  56361. * @param min defines the alpha remap minimal range
  56362. * @param max defines the alpha remap maximal range
  56363. * @returns the current particle system
  56364. */
  56365. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  56366. if (!this._alphaRemapGradients) {
  56367. this._alphaRemapGradients = [];
  56368. }
  56369. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  56370. return this;
  56371. };
  56372. /**
  56373. * Remove a specific alpha remap gradient
  56374. * @param gradient defines the gradient to remove
  56375. * @returns the current particle system
  56376. */
  56377. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  56378. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  56379. return this;
  56380. };
  56381. /**
  56382. * Adds a new angular speed gradient
  56383. * @param gradient defines the gradient to use (between 0 and 1)
  56384. * @param factor defines the angular speed to affect to the specified gradient
  56385. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56386. * @returns the current particle system
  56387. */
  56388. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56389. if (!this._angularSpeedGradients) {
  56390. this._angularSpeedGradients = [];
  56391. }
  56392. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56393. return this;
  56394. };
  56395. /**
  56396. * Remove a specific angular speed gradient
  56397. * @param gradient defines the gradient to remove
  56398. * @returns the current particle system
  56399. */
  56400. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56401. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56402. return this;
  56403. };
  56404. /**
  56405. * Adds a new velocity gradient
  56406. * @param gradient defines the gradient to use (between 0 and 1)
  56407. * @param factor defines the velocity to affect to the specified gradient
  56408. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56409. * @returns the current particle system
  56410. */
  56411. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56412. if (!this._velocityGradients) {
  56413. this._velocityGradients = [];
  56414. }
  56415. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56416. return this;
  56417. };
  56418. /**
  56419. * Remove a specific velocity gradient
  56420. * @param gradient defines the gradient to remove
  56421. * @returns the current particle system
  56422. */
  56423. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56424. this._removeFactorGradient(this._velocityGradients, gradient);
  56425. return this;
  56426. };
  56427. /**
  56428. * Adds a new limit velocity gradient
  56429. * @param gradient defines the gradient to use (between 0 and 1)
  56430. * @param factor defines the limit velocity value to affect to the specified gradient
  56431. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56432. * @returns the current particle system
  56433. */
  56434. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56435. if (!this._limitVelocityGradients) {
  56436. this._limitVelocityGradients = [];
  56437. }
  56438. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56439. return this;
  56440. };
  56441. /**
  56442. * Remove a specific limit velocity gradient
  56443. * @param gradient defines the gradient to remove
  56444. * @returns the current particle system
  56445. */
  56446. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56447. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56448. return this;
  56449. };
  56450. /**
  56451. * Adds a new drag gradient
  56452. * @param gradient defines the gradient to use (between 0 and 1)
  56453. * @param factor defines the drag value to affect to the specified gradient
  56454. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56455. * @returns the current particle system
  56456. */
  56457. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  56458. if (!this._dragGradients) {
  56459. this._dragGradients = [];
  56460. }
  56461. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  56462. return this;
  56463. };
  56464. /**
  56465. * Remove a specific drag gradient
  56466. * @param gradient defines the gradient to remove
  56467. * @returns the current particle system
  56468. */
  56469. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  56470. this._removeFactorGradient(this._dragGradients, gradient);
  56471. return this;
  56472. };
  56473. /**
  56474. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  56475. * @param gradient defines the gradient to use (between 0 and 1)
  56476. * @param factor defines the emit rate value to affect to the specified gradient
  56477. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56478. * @returns the current particle system
  56479. */
  56480. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  56481. if (!this._emitRateGradients) {
  56482. this._emitRateGradients = [];
  56483. }
  56484. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  56485. if (!this._currentEmitRateGradient) {
  56486. this._currentEmitRateGradient = this._emitRateGradients[0];
  56487. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  56488. this._currentEmitRate2 = this._currentEmitRate1;
  56489. }
  56490. if (this._emitRateGradients.length === 2) {
  56491. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  56492. }
  56493. return this;
  56494. };
  56495. /**
  56496. * Remove a specific emit rate gradient
  56497. * @param gradient defines the gradient to remove
  56498. * @returns the current particle system
  56499. */
  56500. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  56501. this._removeFactorGradient(this._emitRateGradients, gradient);
  56502. return this;
  56503. };
  56504. /**
  56505. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  56506. * @param gradient defines the gradient to use (between 0 and 1)
  56507. * @param factor defines the start size value to affect to the specified gradient
  56508. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56509. * @returns the current particle system
  56510. */
  56511. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  56512. if (!this._startSizeGradients) {
  56513. this._startSizeGradients = [];
  56514. }
  56515. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  56516. if (!this._currentStartSizeGradient) {
  56517. this._currentStartSizeGradient = this._startSizeGradients[0];
  56518. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  56519. this._currentStartSize2 = this._currentStartSize1;
  56520. }
  56521. if (this._startSizeGradients.length === 2) {
  56522. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  56523. }
  56524. return this;
  56525. };
  56526. /**
  56527. * Remove a specific start size gradient
  56528. * @param gradient defines the gradient to remove
  56529. * @returns the current particle system
  56530. */
  56531. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  56532. this._removeFactorGradient(this._emitRateGradients, gradient);
  56533. return this;
  56534. };
  56535. ParticleSystem.prototype._createRampGradientTexture = function () {
  56536. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  56537. return;
  56538. }
  56539. var data = new Uint8Array(this._rawTextureWidth * 4);
  56540. var tmpColor = BABYLON.Tmp.Color3[0];
  56541. for (var x = 0; x < this._rawTextureWidth; x++) {
  56542. var ratio = x / this._rawTextureWidth;
  56543. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  56544. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  56545. data[x * 4] = tmpColor.r * 255;
  56546. data[x * 4 + 1] = tmpColor.g * 255;
  56547. data[x * 4 + 2] = tmpColor.b * 255;
  56548. data[x * 4 + 3] = 255;
  56549. });
  56550. }
  56551. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  56552. };
  56553. /**
  56554. * Gets the current list of ramp gradients.
  56555. * You must use addRampGradient and removeRampGradient to udpate this list
  56556. * @returns the list of ramp gradients
  56557. */
  56558. ParticleSystem.prototype.getRampGradients = function () {
  56559. return this._rampGradients;
  56560. };
  56561. /**
  56562. * Adds a new ramp gradient used to remap particle colors
  56563. * @param gradient defines the gradient to use (between 0 and 1)
  56564. * @param color defines the color to affect to the specified gradient
  56565. * @returns the current particle system
  56566. */
  56567. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  56568. if (!this._rampGradients) {
  56569. this._rampGradients = [];
  56570. }
  56571. var rampGradient = new BABYLON.Color3Gradient();
  56572. rampGradient.gradient = gradient;
  56573. rampGradient.color = color;
  56574. this._rampGradients.push(rampGradient);
  56575. this._rampGradients.sort(function (a, b) {
  56576. if (a.gradient < b.gradient) {
  56577. return -1;
  56578. }
  56579. else if (a.gradient > b.gradient) {
  56580. return 1;
  56581. }
  56582. return 0;
  56583. });
  56584. if (this._rampGradientsTexture) {
  56585. this._rampGradientsTexture.dispose();
  56586. this._rampGradientsTexture = null;
  56587. }
  56588. this._createRampGradientTexture();
  56589. return this;
  56590. };
  56591. /**
  56592. * Remove a specific ramp gradient
  56593. * @param gradient defines the gradient to remove
  56594. * @returns the current particle system
  56595. */
  56596. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  56597. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  56598. this._rampGradientsTexture = null;
  56599. if (this._rampGradients && this._rampGradients.length > 0) {
  56600. this._createRampGradientTexture();
  56601. }
  56602. return this;
  56603. };
  56604. /**
  56605. * Adds a new color gradient
  56606. * @param gradient defines the gradient to use (between 0 and 1)
  56607. * @param color defines the color to affect to the specified gradient
  56608. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56609. */
  56610. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56611. if (!this._colorGradients) {
  56612. this._colorGradients = [];
  56613. }
  56614. var colorGradient = new BABYLON.ColorGradient();
  56615. colorGradient.gradient = gradient;
  56616. colorGradient.color1 = color;
  56617. colorGradient.color2 = color2;
  56618. this._colorGradients.push(colorGradient);
  56619. this._colorGradients.sort(function (a, b) {
  56620. if (a.gradient < b.gradient) {
  56621. return -1;
  56622. }
  56623. else if (a.gradient > b.gradient) {
  56624. return 1;
  56625. }
  56626. return 0;
  56627. });
  56628. return this;
  56629. };
  56630. /**
  56631. * Remove a specific color gradient
  56632. * @param gradient defines the gradient to remove
  56633. */
  56634. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56635. if (!this._colorGradients) {
  56636. return this;
  56637. }
  56638. var index = 0;
  56639. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56640. var colorGradient = _a[_i];
  56641. if (colorGradient.gradient === gradient) {
  56642. this._colorGradients.splice(index, 1);
  56643. break;
  56644. }
  56645. index++;
  56646. }
  56647. return this;
  56648. };
  56649. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56650. u = Math.abs(u) * 0.5 + 0.5;
  56651. v = Math.abs(v) * 0.5 + 0.5;
  56652. var wrappedU = ((u * width) % width) | 0;
  56653. var wrappedV = ((v * height) % height) | 0;
  56654. var position = (wrappedU + wrappedV * width) * 4;
  56655. return pixels[position] / 255;
  56656. };
  56657. ParticleSystem.prototype._reset = function () {
  56658. this._resetEffect();
  56659. };
  56660. ParticleSystem.prototype._resetEffect = function () {
  56661. if (this._vertexBuffer) {
  56662. this._vertexBuffer.dispose();
  56663. this._vertexBuffer = null;
  56664. }
  56665. if (this._spriteBuffer) {
  56666. this._spriteBuffer.dispose();
  56667. this._spriteBuffer = null;
  56668. }
  56669. this._createVertexBuffers();
  56670. };
  56671. ParticleSystem.prototype._createVertexBuffers = function () {
  56672. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56673. if (this._isAnimationSheetEnabled) {
  56674. this._vertexBufferSize += 1;
  56675. }
  56676. if (!this._isBillboardBased) {
  56677. this._vertexBufferSize += 3;
  56678. }
  56679. if (this._useRampGradients) {
  56680. this._vertexBufferSize += 4;
  56681. }
  56682. var engine = this._scene.getEngine();
  56683. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56684. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56685. var dataOffset = 0;
  56686. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56687. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56688. dataOffset += 3;
  56689. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56690. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56691. dataOffset += 4;
  56692. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56693. this._vertexBuffers["angle"] = options;
  56694. dataOffset += 1;
  56695. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56696. this._vertexBuffers["size"] = size;
  56697. dataOffset += 2;
  56698. if (this._isAnimationSheetEnabled) {
  56699. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56700. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56701. dataOffset += 1;
  56702. }
  56703. if (!this._isBillboardBased) {
  56704. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56705. this._vertexBuffers["direction"] = directionBuffer;
  56706. dataOffset += 3;
  56707. }
  56708. if (this._useRampGradients) {
  56709. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56710. this._vertexBuffers["remapData"] = rampDataBuffer;
  56711. dataOffset += 4;
  56712. }
  56713. var offsets;
  56714. if (this._useInstancing) {
  56715. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56716. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56717. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56718. }
  56719. else {
  56720. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56721. dataOffset += 2;
  56722. }
  56723. this._vertexBuffers["offset"] = offsets;
  56724. };
  56725. ParticleSystem.prototype._createIndexBuffer = function () {
  56726. if (this._useInstancing) {
  56727. return;
  56728. }
  56729. var indices = [];
  56730. var index = 0;
  56731. for (var count = 0; count < this._capacity; count++) {
  56732. indices.push(index);
  56733. indices.push(index + 1);
  56734. indices.push(index + 2);
  56735. indices.push(index);
  56736. indices.push(index + 2);
  56737. indices.push(index + 3);
  56738. index += 4;
  56739. }
  56740. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56741. };
  56742. /**
  56743. * Gets the maximum number of particles active at the same time.
  56744. * @returns The max number of active particles.
  56745. */
  56746. ParticleSystem.prototype.getCapacity = function () {
  56747. return this._capacity;
  56748. };
  56749. /**
  56750. * Gets whether there are still active particles in the system.
  56751. * @returns True if it is alive, otherwise false.
  56752. */
  56753. ParticleSystem.prototype.isAlive = function () {
  56754. return this._alive;
  56755. };
  56756. /**
  56757. * Gets if the system has been started. (Note: this will still be true after stop is called)
  56758. * @returns True if it has been started, otherwise false.
  56759. */
  56760. ParticleSystem.prototype.isStarted = function () {
  56761. return this._started;
  56762. };
  56763. /**
  56764. * Starts the particle system and begins to emit
  56765. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  56766. */
  56767. ParticleSystem.prototype.start = function (delay) {
  56768. var _this = this;
  56769. if (delay === void 0) { delay = this.startDelay; }
  56770. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  56771. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  56772. }
  56773. if (delay) {
  56774. setTimeout(function () {
  56775. _this.start(0);
  56776. }, delay);
  56777. return;
  56778. }
  56779. // Convert the subEmitters field to the constant type field _subEmitters
  56780. this._subEmitters = new Array();
  56781. if (this.subEmitters) {
  56782. this.subEmitters.forEach(function (subEmitter) {
  56783. if (subEmitter instanceof ParticleSystem) {
  56784. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  56785. }
  56786. else if (subEmitter instanceof BABYLON.SubEmitter) {
  56787. _this._subEmitters.push([subEmitter]);
  56788. }
  56789. else if (subEmitter instanceof Array) {
  56790. _this._subEmitters.push(subEmitter);
  56791. }
  56792. _this._subEmitters[_this._subEmitters.length - 1].forEach(function (se) {
  56793. if (!(se.particleSystem.emitter instanceof BABYLON.AbstractMesh) && se.inheritDirection) {
  56794. BABYLON.Tools.Warn("subEmitter.inheritDirection is not supported with non-mesh emitter type");
  56795. }
  56796. });
  56797. });
  56798. }
  56799. this._started = true;
  56800. this._stopped = false;
  56801. this._actualFrame = 0;
  56802. if (this._subEmitters && this._subEmitters.length != 0) {
  56803. this.activeSubSystems = new Array();
  56804. }
  56805. if (this.preWarmCycles) {
  56806. var noiseTextureAsProcedural_1 = this.noiseTexture;
  56807. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  56808. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  56809. setTimeout(function () {
  56810. for (var index = 0; index < _this.preWarmCycles; index++) {
  56811. _this.animate(true);
  56812. noiseTextureAsProcedural_1.render();
  56813. }
  56814. });
  56815. });
  56816. }
  56817. else {
  56818. for (var index = 0; index < this.preWarmCycles; index++) {
  56819. this.animate(true);
  56820. }
  56821. }
  56822. }
  56823. };
  56824. /**
  56825. * Stops the particle system.
  56826. * @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.
  56827. */
  56828. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56829. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56830. this._stopped = true;
  56831. if (stopSubEmitters) {
  56832. this._stopSubEmitters();
  56833. }
  56834. };
  56835. // animation sheet
  56836. /**
  56837. * Remove all active particles
  56838. */
  56839. ParticleSystem.prototype.reset = function () {
  56840. this._stockParticles = [];
  56841. this._particles = [];
  56842. };
  56843. /**
  56844. * @hidden (for internal use only)
  56845. */
  56846. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56847. var offset = index * this._vertexBufferSize;
  56848. this._vertexData[offset++] = particle.position.x;
  56849. this._vertexData[offset++] = particle.position.y;
  56850. this._vertexData[offset++] = particle.position.z;
  56851. this._vertexData[offset++] = particle.color.r;
  56852. this._vertexData[offset++] = particle.color.g;
  56853. this._vertexData[offset++] = particle.color.b;
  56854. this._vertexData[offset++] = particle.color.a;
  56855. this._vertexData[offset++] = particle.angle;
  56856. this._vertexData[offset++] = particle.scale.x * particle.size;
  56857. this._vertexData[offset++] = particle.scale.y * particle.size;
  56858. if (this._isAnimationSheetEnabled) {
  56859. this._vertexData[offset++] = particle.cellIndex;
  56860. }
  56861. if (!this._isBillboardBased) {
  56862. if (particle._initialDirection) {
  56863. this._vertexData[offset++] = particle._initialDirection.x;
  56864. this._vertexData[offset++] = particle._initialDirection.y;
  56865. this._vertexData[offset++] = particle._initialDirection.z;
  56866. }
  56867. else {
  56868. this._vertexData[offset++] = particle.direction.x;
  56869. this._vertexData[offset++] = particle.direction.y;
  56870. this._vertexData[offset++] = particle.direction.z;
  56871. }
  56872. }
  56873. if (this._useRampGradients) {
  56874. this._vertexData[offset++] = particle.remapData.x;
  56875. this._vertexData[offset++] = particle.remapData.y;
  56876. this._vertexData[offset++] = particle.remapData.z;
  56877. this._vertexData[offset++] = particle.remapData.w;
  56878. }
  56879. if (!this._useInstancing) {
  56880. if (this._isAnimationSheetEnabled) {
  56881. if (offsetX === 0)
  56882. offsetX = this._epsilon;
  56883. else if (offsetX === 1)
  56884. offsetX = 1 - this._epsilon;
  56885. if (offsetY === 0)
  56886. offsetY = this._epsilon;
  56887. else if (offsetY === 1)
  56888. offsetY = 1 - this._epsilon;
  56889. }
  56890. this._vertexData[offset++] = offsetX;
  56891. this._vertexData[offset++] = offsetY;
  56892. }
  56893. };
  56894. ParticleSystem.prototype._stopSubEmitters = function () {
  56895. if (!this.activeSubSystems) {
  56896. return;
  56897. }
  56898. this.activeSubSystems.forEach(function (subSystem) {
  56899. subSystem.stop(true);
  56900. });
  56901. this.activeSubSystems = new Array();
  56902. };
  56903. ParticleSystem.prototype._removeFromRoot = function () {
  56904. if (!this._rootParticleSystem) {
  56905. return;
  56906. }
  56907. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56908. if (index !== -1) {
  56909. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56910. }
  56911. };
  56912. // End of sub system methods
  56913. ParticleSystem.prototype._update = function (newParticles) {
  56914. var _this = this;
  56915. // Update current
  56916. this._alive = this._particles.length > 0;
  56917. if (this.emitter.position) {
  56918. var emitterMesh = this.emitter;
  56919. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  56920. }
  56921. else {
  56922. var emitterPosition = this.emitter;
  56923. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56924. }
  56925. this.updateFunction(this._particles);
  56926. // Add new ones
  56927. var particle;
  56928. var _loop_2 = function () {
  56929. if (this_1._particles.length === this_1._capacity) {
  56930. return "break";
  56931. }
  56932. particle = this_1._createParticle();
  56933. this_1._particles.push(particle);
  56934. // Emitter
  56935. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  56936. if (this_1.startPositionFunction) {
  56937. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56938. }
  56939. else {
  56940. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56941. }
  56942. if (this_1.startDirectionFunction) {
  56943. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56944. }
  56945. else {
  56946. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56947. }
  56948. if (emitPower === 0) {
  56949. if (!particle._initialDirection) {
  56950. particle._initialDirection = particle.direction.clone();
  56951. }
  56952. else {
  56953. particle._initialDirection.copyFrom(particle.direction);
  56954. }
  56955. }
  56956. else {
  56957. particle._initialDirection = null;
  56958. }
  56959. particle.direction.scaleInPlace(emitPower);
  56960. // Life time
  56961. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  56962. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  56963. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  56964. var factorGradient1 = currentGradient;
  56965. var factorGradient2 = nextGradient;
  56966. var lifeTime1 = factorGradient1.getFactor();
  56967. var lifeTime2 = factorGradient2.getFactor();
  56968. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  56969. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  56970. });
  56971. }
  56972. else {
  56973. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  56974. }
  56975. // Size
  56976. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  56977. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  56978. }
  56979. else {
  56980. particle._currentSizeGradient = this_1._sizeGradients[0];
  56981. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  56982. particle.size = particle._currentSize1;
  56983. if (this_1._sizeGradients.length > 1) {
  56984. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  56985. }
  56986. else {
  56987. particle._currentSize2 = particle._currentSize1;
  56988. }
  56989. }
  56990. // Size and scale
  56991. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  56992. // Adjust scale by start size
  56993. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  56994. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  56995. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  56996. if (currentGradient !== _this._currentStartSizeGradient) {
  56997. _this._currentStartSize1 = _this._currentStartSize2;
  56998. _this._currentStartSize2 = nextGradient.getFactor();
  56999. _this._currentStartSizeGradient = currentGradient;
  57000. }
  57001. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  57002. particle.scale.scaleInPlace(value);
  57003. });
  57004. }
  57005. // Angle
  57006. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  57007. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  57008. }
  57009. else {
  57010. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  57011. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  57012. particle._currentAngularSpeed1 = particle.angularSpeed;
  57013. if (this_1._angularSpeedGradients.length > 1) {
  57014. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  57015. }
  57016. else {
  57017. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  57018. }
  57019. }
  57020. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  57021. // Velocity
  57022. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  57023. particle._currentVelocityGradient = this_1._velocityGradients[0];
  57024. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  57025. if (this_1._velocityGradients.length > 1) {
  57026. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  57027. }
  57028. else {
  57029. particle._currentVelocity2 = particle._currentVelocity1;
  57030. }
  57031. }
  57032. // Limit velocity
  57033. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  57034. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  57035. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  57036. if (this_1._limitVelocityGradients.length > 1) {
  57037. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  57038. }
  57039. else {
  57040. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  57041. }
  57042. }
  57043. // Drag
  57044. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  57045. particle._currentDragGradient = this_1._dragGradients[0];
  57046. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  57047. if (this_1._dragGradients.length > 1) {
  57048. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  57049. }
  57050. else {
  57051. particle._currentDrag2 = particle._currentDrag1;
  57052. }
  57053. }
  57054. // Color
  57055. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  57056. step = BABYLON.Scalar.RandomRange(0, 1.0);
  57057. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  57058. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  57059. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  57060. }
  57061. else {
  57062. particle._currentColorGradient = this_1._colorGradients[0];
  57063. particle._currentColorGradient.getColorToRef(particle.color);
  57064. particle._currentColor1.copyFrom(particle.color);
  57065. if (this_1._colorGradients.length > 1) {
  57066. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  57067. }
  57068. else {
  57069. particle._currentColor2.copyFrom(particle.color);
  57070. }
  57071. }
  57072. // Sheet
  57073. if (this_1._isAnimationSheetEnabled) {
  57074. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  57075. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  57076. }
  57077. // Inherited Velocity
  57078. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  57079. // Ramp
  57080. if (this_1._useRampGradients) {
  57081. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  57082. }
  57083. // Noise texture coordinates
  57084. if (this_1.noiseTexture) {
  57085. if (particle._randomNoiseCoordinates1) {
  57086. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  57087. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  57088. }
  57089. else {
  57090. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  57091. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  57092. }
  57093. }
  57094. };
  57095. var this_1 = this, step;
  57096. for (var index = 0; index < newParticles; index++) {
  57097. var state_1 = _loop_2();
  57098. if (state_1 === "break")
  57099. break;
  57100. }
  57101. };
  57102. /** @hidden */
  57103. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  57104. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57105. if (isBillboardBased === void 0) { isBillboardBased = false; }
  57106. if (useRampGradients === void 0) { useRampGradients = false; }
  57107. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  57108. if (isAnimationSheetEnabled) {
  57109. attributeNamesOrOptions.push("cellIndex");
  57110. }
  57111. if (!isBillboardBased) {
  57112. attributeNamesOrOptions.push("direction");
  57113. }
  57114. if (useRampGradients) {
  57115. attributeNamesOrOptions.push("remapData");
  57116. }
  57117. return attributeNamesOrOptions;
  57118. };
  57119. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  57120. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57121. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  57122. if (isAnimationSheetEnabled) {
  57123. effectCreationOption.push("particlesInfos");
  57124. }
  57125. return effectCreationOption;
  57126. };
  57127. ParticleSystem.prototype._getEffect = function (blendMode) {
  57128. if (this._customEffect) {
  57129. return this._customEffect;
  57130. }
  57131. ;
  57132. var defines = [];
  57133. if (this._scene.clipPlane) {
  57134. defines.push("#define CLIPPLANE");
  57135. }
  57136. if (this._scene.clipPlane2) {
  57137. defines.push("#define CLIPPLANE2");
  57138. }
  57139. if (this._scene.clipPlane3) {
  57140. defines.push("#define CLIPPLANE3");
  57141. }
  57142. if (this._scene.clipPlane4) {
  57143. defines.push("#define CLIPPLANE4");
  57144. }
  57145. if (this._isAnimationSheetEnabled) {
  57146. defines.push("#define ANIMATESHEET");
  57147. }
  57148. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  57149. defines.push("#define BLENDMULTIPLYMODE");
  57150. }
  57151. if (this._useRampGradients) {
  57152. defines.push("#define RAMPGRADIENT");
  57153. }
  57154. if (this._isBillboardBased) {
  57155. defines.push("#define BILLBOARD");
  57156. switch (this.billboardMode) {
  57157. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57158. defines.push("#define BILLBOARDY");
  57159. break;
  57160. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57161. default:
  57162. break;
  57163. }
  57164. }
  57165. if (this._imageProcessingConfiguration) {
  57166. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  57167. defines.push(this._imageProcessingConfigurationDefines.toString());
  57168. }
  57169. // Effect
  57170. var join = defines.join("\n");
  57171. if (this._cachedDefines !== join) {
  57172. this._cachedDefines = join;
  57173. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased, this._useRampGradients);
  57174. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  57175. var samplers = ["diffuseSampler", "rampSampler"];
  57176. if (BABYLON.ImageProcessingConfiguration) {
  57177. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  57178. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  57179. }
  57180. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  57181. }
  57182. return this._effect;
  57183. };
  57184. /**
  57185. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57186. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  57187. */
  57188. ParticleSystem.prototype.animate = function (preWarmOnly) {
  57189. var _this = this;
  57190. if (preWarmOnly === void 0) { preWarmOnly = false; }
  57191. if (!this._started)
  57192. return;
  57193. if (!preWarmOnly) {
  57194. // Check
  57195. if (!this.isReady())
  57196. return;
  57197. if (this._currentRenderId === this._scene.getRenderId()) {
  57198. return;
  57199. }
  57200. this._currentRenderId = this._scene.getRenderId();
  57201. }
  57202. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57203. // Determine the number of particles we need to create
  57204. var newParticles;
  57205. if (this.manualEmitCount > -1) {
  57206. newParticles = this.manualEmitCount;
  57207. this._newPartsExcess = 0;
  57208. this.manualEmitCount = 0;
  57209. }
  57210. else {
  57211. var rate_1 = this.emitRate;
  57212. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  57213. var ratio = this._actualFrame / this.targetStopDuration;
  57214. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  57215. if (currentGradient !== _this._currentEmitRateGradient) {
  57216. _this._currentEmitRate1 = _this._currentEmitRate2;
  57217. _this._currentEmitRate2 = nextGradient.getFactor();
  57218. _this._currentEmitRateGradient = currentGradient;
  57219. }
  57220. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  57221. });
  57222. }
  57223. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  57224. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  57225. }
  57226. if (this._newPartsExcess > 1.0) {
  57227. newParticles += this._newPartsExcess >> 0;
  57228. this._newPartsExcess -= this._newPartsExcess >> 0;
  57229. }
  57230. this._alive = false;
  57231. if (!this._stopped) {
  57232. this._actualFrame += this._scaledUpdateSpeed;
  57233. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  57234. this.stop();
  57235. }
  57236. else {
  57237. newParticles = 0;
  57238. }
  57239. this._update(newParticles);
  57240. // Stopped?
  57241. if (this._stopped) {
  57242. if (!this._alive) {
  57243. this._started = false;
  57244. if (this.onAnimationEnd) {
  57245. this.onAnimationEnd();
  57246. }
  57247. if (this.disposeOnStop) {
  57248. this._scene._toBeDisposed.push(this);
  57249. }
  57250. }
  57251. }
  57252. if (!preWarmOnly) {
  57253. // Update VBO
  57254. var offset = 0;
  57255. for (var index = 0; index < this._particles.length; index++) {
  57256. var particle = this._particles[index];
  57257. this._appendParticleVertices(offset, particle);
  57258. offset += this._useInstancing ? 1 : 4;
  57259. }
  57260. if (this._vertexBuffer) {
  57261. this._vertexBuffer.update(this._vertexData);
  57262. }
  57263. }
  57264. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  57265. this.stop();
  57266. }
  57267. };
  57268. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  57269. this._appendParticleVertex(offset++, particle, 0, 0);
  57270. if (!this._useInstancing) {
  57271. this._appendParticleVertex(offset++, particle, 1, 0);
  57272. this._appendParticleVertex(offset++, particle, 1, 1);
  57273. this._appendParticleVertex(offset++, particle, 0, 1);
  57274. }
  57275. };
  57276. /**
  57277. * Rebuilds the particle system.
  57278. */
  57279. ParticleSystem.prototype.rebuild = function () {
  57280. this._createIndexBuffer();
  57281. if (this._vertexBuffer) {
  57282. this._vertexBuffer._rebuild();
  57283. }
  57284. };
  57285. /**
  57286. * Is this system ready to be used/rendered
  57287. * @return true if the system is ready
  57288. */
  57289. ParticleSystem.prototype.isReady = function () {
  57290. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57291. return false;
  57292. }
  57293. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  57294. if (!this._getEffect(this.blendMode).isReady()) {
  57295. return false;
  57296. }
  57297. }
  57298. else {
  57299. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  57300. return false;
  57301. }
  57302. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  57303. return false;
  57304. }
  57305. }
  57306. return true;
  57307. };
  57308. ParticleSystem.prototype._render = function (blendMode) {
  57309. var effect = this._getEffect(blendMode);
  57310. var engine = this._scene.getEngine();
  57311. // Render
  57312. engine.enableEffect(effect);
  57313. var viewMatrix = this._scene.getViewMatrix();
  57314. effect.setTexture("diffuseSampler", this.particleTexture);
  57315. effect.setMatrix("view", viewMatrix);
  57316. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57317. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57318. var baseSize = this.particleTexture.getBaseSize();
  57319. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57320. }
  57321. effect.setVector2("translationPivot", this.translationPivot);
  57322. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57323. if (this._isBillboardBased) {
  57324. var camera = this._scene.activeCamera;
  57325. effect.setVector3("eyePosition", camera.globalPosition);
  57326. }
  57327. if (this._rampGradientsTexture) {
  57328. effect.setTexture("rampSampler", this._rampGradientsTexture);
  57329. }
  57330. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  57331. var invView = viewMatrix.clone();
  57332. invView.invert();
  57333. effect.setMatrix("invView", invView);
  57334. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  57335. }
  57336. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57337. // image processing
  57338. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  57339. this._imageProcessingConfiguration.bind(effect);
  57340. }
  57341. // Draw order
  57342. switch (blendMode) {
  57343. case ParticleSystem.BLENDMODE_ADD:
  57344. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57345. break;
  57346. case ParticleSystem.BLENDMODE_ONEONE:
  57347. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57348. break;
  57349. case ParticleSystem.BLENDMODE_STANDARD:
  57350. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57351. break;
  57352. case ParticleSystem.BLENDMODE_MULTIPLY:
  57353. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  57354. break;
  57355. }
  57356. if (this._useInstancing) {
  57357. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  57358. }
  57359. else {
  57360. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57361. }
  57362. return this._particles.length;
  57363. };
  57364. /**
  57365. * Renders the particle system in its current state.
  57366. * @returns the current number of particles
  57367. */
  57368. ParticleSystem.prototype.render = function () {
  57369. // Check
  57370. if (!this.isReady() || !this._particles.length) {
  57371. return 0;
  57372. }
  57373. var engine = this._scene.getEngine();
  57374. engine.setState(false);
  57375. if (this.forceDepthWrite) {
  57376. engine.setDepthWrite(true);
  57377. }
  57378. var outparticles = 0;
  57379. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  57380. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  57381. }
  57382. outparticles = this._render(this.blendMode);
  57383. engine.unbindInstanceAttributes();
  57384. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57385. return outparticles;
  57386. };
  57387. /**
  57388. * Disposes the particle system and free the associated resources
  57389. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57390. */
  57391. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57392. if (disposeTexture === void 0) { disposeTexture = true; }
  57393. if (this._vertexBuffer) {
  57394. this._vertexBuffer.dispose();
  57395. this._vertexBuffer = null;
  57396. }
  57397. if (this._spriteBuffer) {
  57398. this._spriteBuffer.dispose();
  57399. this._spriteBuffer = null;
  57400. }
  57401. if (this._indexBuffer) {
  57402. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57403. this._indexBuffer = null;
  57404. }
  57405. if (disposeTexture && this.particleTexture) {
  57406. this.particleTexture.dispose();
  57407. this.particleTexture = null;
  57408. }
  57409. if (disposeTexture && this.noiseTexture) {
  57410. this.noiseTexture.dispose();
  57411. this.noiseTexture = null;
  57412. }
  57413. if (this._rampGradientsTexture) {
  57414. this._rampGradientsTexture.dispose();
  57415. this._rampGradientsTexture = null;
  57416. }
  57417. this._removeFromRoot();
  57418. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  57419. this.emitter.dispose(true);
  57420. }
  57421. // Remove from scene
  57422. var index = this._scene.particleSystems.indexOf(this);
  57423. if (index > -1) {
  57424. this._scene.particleSystems.splice(index, 1);
  57425. }
  57426. // Callback
  57427. this.onDisposeObservable.notifyObservers(this);
  57428. this.onDisposeObservable.clear();
  57429. };
  57430. // Clone
  57431. /**
  57432. * Clones the particle system.
  57433. * @param name The name of the cloned object
  57434. * @param newEmitter The new emitter to use
  57435. * @returns the cloned particle system
  57436. */
  57437. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57438. var custom = null;
  57439. var program = null;
  57440. if (this.customShader != null) {
  57441. program = this.customShader;
  57442. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57443. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57444. }
  57445. else if (this._customEffect) {
  57446. custom = this._customEffect;
  57447. }
  57448. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57449. result.customShader = program;
  57450. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  57451. if (newEmitter === undefined) {
  57452. newEmitter = this.emitter;
  57453. }
  57454. result.noiseTexture = this.noiseTexture;
  57455. result.emitter = newEmitter;
  57456. if (this.particleTexture) {
  57457. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57458. }
  57459. // Clone gradients
  57460. if (this._colorGradients) {
  57461. this._colorGradients.forEach(function (v) {
  57462. result.addColorGradient(v.gradient, v.color1, v.color2);
  57463. });
  57464. }
  57465. if (this._dragGradients) {
  57466. this._dragGradients.forEach(function (v) {
  57467. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  57468. });
  57469. }
  57470. if (this._angularSpeedGradients) {
  57471. this._angularSpeedGradients.forEach(function (v) {
  57472. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  57473. });
  57474. }
  57475. if (this._emitRateGradients) {
  57476. this._emitRateGradients.forEach(function (v) {
  57477. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  57478. });
  57479. }
  57480. if (this._lifeTimeGradients) {
  57481. this._lifeTimeGradients.forEach(function (v) {
  57482. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  57483. });
  57484. }
  57485. if (this._limitVelocityGradients) {
  57486. this._limitVelocityGradients.forEach(function (v) {
  57487. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  57488. });
  57489. }
  57490. if (this._sizeGradients) {
  57491. this._sizeGradients.forEach(function (v) {
  57492. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  57493. });
  57494. }
  57495. if (this._startSizeGradients) {
  57496. this._startSizeGradients.forEach(function (v) {
  57497. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  57498. });
  57499. }
  57500. if (this._velocityGradients) {
  57501. this._velocityGradients.forEach(function (v) {
  57502. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  57503. });
  57504. }
  57505. if (this._rampGradients) {
  57506. this._rampGradients.forEach(function (v) {
  57507. result.addRampGradient(v.gradient, v.color);
  57508. });
  57509. }
  57510. if (this._colorRemapGradients) {
  57511. this._colorRemapGradients.forEach(function (v) {
  57512. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  57513. });
  57514. }
  57515. if (this._alphaRemapGradients) {
  57516. this._alphaRemapGradients.forEach(function (v) {
  57517. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  57518. });
  57519. }
  57520. if (!this.preventAutoStart) {
  57521. result.start();
  57522. }
  57523. return result;
  57524. };
  57525. /**
  57526. * Serializes the particle system to a JSON object.
  57527. * @returns the JSON object
  57528. */
  57529. ParticleSystem.prototype.serialize = function () {
  57530. var serializationObject = {};
  57531. ParticleSystem._Serialize(serializationObject, this);
  57532. serializationObject.textureMask = this.textureMask.asArray();
  57533. serializationObject.customShader = this.customShader;
  57534. serializationObject.preventAutoStart = this.preventAutoStart;
  57535. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57536. return serializationObject;
  57537. };
  57538. /** @hidden */
  57539. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  57540. serializationObject.name = particleSystem.name;
  57541. serializationObject.id = particleSystem.id;
  57542. serializationObject.capacity = particleSystem.getCapacity();
  57543. // Emitter
  57544. if (particleSystem.emitter.position) {
  57545. var emitterMesh = particleSystem.emitter;
  57546. serializationObject.emitterId = emitterMesh.id;
  57547. }
  57548. else {
  57549. var emitterPosition = particleSystem.emitter;
  57550. serializationObject.emitter = emitterPosition.asArray();
  57551. }
  57552. // Emitter
  57553. if (particleSystem.particleEmitterType) {
  57554. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  57555. }
  57556. if (particleSystem.particleTexture) {
  57557. serializationObject.textureName = particleSystem.particleTexture.name;
  57558. }
  57559. // Animations
  57560. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  57561. // Particle system
  57562. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  57563. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  57564. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  57565. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  57566. serializationObject.minSize = particleSystem.minSize;
  57567. serializationObject.maxSize = particleSystem.maxSize;
  57568. serializationObject.minScaleX = particleSystem.minScaleX;
  57569. serializationObject.maxScaleX = particleSystem.maxScaleX;
  57570. serializationObject.minScaleY = particleSystem.minScaleY;
  57571. serializationObject.maxScaleY = particleSystem.maxScaleY;
  57572. serializationObject.minEmitPower = particleSystem.minEmitPower;
  57573. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  57574. serializationObject.minLifeTime = particleSystem.minLifeTime;
  57575. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  57576. serializationObject.emitRate = particleSystem.emitRate;
  57577. serializationObject.gravity = particleSystem.gravity.asArray();
  57578. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  57579. serializationObject.color1 = particleSystem.color1.asArray();
  57580. serializationObject.color2 = particleSystem.color2.asArray();
  57581. serializationObject.colorDead = particleSystem.colorDead.asArray();
  57582. serializationObject.updateSpeed = particleSystem.updateSpeed;
  57583. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  57584. serializationObject.blendMode = particleSystem.blendMode;
  57585. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  57586. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  57587. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  57588. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  57589. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  57590. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  57591. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  57592. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  57593. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  57594. var colorGradients = particleSystem.getColorGradients();
  57595. if (colorGradients) {
  57596. serializationObject.colorGradients = [];
  57597. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  57598. var colorGradient = colorGradients_1[_i];
  57599. var serializedGradient = {
  57600. gradient: colorGradient.gradient,
  57601. color1: colorGradient.color1.asArray()
  57602. };
  57603. if (colorGradient.color2) {
  57604. serializedGradient.color2 = colorGradient.color2.asArray();
  57605. }
  57606. serializationObject.colorGradients.push(serializedGradient);
  57607. }
  57608. }
  57609. var rampGradients = particleSystem.getRampGradients();
  57610. if (rampGradients) {
  57611. serializationObject.rampGradients = [];
  57612. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  57613. var rampGradient = rampGradients_1[_a];
  57614. var serializedGradient = {
  57615. gradient: rampGradient.gradient,
  57616. color: rampGradient.color.asArray()
  57617. };
  57618. serializationObject.rampGradients.push(serializedGradient);
  57619. }
  57620. }
  57621. var colorRemapGradients = particleSystem.getColorRemapGradients();
  57622. if (colorRemapGradients) {
  57623. serializationObject.colorRemapGradients = [];
  57624. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  57625. var colorRemapGradient = colorRemapGradients_1[_b];
  57626. var serializedGradient = {
  57627. gradient: colorRemapGradient.gradient,
  57628. factor1: colorRemapGradient.factor1
  57629. };
  57630. if (colorRemapGradient.factor2 !== undefined) {
  57631. serializedGradient.factor2 = colorRemapGradient.factor2;
  57632. }
  57633. serializationObject.colorRemapGradients.push(serializedGradient);
  57634. }
  57635. }
  57636. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  57637. if (alphaRemapGradients) {
  57638. serializationObject.alphaRemapGradients = [];
  57639. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  57640. var alphaRemapGradient = alphaRemapGradients_1[_c];
  57641. var serializedGradient = {
  57642. gradient: alphaRemapGradient.gradient,
  57643. factor1: alphaRemapGradient.factor1
  57644. };
  57645. if (alphaRemapGradient.factor2 !== undefined) {
  57646. serializedGradient.factor2 = alphaRemapGradient.factor2;
  57647. }
  57648. serializationObject.alphaRemapGradients.push(serializedGradient);
  57649. }
  57650. }
  57651. var sizeGradients = particleSystem.getSizeGradients();
  57652. if (sizeGradients) {
  57653. serializationObject.sizeGradients = [];
  57654. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  57655. var sizeGradient = sizeGradients_1[_d];
  57656. var serializedGradient = {
  57657. gradient: sizeGradient.gradient,
  57658. factor1: sizeGradient.factor1
  57659. };
  57660. if (sizeGradient.factor2 !== undefined) {
  57661. serializedGradient.factor2 = sizeGradient.factor2;
  57662. }
  57663. serializationObject.sizeGradients.push(serializedGradient);
  57664. }
  57665. }
  57666. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  57667. if (angularSpeedGradients) {
  57668. serializationObject.angularSpeedGradients = [];
  57669. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  57670. var angularSpeedGradient = angularSpeedGradients_1[_e];
  57671. var serializedGradient = {
  57672. gradient: angularSpeedGradient.gradient,
  57673. factor1: angularSpeedGradient.factor1
  57674. };
  57675. if (angularSpeedGradient.factor2 !== undefined) {
  57676. serializedGradient.factor2 = angularSpeedGradient.factor2;
  57677. }
  57678. serializationObject.angularSpeedGradients.push(serializedGradient);
  57679. }
  57680. }
  57681. var velocityGradients = particleSystem.getVelocityGradients();
  57682. if (velocityGradients) {
  57683. serializationObject.velocityGradients = [];
  57684. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  57685. var velocityGradient = velocityGradients_1[_f];
  57686. var serializedGradient = {
  57687. gradient: velocityGradient.gradient,
  57688. factor1: velocityGradient.factor1
  57689. };
  57690. if (velocityGradient.factor2 !== undefined) {
  57691. serializedGradient.factor2 = velocityGradient.factor2;
  57692. }
  57693. serializationObject.velocityGradients.push(serializedGradient);
  57694. }
  57695. }
  57696. var dragGradients = particleSystem.getDragGradients();
  57697. if (dragGradients) {
  57698. serializationObject.dragyGradients = [];
  57699. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  57700. var dragGradient = dragGradients_1[_g];
  57701. var serializedGradient = {
  57702. gradient: dragGradient.gradient,
  57703. factor1: dragGradient.factor1
  57704. };
  57705. if (dragGradient.factor2 !== undefined) {
  57706. serializedGradient.factor2 = dragGradient.factor2;
  57707. }
  57708. serializationObject.dragGradients.push(serializedGradient);
  57709. }
  57710. }
  57711. var emitRateGradients = particleSystem.getEmitRateGradients();
  57712. if (emitRateGradients) {
  57713. serializationObject.emitRateGradients = [];
  57714. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  57715. var emitRateGradient = emitRateGradients_1[_h];
  57716. var serializedGradient = {
  57717. gradient: emitRateGradient.gradient,
  57718. factor1: emitRateGradient.factor1
  57719. };
  57720. if (emitRateGradient.factor2 !== undefined) {
  57721. serializedGradient.factor2 = emitRateGradient.factor2;
  57722. }
  57723. serializationObject.emitRateGradients.push(serializedGradient);
  57724. }
  57725. }
  57726. var startSizeGradients = particleSystem.getStartSizeGradients();
  57727. if (startSizeGradients) {
  57728. serializationObject.startSizeGradients = [];
  57729. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  57730. var startSizeGradient = startSizeGradients_1[_j];
  57731. var serializedGradient = {
  57732. gradient: startSizeGradient.gradient,
  57733. factor1: startSizeGradient.factor1
  57734. };
  57735. if (startSizeGradient.factor2 !== undefined) {
  57736. serializedGradient.factor2 = startSizeGradient.factor2;
  57737. }
  57738. serializationObject.startSizeGradients.push(serializedGradient);
  57739. }
  57740. }
  57741. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  57742. if (limitVelocityGradients) {
  57743. serializationObject.limitVelocityGradients = [];
  57744. for (var _k = 0, limitVelocityGradients_1 = limitVelocityGradients; _k < limitVelocityGradients_1.length; _k++) {
  57745. var limitVelocityGradient = limitVelocityGradients_1[_k];
  57746. var serializedGradient = {
  57747. gradient: limitVelocityGradient.gradient,
  57748. factor1: limitVelocityGradient.factor1
  57749. };
  57750. if (limitVelocityGradient.factor2 !== undefined) {
  57751. serializedGradient.factor2 = limitVelocityGradient.factor2;
  57752. }
  57753. serializationObject.limitVelocityGradients.push(serializedGradient);
  57754. }
  57755. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  57756. }
  57757. if (particleSystem.noiseTexture) {
  57758. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  57759. }
  57760. };
  57761. /** @hidden */
  57762. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  57763. // Texture
  57764. if (parsedParticleSystem.textureName) {
  57765. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57766. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57767. }
  57768. // Emitter
  57769. if (parsedParticleSystem.emitterId === undefined) {
  57770. particleSystem.emitter = BABYLON.Vector3.Zero();
  57771. }
  57772. else if (parsedParticleSystem.emitterId) {
  57773. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57774. }
  57775. else {
  57776. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57777. }
  57778. // Misc.
  57779. if (parsedParticleSystem.renderingGroupId !== undefined) {
  57780. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  57781. }
  57782. if (parsedParticleSystem.isBillboardBased !== undefined) {
  57783. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  57784. }
  57785. // Animations
  57786. if (parsedParticleSystem.animations) {
  57787. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57788. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57789. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57790. }
  57791. }
  57792. if (parsedParticleSystem.autoAnimate) {
  57793. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57794. }
  57795. // Particle system
  57796. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57797. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57798. particleSystem.minSize = parsedParticleSystem.minSize;
  57799. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57800. if (parsedParticleSystem.minScaleX) {
  57801. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57802. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  57803. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  57804. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  57805. }
  57806. if (parsedParticleSystem.preWarmCycles !== undefined) {
  57807. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  57808. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  57809. }
  57810. if (parsedParticleSystem.minInitialRotation !== undefined) {
  57811. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  57812. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  57813. }
  57814. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57815. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57816. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57817. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57818. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57819. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57820. if (parsedParticleSystem.noiseStrength) {
  57821. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  57822. }
  57823. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57824. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57825. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57826. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57827. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57828. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57829. if (parsedParticleSystem.colorGradients) {
  57830. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  57831. var colorGradient = _a[_i];
  57832. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  57833. }
  57834. }
  57835. if (parsedParticleSystem.rampGradients) {
  57836. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  57837. var rampGradient = _c[_b];
  57838. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color1));
  57839. }
  57840. }
  57841. if (parsedParticleSystem.colorRemapGradients) {
  57842. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  57843. var colorRemapGradient = _e[_d];
  57844. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  57845. }
  57846. }
  57847. if (parsedParticleSystem.alphaRemapGradients) {
  57848. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  57849. var alphaRemapGradient = _g[_f];
  57850. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  57851. }
  57852. }
  57853. if (parsedParticleSystem.sizeGradients) {
  57854. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  57855. var sizeGradient = _j[_h];
  57856. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  57857. }
  57858. }
  57859. if (parsedParticleSystem.sizeGradients) {
  57860. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  57861. var sizeGradient = _l[_k];
  57862. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  57863. }
  57864. }
  57865. if (parsedParticleSystem.angularSpeedGradients) {
  57866. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  57867. var angularSpeedGradient = _o[_m];
  57868. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  57869. }
  57870. }
  57871. if (parsedParticleSystem.velocityGradients) {
  57872. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  57873. var velocityGradient = _q[_p];
  57874. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  57875. }
  57876. }
  57877. if (parsedParticleSystem.dragGradients) {
  57878. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  57879. var dragGradient = _s[_r];
  57880. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  57881. }
  57882. }
  57883. if (parsedParticleSystem.emitRateGradients) {
  57884. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  57885. var emitRateGradient = _u[_t];
  57886. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  57887. }
  57888. }
  57889. if (parsedParticleSystem.startSizeGradients) {
  57890. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  57891. var startSizeGradient = _w[_v];
  57892. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  57893. }
  57894. }
  57895. if (parsedParticleSystem.limitVelocityGradients) {
  57896. for (var _x = 0, _y = parsedParticleSystem.limitVelocityGradients; _x < _y.length; _x++) {
  57897. var limitVelocityGradient = _y[_x];
  57898. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  57899. }
  57900. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  57901. }
  57902. if (parsedParticleSystem.noiseTexture) {
  57903. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  57904. }
  57905. // Emitter
  57906. var emitterType;
  57907. if (parsedParticleSystem.particleEmitterType) {
  57908. switch (parsedParticleSystem.particleEmitterType.type) {
  57909. case "SphereParticleEmitter":
  57910. emitterType = new BABYLON.SphereParticleEmitter();
  57911. break;
  57912. case "SphereDirectedParticleEmitter":
  57913. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57914. break;
  57915. case "ConeEmitter":
  57916. case "ConeParticleEmitter":
  57917. emitterType = new BABYLON.ConeParticleEmitter();
  57918. break;
  57919. case "BoxEmitter":
  57920. case "BoxParticleEmitter":
  57921. default:
  57922. emitterType = new BABYLON.BoxParticleEmitter();
  57923. break;
  57924. }
  57925. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57926. }
  57927. else {
  57928. emitterType = new BABYLON.BoxParticleEmitter();
  57929. emitterType.parse(parsedParticleSystem);
  57930. }
  57931. particleSystem.particleEmitterType = emitterType;
  57932. // Animation sheet
  57933. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57934. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57935. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57936. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57937. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57938. };
  57939. /**
  57940. * Parses a JSON object to create a particle system.
  57941. * @param parsedParticleSystem The JSON object to parse
  57942. * @param scene The scene to create the particle system in
  57943. * @param rootUrl The root url to use to load external dependencies like texture
  57944. * @returns the Parsed particle system
  57945. */
  57946. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57947. var name = parsedParticleSystem.name;
  57948. var custom = null;
  57949. var program = null;
  57950. if (parsedParticleSystem.customShader) {
  57951. program = parsedParticleSystem.customShader;
  57952. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57953. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57954. }
  57955. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57956. particleSystem.customShader = program;
  57957. if (parsedParticleSystem.id) {
  57958. particleSystem.id = parsedParticleSystem.id;
  57959. }
  57960. // Auto start
  57961. if (parsedParticleSystem.preventAutoStart) {
  57962. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57963. }
  57964. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57965. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57966. if (!particleSystem.preventAutoStart) {
  57967. particleSystem.start();
  57968. }
  57969. return particleSystem;
  57970. };
  57971. return ParticleSystem;
  57972. }(BABYLON.BaseParticleSystem));
  57973. BABYLON.ParticleSystem = ParticleSystem;
  57974. })(BABYLON || (BABYLON = {}));
  57975. //# sourceMappingURL=babylon.particleSystem.js.map
  57976. var BABYLON;
  57977. (function (BABYLON) {
  57978. /**
  57979. * Particle emitter emitting particles from the inside of a box.
  57980. * It emits the particles randomly between 2 given directions.
  57981. */
  57982. var BoxParticleEmitter = /** @class */ (function () {
  57983. /**
  57984. * Creates a new instance BoxParticleEmitter
  57985. */
  57986. function BoxParticleEmitter() {
  57987. /**
  57988. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57989. */
  57990. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57991. /**
  57992. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57993. */
  57994. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57995. /**
  57996. * 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.
  57997. */
  57998. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57999. /**
  58000. * 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.
  58001. */
  58002. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  58003. }
  58004. /**
  58005. * Called by the particle System when the direction is computed for the created particle.
  58006. * @param worldMatrix is the world matrix of the particle system
  58007. * @param directionToUpdate is the direction vector to update with the result
  58008. * @param particle is the particle we are computed the direction for
  58009. */
  58010. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58011. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58012. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58013. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58014. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58015. };
  58016. /**
  58017. * Called by the particle System when the position is computed for the created particle.
  58018. * @param worldMatrix is the world matrix of the particle system
  58019. * @param positionToUpdate is the position vector to update with the result
  58020. * @param particle is the particle we are computed the position for
  58021. */
  58022. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58023. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  58024. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  58025. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  58026. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58027. };
  58028. /**
  58029. * Clones the current emitter and returns a copy of it
  58030. * @returns the new emitter
  58031. */
  58032. BoxParticleEmitter.prototype.clone = function () {
  58033. var newOne = new BoxParticleEmitter();
  58034. BABYLON.Tools.DeepCopy(this, newOne);
  58035. return newOne;
  58036. };
  58037. /**
  58038. * Called by the GPUParticleSystem to setup the update shader
  58039. * @param effect defines the update shader
  58040. */
  58041. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  58042. effect.setVector3("direction1", this.direction1);
  58043. effect.setVector3("direction2", this.direction2);
  58044. effect.setVector3("minEmitBox", this.minEmitBox);
  58045. effect.setVector3("maxEmitBox", this.maxEmitBox);
  58046. };
  58047. /**
  58048. * Returns a string to use to update the GPU particles update shader
  58049. * @returns a string containng the defines string
  58050. */
  58051. BoxParticleEmitter.prototype.getEffectDefines = function () {
  58052. return "#define BOXEMITTER";
  58053. };
  58054. /**
  58055. * Returns the string "BoxParticleEmitter"
  58056. * @returns a string containing the class name
  58057. */
  58058. BoxParticleEmitter.prototype.getClassName = function () {
  58059. return "BoxParticleEmitter";
  58060. };
  58061. /**
  58062. * Serializes the particle system to a JSON object.
  58063. * @returns the JSON object
  58064. */
  58065. BoxParticleEmitter.prototype.serialize = function () {
  58066. var serializationObject = {};
  58067. serializationObject.type = this.getClassName();
  58068. serializationObject.direction1 = this.direction1.asArray();
  58069. serializationObject.direction2 = this.direction2.asArray();
  58070. serializationObject.minEmitBox = this.minEmitBox.asArray();
  58071. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  58072. return serializationObject;
  58073. };
  58074. /**
  58075. * Parse properties from a JSON object
  58076. * @param serializationObject defines the JSON object
  58077. */
  58078. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  58079. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58080. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58081. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  58082. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  58083. };
  58084. return BoxParticleEmitter;
  58085. }());
  58086. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  58087. })(BABYLON || (BABYLON = {}));
  58088. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  58089. var BABYLON;
  58090. (function (BABYLON) {
  58091. /**
  58092. * Particle emitter emitting particles from the inside of a cylinder.
  58093. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  58094. */
  58095. var CylinderParticleEmitter = /** @class */ (function () {
  58096. /**
  58097. * Creates a new instance CylinderParticleEmitter
  58098. * @param radius the radius of the emission cylinder (1 by default)
  58099. * @param height the height of the emission cylinder (1 by default)
  58100. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58101. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58102. */
  58103. function CylinderParticleEmitter(
  58104. /**
  58105. * The radius of the emission cylinder.
  58106. */
  58107. radius,
  58108. /**
  58109. * The height of the emission cylinder.
  58110. */
  58111. height,
  58112. /**
  58113. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58114. */
  58115. radiusRange,
  58116. /**
  58117. * How much to randomize the particle direction [0-1].
  58118. */
  58119. directionRandomizer) {
  58120. if (radius === void 0) { radius = 1; }
  58121. if (height === void 0) { height = 1; }
  58122. if (radiusRange === void 0) { radiusRange = 1; }
  58123. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58124. this.radius = radius;
  58125. this.height = height;
  58126. this.radiusRange = radiusRange;
  58127. this.directionRandomizer = directionRandomizer;
  58128. }
  58129. /**
  58130. * Called by the particle System when the direction is computed for the created particle.
  58131. * @param worldMatrix is the world matrix of the particle system
  58132. * @param directionToUpdate is the direction vector to update with the result
  58133. * @param particle is the particle we are computed the direction for
  58134. */
  58135. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58136. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58137. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  58138. var angle = Math.atan2(direction.x, direction.z);
  58139. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  58140. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  58141. direction.x = Math.sin(angle);
  58142. direction.z = Math.cos(angle);
  58143. direction.normalize();
  58144. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58145. };
  58146. /**
  58147. * Called by the particle System when the position is computed for the created particle.
  58148. * @param worldMatrix is the world matrix of the particle system
  58149. * @param positionToUpdate is the position vector to update with the result
  58150. * @param particle is the particle we are computed the position for
  58151. */
  58152. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58153. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  58154. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58155. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  58156. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  58157. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  58158. var xPos = positionRadius * Math.cos(angle);
  58159. var zPos = positionRadius * Math.sin(angle);
  58160. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  58161. };
  58162. /**
  58163. * Clones the current emitter and returns a copy of it
  58164. * @returns the new emitter
  58165. */
  58166. CylinderParticleEmitter.prototype.clone = function () {
  58167. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  58168. BABYLON.Tools.DeepCopy(this, newOne);
  58169. return newOne;
  58170. };
  58171. /**
  58172. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58173. * @param effect defines the update shader
  58174. */
  58175. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  58176. effect.setFloat("radius", this.radius);
  58177. effect.setFloat("height", this.height);
  58178. effect.setFloat("radiusRange", this.radiusRange);
  58179. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58180. };
  58181. /**
  58182. * Returns a string to use to update the GPU particles update shader
  58183. * @returns a string containng the defines string
  58184. */
  58185. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  58186. return "#define CYLINDEREMITTER";
  58187. };
  58188. /**
  58189. * Returns the string "CylinderParticleEmitter"
  58190. * @returns a string containing the class name
  58191. */
  58192. CylinderParticleEmitter.prototype.getClassName = function () {
  58193. return "CylinderParticleEmitter";
  58194. };
  58195. /**
  58196. * Serializes the particle system to a JSON object.
  58197. * @returns the JSON object
  58198. */
  58199. CylinderParticleEmitter.prototype.serialize = function () {
  58200. var serializationObject = {};
  58201. serializationObject.type = this.getClassName();
  58202. serializationObject.radius = this.radius;
  58203. serializationObject.height = this.height;
  58204. serializationObject.radiusRange = this.radiusRange;
  58205. serializationObject.directionRandomizer = this.directionRandomizer;
  58206. return serializationObject;
  58207. };
  58208. /**
  58209. * Parse properties from a JSON object
  58210. * @param serializationObject defines the JSON object
  58211. */
  58212. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  58213. this.radius = serializationObject.radius;
  58214. this.height = serializationObject.height;
  58215. this.radiusRange = serializationObject.radiusRange;
  58216. this.directionRandomizer = serializationObject.directionRandomizer;
  58217. };
  58218. return CylinderParticleEmitter;
  58219. }());
  58220. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  58221. /**
  58222. * Particle emitter emitting particles from the inside of a cylinder.
  58223. * It emits the particles randomly between two vectors.
  58224. */
  58225. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  58226. __extends(CylinderDirectedParticleEmitter, _super);
  58227. /**
  58228. * Creates a new instance CylinderDirectedParticleEmitter
  58229. * @param radius the radius of the emission cylinder (1 by default)
  58230. * @param height the height of the emission cylinder (1 by default)
  58231. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58232. * @param direction1 the min limit of the emission direction (up vector by default)
  58233. * @param direction2 the max limit of the emission direction (up vector by default)
  58234. */
  58235. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  58236. /**
  58237. * The min limit of the emission direction.
  58238. */
  58239. direction1,
  58240. /**
  58241. * The max limit of the emission direction.
  58242. */
  58243. direction2) {
  58244. if (radius === void 0) { radius = 1; }
  58245. if (height === void 0) { height = 1; }
  58246. if (radiusRange === void 0) { radiusRange = 1; }
  58247. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58248. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58249. var _this = _super.call(this, radius, height, radiusRange) || this;
  58250. _this.direction1 = direction1;
  58251. _this.direction2 = direction2;
  58252. return _this;
  58253. }
  58254. /**
  58255. * Called by the particle System when the direction is computed for the created particle.
  58256. * @param worldMatrix is the world matrix of the particle system
  58257. * @param directionToUpdate is the direction vector to update with the result
  58258. * @param particle is the particle we are computed the direction for
  58259. */
  58260. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58261. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58262. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58263. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58264. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58265. };
  58266. /**
  58267. * Clones the current emitter and returns a copy of it
  58268. * @returns the new emitter
  58269. */
  58270. CylinderDirectedParticleEmitter.prototype.clone = function () {
  58271. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  58272. BABYLON.Tools.DeepCopy(this, newOne);
  58273. return newOne;
  58274. };
  58275. /**
  58276. * Called by the GPUParticleSystem to setup the update shader
  58277. * @param effect defines the update shader
  58278. */
  58279. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58280. effect.setFloat("radius", this.radius);
  58281. effect.setFloat("height", this.height);
  58282. effect.setFloat("radiusRange", this.radiusRange);
  58283. effect.setVector3("direction1", this.direction1);
  58284. effect.setVector3("direction2", this.direction2);
  58285. };
  58286. /**
  58287. * Returns a string to use to update the GPU particles update shader
  58288. * @returns a string containng the defines string
  58289. */
  58290. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58291. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  58292. };
  58293. /**
  58294. * Returns the string "CylinderDirectedParticleEmitter"
  58295. * @returns a string containing the class name
  58296. */
  58297. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  58298. return "CylinderDirectedParticleEmitter";
  58299. };
  58300. /**
  58301. * Serializes the particle system to a JSON object.
  58302. * @returns the JSON object
  58303. */
  58304. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  58305. var serializationObject = _super.prototype.serialize.call(this);
  58306. serializationObject.direction1 = this.direction1.asArray();
  58307. serializationObject.direction2 = this.direction2.asArray();
  58308. return serializationObject;
  58309. };
  58310. /**
  58311. * Parse properties from a JSON object
  58312. * @param serializationObject defines the JSON object
  58313. */
  58314. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58315. _super.prototype.parse.call(this, serializationObject);
  58316. this.direction1.copyFrom(serializationObject.direction1);
  58317. this.direction2.copyFrom(serializationObject.direction2);
  58318. };
  58319. return CylinderDirectedParticleEmitter;
  58320. }(CylinderParticleEmitter));
  58321. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  58322. })(BABYLON || (BABYLON = {}));
  58323. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  58324. var BABYLON;
  58325. (function (BABYLON) {
  58326. /**
  58327. * Particle emitter emitting particles from the inside of a cone.
  58328. * It emits the particles alongside the cone volume from the base to the particle.
  58329. * The emission direction might be randomized.
  58330. */
  58331. var ConeParticleEmitter = /** @class */ (function () {
  58332. /**
  58333. * Creates a new instance ConeParticleEmitter
  58334. * @param radius the radius of the emission cone (1 by default)
  58335. * @param angles the cone base angle (PI by default)
  58336. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  58337. */
  58338. function ConeParticleEmitter(radius, angle,
  58339. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  58340. directionRandomizer) {
  58341. if (radius === void 0) { radius = 1; }
  58342. if (angle === void 0) { angle = Math.PI; }
  58343. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58344. this.directionRandomizer = directionRandomizer;
  58345. /**
  58346. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  58347. */
  58348. this.radiusRange = 1;
  58349. /**
  58350. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  58351. */
  58352. this.heightRange = 1;
  58353. /**
  58354. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  58355. */
  58356. this.emitFromSpawnPointOnly = false;
  58357. this.angle = angle;
  58358. this.radius = radius;
  58359. }
  58360. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  58361. /**
  58362. * Gets or sets the radius of the emission cone
  58363. */
  58364. get: function () {
  58365. return this._radius;
  58366. },
  58367. set: function (value) {
  58368. this._radius = value;
  58369. this._buildHeight();
  58370. },
  58371. enumerable: true,
  58372. configurable: true
  58373. });
  58374. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  58375. /**
  58376. * Gets or sets the angle of the emission cone
  58377. */
  58378. get: function () {
  58379. return this._angle;
  58380. },
  58381. set: function (value) {
  58382. this._angle = value;
  58383. this._buildHeight();
  58384. },
  58385. enumerable: true,
  58386. configurable: true
  58387. });
  58388. ConeParticleEmitter.prototype._buildHeight = function () {
  58389. if (this._angle !== 0) {
  58390. this._height = this._radius / Math.tan(this._angle / 2);
  58391. }
  58392. else {
  58393. this._height = 1;
  58394. }
  58395. };
  58396. /**
  58397. * Called by the particle System when the direction is computed for the created particle.
  58398. * @param worldMatrix is the world matrix of the particle system
  58399. * @param directionToUpdate is the direction vector to update with the result
  58400. * @param particle is the particle we are computed the direction for
  58401. */
  58402. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58403. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  58404. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  58405. }
  58406. else {
  58407. // measure the direction Vector from the emitter to the particle.
  58408. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58409. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58410. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58411. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58412. direction.x += randX;
  58413. direction.y += randY;
  58414. direction.z += randZ;
  58415. direction.normalize();
  58416. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58417. }
  58418. };
  58419. /**
  58420. * Called by the particle System when the position is computed for the created particle.
  58421. * @param worldMatrix is the world matrix of the particle system
  58422. * @param positionToUpdate is the position vector to update with the result
  58423. * @param particle is the particle we are computed the position for
  58424. */
  58425. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58426. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  58427. var h;
  58428. if (!this.emitFromSpawnPointOnly) {
  58429. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  58430. // Better distribution in a cone at normal angles.
  58431. h = 1 - h * h;
  58432. }
  58433. else {
  58434. h = 0.0001;
  58435. }
  58436. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  58437. radius = radius * h;
  58438. var randX = radius * Math.sin(s);
  58439. var randZ = radius * Math.cos(s);
  58440. var randY = h * this._height;
  58441. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58442. };
  58443. /**
  58444. * Clones the current emitter and returns a copy of it
  58445. * @returns the new emitter
  58446. */
  58447. ConeParticleEmitter.prototype.clone = function () {
  58448. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  58449. BABYLON.Tools.DeepCopy(this, newOne);
  58450. return newOne;
  58451. };
  58452. /**
  58453. * Called by the GPUParticleSystem to setup the update shader
  58454. * @param effect defines the update shader
  58455. */
  58456. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  58457. effect.setFloat2("radius", this._radius, this.radiusRange);
  58458. effect.setFloat("coneAngle", this._angle);
  58459. effect.setFloat2("height", this._height, this.heightRange);
  58460. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58461. };
  58462. /**
  58463. * Returns a string to use to update the GPU particles update shader
  58464. * @returns a string containng the defines string
  58465. */
  58466. ConeParticleEmitter.prototype.getEffectDefines = function () {
  58467. var defines = "#define CONEEMITTER";
  58468. if (this.emitFromSpawnPointOnly) {
  58469. defines += "\n#define CONEEMITTERSPAWNPOINT";
  58470. }
  58471. return defines;
  58472. };
  58473. /**
  58474. * Returns the string "ConeParticleEmitter"
  58475. * @returns a string containing the class name
  58476. */
  58477. ConeParticleEmitter.prototype.getClassName = function () {
  58478. return "ConeParticleEmitter";
  58479. };
  58480. /**
  58481. * Serializes the particle system to a JSON object.
  58482. * @returns the JSON object
  58483. */
  58484. ConeParticleEmitter.prototype.serialize = function () {
  58485. var serializationObject = {};
  58486. serializationObject.type = this.getClassName();
  58487. serializationObject.radius = this._radius;
  58488. serializationObject.angle = this._angle;
  58489. serializationObject.directionRandomizer = this.directionRandomizer;
  58490. return serializationObject;
  58491. };
  58492. /**
  58493. * Parse properties from a JSON object
  58494. * @param serializationObject defines the JSON object
  58495. */
  58496. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  58497. this.radius = serializationObject.radius;
  58498. this.angle = serializationObject.angle;
  58499. this.directionRandomizer = serializationObject.directionRandomizer;
  58500. };
  58501. return ConeParticleEmitter;
  58502. }());
  58503. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  58504. })(BABYLON || (BABYLON = {}));
  58505. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  58506. var BABYLON;
  58507. (function (BABYLON) {
  58508. /**
  58509. * Particle emitter emitting particles from the inside of a sphere.
  58510. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  58511. */
  58512. var SphereParticleEmitter = /** @class */ (function () {
  58513. /**
  58514. * Creates a new instance SphereParticleEmitter
  58515. * @param radius the radius of the emission sphere (1 by default)
  58516. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58517. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58518. */
  58519. function SphereParticleEmitter(
  58520. /**
  58521. * The radius of the emission sphere.
  58522. */
  58523. radius,
  58524. /**
  58525. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58526. */
  58527. radiusRange,
  58528. /**
  58529. * How much to randomize the particle direction [0-1].
  58530. */
  58531. directionRandomizer) {
  58532. if (radius === void 0) { radius = 1; }
  58533. if (radiusRange === void 0) { radiusRange = 1; }
  58534. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58535. this.radius = radius;
  58536. this.radiusRange = radiusRange;
  58537. this.directionRandomizer = directionRandomizer;
  58538. }
  58539. /**
  58540. * Called by the particle System when the direction is computed for the created particle.
  58541. * @param worldMatrix is the world matrix of the particle system
  58542. * @param directionToUpdate is the direction vector to update with the result
  58543. * @param particle is the particle we are computed the direction for
  58544. */
  58545. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58546. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58547. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58548. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58549. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58550. direction.x += randX;
  58551. direction.y += randY;
  58552. direction.z += randZ;
  58553. direction.normalize();
  58554. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58555. };
  58556. /**
  58557. * Called by the particle System when the position is computed for the created particle.
  58558. * @param worldMatrix is the world matrix of the particle system
  58559. * @param positionToUpdate is the position vector to update with the result
  58560. * @param particle is the particle we are computed the position for
  58561. */
  58562. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58563. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58564. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58565. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58566. var theta = Math.acos(2 * v - 1);
  58567. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58568. var randY = randRadius * Math.cos(theta);
  58569. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58570. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58571. };
  58572. /**
  58573. * Clones the current emitter and returns a copy of it
  58574. * @returns the new emitter
  58575. */
  58576. SphereParticleEmitter.prototype.clone = function () {
  58577. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  58578. BABYLON.Tools.DeepCopy(this, newOne);
  58579. return newOne;
  58580. };
  58581. /**
  58582. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58583. * @param effect defines the update shader
  58584. */
  58585. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  58586. effect.setFloat("radius", this.radius);
  58587. effect.setFloat("radiusRange", this.radiusRange);
  58588. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58589. };
  58590. /**
  58591. * Returns a string to use to update the GPU particles update shader
  58592. * @returns a string containng the defines string
  58593. */
  58594. SphereParticleEmitter.prototype.getEffectDefines = function () {
  58595. return "#define SPHEREEMITTER";
  58596. };
  58597. /**
  58598. * Returns the string "SphereParticleEmitter"
  58599. * @returns a string containing the class name
  58600. */
  58601. SphereParticleEmitter.prototype.getClassName = function () {
  58602. return "SphereParticleEmitter";
  58603. };
  58604. /**
  58605. * Serializes the particle system to a JSON object.
  58606. * @returns the JSON object
  58607. */
  58608. SphereParticleEmitter.prototype.serialize = function () {
  58609. var serializationObject = {};
  58610. serializationObject.type = this.getClassName();
  58611. serializationObject.radius = this.radius;
  58612. serializationObject.radiusRange = this.radiusRange;
  58613. serializationObject.directionRandomizer = this.directionRandomizer;
  58614. return serializationObject;
  58615. };
  58616. /**
  58617. * Parse properties from a JSON object
  58618. * @param serializationObject defines the JSON object
  58619. */
  58620. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  58621. this.radius = serializationObject.radius;
  58622. this.radiusRange = serializationObject.radiusRange;
  58623. this.directionRandomizer = serializationObject.directionRandomizer;
  58624. };
  58625. return SphereParticleEmitter;
  58626. }());
  58627. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  58628. /**
  58629. * Particle emitter emitting particles from the inside of a sphere.
  58630. * It emits the particles randomly between two vectors.
  58631. */
  58632. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  58633. __extends(SphereDirectedParticleEmitter, _super);
  58634. /**
  58635. * Creates a new instance SphereDirectedParticleEmitter
  58636. * @param radius the radius of the emission sphere (1 by default)
  58637. * @param direction1 the min limit of the emission direction (up vector by default)
  58638. * @param direction2 the max limit of the emission direction (up vector by default)
  58639. */
  58640. function SphereDirectedParticleEmitter(radius,
  58641. /**
  58642. * The min limit of the emission direction.
  58643. */
  58644. direction1,
  58645. /**
  58646. * The max limit of the emission direction.
  58647. */
  58648. direction2) {
  58649. if (radius === void 0) { radius = 1; }
  58650. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58651. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58652. var _this = _super.call(this, radius) || this;
  58653. _this.direction1 = direction1;
  58654. _this.direction2 = direction2;
  58655. return _this;
  58656. }
  58657. /**
  58658. * Called by the particle System when the direction is computed for the created particle.
  58659. * @param worldMatrix is the world matrix of the particle system
  58660. * @param directionToUpdate is the direction vector to update with the result
  58661. * @param particle is the particle we are computed the direction for
  58662. */
  58663. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58664. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58665. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58666. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58667. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58668. };
  58669. /**
  58670. * Clones the current emitter and returns a copy of it
  58671. * @returns the new emitter
  58672. */
  58673. SphereDirectedParticleEmitter.prototype.clone = function () {
  58674. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  58675. BABYLON.Tools.DeepCopy(this, newOne);
  58676. return newOne;
  58677. };
  58678. /**
  58679. * Called by the GPUParticleSystem to setup the update shader
  58680. * @param effect defines the update shader
  58681. */
  58682. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58683. effect.setFloat("radius", this.radius);
  58684. effect.setFloat("radiusRange", this.radiusRange);
  58685. effect.setVector3("direction1", this.direction1);
  58686. effect.setVector3("direction2", this.direction2);
  58687. };
  58688. /**
  58689. * Returns a string to use to update the GPU particles update shader
  58690. * @returns a string containng the defines string
  58691. */
  58692. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58693. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  58694. };
  58695. /**
  58696. * Returns the string "SphereDirectedParticleEmitter"
  58697. * @returns a string containing the class name
  58698. */
  58699. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  58700. return "SphereDirectedParticleEmitter";
  58701. };
  58702. /**
  58703. * Serializes the particle system to a JSON object.
  58704. * @returns the JSON object
  58705. */
  58706. SphereDirectedParticleEmitter.prototype.serialize = function () {
  58707. var serializationObject = _super.prototype.serialize.call(this);
  58708. serializationObject.direction1 = this.direction1.asArray();
  58709. serializationObject.direction2 = this.direction2.asArray();
  58710. return serializationObject;
  58711. };
  58712. /**
  58713. * Parse properties from a JSON object
  58714. * @param serializationObject defines the JSON object
  58715. */
  58716. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58717. _super.prototype.parse.call(this, serializationObject);
  58718. this.direction1.copyFrom(serializationObject.direction1);
  58719. this.direction2.copyFrom(serializationObject.direction2);
  58720. };
  58721. return SphereDirectedParticleEmitter;
  58722. }(SphereParticleEmitter));
  58723. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  58724. })(BABYLON || (BABYLON = {}));
  58725. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  58726. var BABYLON;
  58727. (function (BABYLON) {
  58728. /**
  58729. * Particle emitter emitting particles from the inside of a hemisphere.
  58730. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  58731. */
  58732. var HemisphericParticleEmitter = /** @class */ (function () {
  58733. /**
  58734. * Creates a new instance HemisphericParticleEmitter
  58735. * @param radius the radius of the emission hemisphere (1 by default)
  58736. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58737. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58738. */
  58739. function HemisphericParticleEmitter(
  58740. /**
  58741. * The radius of the emission hemisphere.
  58742. */
  58743. radius,
  58744. /**
  58745. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58746. */
  58747. radiusRange,
  58748. /**
  58749. * How much to randomize the particle direction [0-1].
  58750. */
  58751. directionRandomizer) {
  58752. if (radius === void 0) { radius = 1; }
  58753. if (radiusRange === void 0) { radiusRange = 1; }
  58754. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58755. this.radius = radius;
  58756. this.radiusRange = radiusRange;
  58757. this.directionRandomizer = directionRandomizer;
  58758. }
  58759. /**
  58760. * Called by the particle System when the direction is computed for the created particle.
  58761. * @param worldMatrix is the world matrix of the particle system
  58762. * @param directionToUpdate is the direction vector to update with the result
  58763. * @param particle is the particle we are computed the direction for
  58764. */
  58765. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58766. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58767. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58768. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58769. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58770. direction.x += randX;
  58771. direction.y += randY;
  58772. direction.z += randZ;
  58773. direction.normalize();
  58774. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58775. };
  58776. /**
  58777. * Called by the particle System when the position is computed for the created particle.
  58778. * @param worldMatrix is the world matrix of the particle system
  58779. * @param positionToUpdate is the position vector to update with the result
  58780. * @param particle is the particle we are computed the position for
  58781. */
  58782. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58783. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58784. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58785. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58786. var theta = Math.acos(2 * v - 1);
  58787. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58788. var randY = randRadius * Math.cos(theta);
  58789. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58790. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  58791. };
  58792. /**
  58793. * Clones the current emitter and returns a copy of it
  58794. * @returns the new emitter
  58795. */
  58796. HemisphericParticleEmitter.prototype.clone = function () {
  58797. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  58798. BABYLON.Tools.DeepCopy(this, newOne);
  58799. return newOne;
  58800. };
  58801. /**
  58802. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58803. * @param effect defines the update shader
  58804. */
  58805. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  58806. effect.setFloat("radius", this.radius);
  58807. effect.setFloat("radiusRange", this.radiusRange);
  58808. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58809. };
  58810. /**
  58811. * Returns a string to use to update the GPU particles update shader
  58812. * @returns a string containng the defines string
  58813. */
  58814. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  58815. return "#define HEMISPHERICEMITTER";
  58816. };
  58817. /**
  58818. * Returns the string "HemisphericParticleEmitter"
  58819. * @returns a string containing the class name
  58820. */
  58821. HemisphericParticleEmitter.prototype.getClassName = function () {
  58822. return "HemisphericParticleEmitter";
  58823. };
  58824. /**
  58825. * Serializes the particle system to a JSON object.
  58826. * @returns the JSON object
  58827. */
  58828. HemisphericParticleEmitter.prototype.serialize = function () {
  58829. var serializationObject = {};
  58830. serializationObject.type = this.getClassName();
  58831. serializationObject.radius = this.radius;
  58832. serializationObject.radiusRange = this.radiusRange;
  58833. serializationObject.directionRandomizer = this.directionRandomizer;
  58834. return serializationObject;
  58835. };
  58836. /**
  58837. * Parse properties from a JSON object
  58838. * @param serializationObject defines the JSON object
  58839. */
  58840. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  58841. this.radius = serializationObject.radius;
  58842. this.radiusRange = serializationObject.radiusRange;
  58843. this.directionRandomizer = serializationObject.directionRandomizer;
  58844. };
  58845. return HemisphericParticleEmitter;
  58846. }());
  58847. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  58848. })(BABYLON || (BABYLON = {}));
  58849. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  58850. var BABYLON;
  58851. (function (BABYLON) {
  58852. /**
  58853. * Particle emitter emitting particles from a point.
  58854. * It emits the particles randomly between 2 given directions.
  58855. */
  58856. var PointParticleEmitter = /** @class */ (function () {
  58857. /**
  58858. * Creates a new instance PointParticleEmitter
  58859. */
  58860. function PointParticleEmitter() {
  58861. /**
  58862. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58863. */
  58864. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58865. /**
  58866. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58867. */
  58868. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58869. }
  58870. /**
  58871. * Called by the particle System when the direction is computed for the created particle.
  58872. * @param worldMatrix is the world matrix of the particle system
  58873. * @param directionToUpdate is the direction vector to update with the result
  58874. * @param particle is the particle we are computed the direction for
  58875. */
  58876. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58877. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58878. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58879. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58880. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58881. };
  58882. /**
  58883. * Called by the particle System when the position is computed for the created particle.
  58884. * @param worldMatrix is the world matrix of the particle system
  58885. * @param positionToUpdate is the position vector to update with the result
  58886. * @param particle is the particle we are computed the position for
  58887. */
  58888. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58889. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  58890. };
  58891. /**
  58892. * Clones the current emitter and returns a copy of it
  58893. * @returns the new emitter
  58894. */
  58895. PointParticleEmitter.prototype.clone = function () {
  58896. var newOne = new PointParticleEmitter();
  58897. BABYLON.Tools.DeepCopy(this, newOne);
  58898. return newOne;
  58899. };
  58900. /**
  58901. * Called by the GPUParticleSystem to setup the update shader
  58902. * @param effect defines the update shader
  58903. */
  58904. PointParticleEmitter.prototype.applyToShader = function (effect) {
  58905. effect.setVector3("direction1", this.direction1);
  58906. effect.setVector3("direction2", this.direction2);
  58907. };
  58908. /**
  58909. * Returns a string to use to update the GPU particles update shader
  58910. * @returns a string containng the defines string
  58911. */
  58912. PointParticleEmitter.prototype.getEffectDefines = function () {
  58913. return "#define POINTEMITTER";
  58914. };
  58915. /**
  58916. * Returns the string "PointParticleEmitter"
  58917. * @returns a string containing the class name
  58918. */
  58919. PointParticleEmitter.prototype.getClassName = function () {
  58920. return "PointParticleEmitter";
  58921. };
  58922. /**
  58923. * Serializes the particle system to a JSON object.
  58924. * @returns the JSON object
  58925. */
  58926. PointParticleEmitter.prototype.serialize = function () {
  58927. var serializationObject = {};
  58928. serializationObject.type = this.getClassName();
  58929. serializationObject.direction1 = this.direction1.asArray();
  58930. serializationObject.direction2 = this.direction2.asArray();
  58931. return serializationObject;
  58932. };
  58933. /**
  58934. * Parse properties from a JSON object
  58935. * @param serializationObject defines the JSON object
  58936. */
  58937. PointParticleEmitter.prototype.parse = function (serializationObject) {
  58938. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58939. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58940. };
  58941. return PointParticleEmitter;
  58942. }());
  58943. BABYLON.PointParticleEmitter = PointParticleEmitter;
  58944. })(BABYLON || (BABYLON = {}));
  58945. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  58946. var BABYLON;
  58947. (function (BABYLON) {
  58948. // Adds the parsers to the scene parsers.
  58949. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  58950. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  58951. if (!individualParser) {
  58952. return;
  58953. }
  58954. // Particles Systems
  58955. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58956. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58957. var parsedParticleSystem = parsedData.particleSystems[index];
  58958. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  58959. }
  58960. }
  58961. });
  58962. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  58963. if (parsedParticleSystem.activeParticleCount) {
  58964. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58965. return ps;
  58966. }
  58967. else {
  58968. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58969. return ps;
  58970. }
  58971. });
  58972. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  58973. if (uniformsNames === void 0) { uniformsNames = []; }
  58974. if (samplers === void 0) { samplers = []; }
  58975. if (defines === void 0) { defines = ""; }
  58976. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  58977. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  58978. if (defines.indexOf(" BILLBOARD") === -1) {
  58979. defines += "\n#define BILLBOARD\n";
  58980. }
  58981. if (samplers.indexOf("diffuseSampler") === -1) {
  58982. samplers.push("diffuseSampler");
  58983. }
  58984. return this.createEffect({
  58985. vertex: "particles",
  58986. fragmentElement: fragmentName
  58987. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  58988. };
  58989. })(BABYLON || (BABYLON = {}));
  58990. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  58991. var BABYLON;
  58992. (function (BABYLON) {
  58993. /**
  58994. * Type of sub emitter
  58995. */
  58996. var SubEmitterType;
  58997. (function (SubEmitterType) {
  58998. /**
  58999. * Attached to the particle over it's lifetime
  59000. */
  59001. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  59002. /**
  59003. * Created when the particle dies
  59004. */
  59005. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  59006. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  59007. /**
  59008. * Sub emitter class used to emit particles from an existing particle
  59009. */
  59010. var SubEmitter = /** @class */ (function () {
  59011. /**
  59012. * Creates a sub emitter
  59013. * @param particleSystem the particle system to be used by the sub emitter
  59014. */
  59015. function SubEmitter(
  59016. /**
  59017. * the particle system to be used by the sub emitter
  59018. */
  59019. particleSystem) {
  59020. this.particleSystem = particleSystem;
  59021. /**
  59022. * Type of the submitter (Default: END)
  59023. */
  59024. this.type = SubEmitterType.END;
  59025. /**
  59026. * If the particle should inherit the direction from the particle it's attached to. (+Y will face the direction the particle is moving) (Default: false)
  59027. * Note: This only is supported when using an emitter of type Mesh
  59028. */
  59029. this.inheritDirection = false;
  59030. /**
  59031. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  59032. */
  59033. this.inheritedVelocityAmount = 0;
  59034. }
  59035. /**
  59036. * Clones the sub emitter
  59037. * @returns the cloned sub emitter
  59038. */
  59039. SubEmitter.prototype.clone = function () {
  59040. // Clone particle system
  59041. var emitter = this.particleSystem.emitter;
  59042. if (!emitter) {
  59043. emitter = new BABYLON.Vector3();
  59044. }
  59045. else if (emitter instanceof BABYLON.Vector3) {
  59046. emitter = emitter.clone();
  59047. }
  59048. else if (emitter instanceof BABYLON.AbstractMesh) {
  59049. emitter = new BABYLON.Mesh("", emitter._scene);
  59050. }
  59051. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  59052. // Clone properties
  59053. clone.type = this.type;
  59054. clone.inheritDirection = this.inheritDirection;
  59055. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  59056. clone.particleSystem._disposeEmitterOnDispose = true;
  59057. return clone;
  59058. };
  59059. return SubEmitter;
  59060. }());
  59061. BABYLON.SubEmitter = SubEmitter;
  59062. })(BABYLON || (BABYLON = {}));
  59063. //# sourceMappingURL=babylon.subEmitter.js.map
  59064. var BABYLON;
  59065. (function (BABYLON) {
  59066. var ShaderMaterial = /** @class */ (function (_super) {
  59067. __extends(ShaderMaterial, _super);
  59068. function ShaderMaterial(name, scene, shaderPath, options) {
  59069. var _this = _super.call(this, name, scene) || this;
  59070. _this._textures = {};
  59071. _this._textureArrays = {};
  59072. _this._floats = {};
  59073. _this._ints = {};
  59074. _this._floatsArrays = {};
  59075. _this._colors3 = {};
  59076. _this._colors3Arrays = {};
  59077. _this._colors4 = {};
  59078. _this._vectors2 = {};
  59079. _this._vectors3 = {};
  59080. _this._vectors4 = {};
  59081. _this._matrices = {};
  59082. _this._matrices3x3 = {};
  59083. _this._matrices2x2 = {};
  59084. _this._vectors2Arrays = {};
  59085. _this._vectors3Arrays = {};
  59086. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59087. _this._shaderPath = shaderPath;
  59088. options.needAlphaBlending = options.needAlphaBlending || false;
  59089. options.needAlphaTesting = options.needAlphaTesting || false;
  59090. options.attributes = options.attributes || ["position", "normal", "uv"];
  59091. options.uniforms = options.uniforms || ["worldViewProjection"];
  59092. options.uniformBuffers = options.uniformBuffers || [];
  59093. options.samplers = options.samplers || [];
  59094. options.defines = options.defines || [];
  59095. _this._options = options;
  59096. return _this;
  59097. }
  59098. ShaderMaterial.prototype.getClassName = function () {
  59099. return "ShaderMaterial";
  59100. };
  59101. ShaderMaterial.prototype.needAlphaBlending = function () {
  59102. return this._options.needAlphaBlending;
  59103. };
  59104. ShaderMaterial.prototype.needAlphaTesting = function () {
  59105. return this._options.needAlphaTesting;
  59106. };
  59107. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59108. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59109. this._options.uniforms.push(uniformName);
  59110. }
  59111. };
  59112. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59113. if (this._options.samplers.indexOf(name) === -1) {
  59114. this._options.samplers.push(name);
  59115. }
  59116. this._textures[name] = texture;
  59117. return this;
  59118. };
  59119. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59120. if (this._options.samplers.indexOf(name) === -1) {
  59121. this._options.samplers.push(name);
  59122. }
  59123. this._checkUniform(name);
  59124. this._textureArrays[name] = textures;
  59125. return this;
  59126. };
  59127. ShaderMaterial.prototype.setFloat = function (name, value) {
  59128. this._checkUniform(name);
  59129. this._floats[name] = value;
  59130. return this;
  59131. };
  59132. ShaderMaterial.prototype.setInt = function (name, value) {
  59133. this._checkUniform(name);
  59134. this._ints[name] = value;
  59135. return this;
  59136. };
  59137. ShaderMaterial.prototype.setFloats = function (name, value) {
  59138. this._checkUniform(name);
  59139. this._floatsArrays[name] = value;
  59140. return this;
  59141. };
  59142. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59143. this._checkUniform(name);
  59144. this._colors3[name] = value;
  59145. return this;
  59146. };
  59147. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59148. this._checkUniform(name);
  59149. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59150. color.toArray(arr, arr.length);
  59151. return arr;
  59152. }, []);
  59153. return this;
  59154. };
  59155. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59156. this._checkUniform(name);
  59157. this._colors4[name] = value;
  59158. return this;
  59159. };
  59160. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59161. this._checkUniform(name);
  59162. this._vectors2[name] = value;
  59163. return this;
  59164. };
  59165. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59166. this._checkUniform(name);
  59167. this._vectors3[name] = value;
  59168. return this;
  59169. };
  59170. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59171. this._checkUniform(name);
  59172. this._vectors4[name] = value;
  59173. return this;
  59174. };
  59175. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59176. this._checkUniform(name);
  59177. this._matrices[name] = value;
  59178. return this;
  59179. };
  59180. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59181. this._checkUniform(name);
  59182. this._matrices3x3[name] = value;
  59183. return this;
  59184. };
  59185. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59186. this._checkUniform(name);
  59187. this._matrices2x2[name] = value;
  59188. return this;
  59189. };
  59190. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59191. this._checkUniform(name);
  59192. this._vectors2Arrays[name] = value;
  59193. return this;
  59194. };
  59195. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59196. this._checkUniform(name);
  59197. this._vectors3Arrays[name] = value;
  59198. return this;
  59199. };
  59200. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59201. if (!mesh) {
  59202. return true;
  59203. }
  59204. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59205. return false;
  59206. }
  59207. return false;
  59208. };
  59209. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59210. var scene = this.getScene();
  59211. var engine = scene.getEngine();
  59212. if (!this.checkReadyOnEveryCall) {
  59213. if (this._renderId === scene.getRenderId()) {
  59214. if (this._checkCache(scene, mesh, useInstances)) {
  59215. return true;
  59216. }
  59217. }
  59218. }
  59219. // Instances
  59220. var defines = [];
  59221. var attribs = [];
  59222. var fallbacks = new BABYLON.EffectFallbacks();
  59223. if (useInstances) {
  59224. defines.push("#define INSTANCES");
  59225. }
  59226. for (var index = 0; index < this._options.defines.length; index++) {
  59227. defines.push(this._options.defines[index]);
  59228. }
  59229. for (var index = 0; index < this._options.attributes.length; index++) {
  59230. attribs.push(this._options.attributes[index]);
  59231. }
  59232. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59233. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59234. defines.push("#define VERTEXCOLOR");
  59235. }
  59236. // Bones
  59237. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59238. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59239. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59240. if (mesh.numBoneInfluencers > 4) {
  59241. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59242. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59243. }
  59244. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59245. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59246. fallbacks.addCPUSkinningFallback(0, mesh);
  59247. if (this._options.uniforms.indexOf("mBones") === -1) {
  59248. this._options.uniforms.push("mBones");
  59249. }
  59250. }
  59251. else {
  59252. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59253. }
  59254. // Textures
  59255. for (var name in this._textures) {
  59256. if (!this._textures[name].isReady()) {
  59257. return false;
  59258. }
  59259. }
  59260. // Alpha test
  59261. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59262. defines.push("#define ALPHATEST");
  59263. }
  59264. var previousEffect = this._effect;
  59265. var join = defines.join("\n");
  59266. this._effect = engine.createEffect(this._shaderPath, {
  59267. attributes: attribs,
  59268. uniformsNames: this._options.uniforms,
  59269. uniformBuffersNames: this._options.uniformBuffers,
  59270. samplers: this._options.samplers,
  59271. defines: join,
  59272. fallbacks: fallbacks,
  59273. onCompiled: this.onCompiled,
  59274. onError: this.onError
  59275. }, engine);
  59276. if (!this._effect.isReady()) {
  59277. return false;
  59278. }
  59279. if (previousEffect !== this._effect) {
  59280. scene.resetCachedMaterial();
  59281. }
  59282. this._renderId = scene.getRenderId();
  59283. return true;
  59284. };
  59285. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59286. var scene = this.getScene();
  59287. if (!this._effect) {
  59288. return;
  59289. }
  59290. if (this._options.uniforms.indexOf("world") !== -1) {
  59291. this._effect.setMatrix("world", world);
  59292. }
  59293. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59294. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59295. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59296. }
  59297. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59298. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59299. }
  59300. };
  59301. ShaderMaterial.prototype.bind = function (world, mesh) {
  59302. // Std values
  59303. this.bindOnlyWorldMatrix(world);
  59304. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59305. if (this._options.uniforms.indexOf("view") !== -1) {
  59306. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59307. }
  59308. if (this._options.uniforms.indexOf("projection") !== -1) {
  59309. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59310. }
  59311. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59312. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59313. }
  59314. // Bones
  59315. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59316. var name;
  59317. // Texture
  59318. for (name in this._textures) {
  59319. this._effect.setTexture(name, this._textures[name]);
  59320. }
  59321. // Texture arrays
  59322. for (name in this._textureArrays) {
  59323. this._effect.setTextureArray(name, this._textureArrays[name]);
  59324. }
  59325. // Int
  59326. for (name in this._ints) {
  59327. this._effect.setInt(name, this._ints[name]);
  59328. }
  59329. // Float
  59330. for (name in this._floats) {
  59331. this._effect.setFloat(name, this._floats[name]);
  59332. }
  59333. // Floats
  59334. for (name in this._floatsArrays) {
  59335. this._effect.setArray(name, this._floatsArrays[name]);
  59336. }
  59337. // Color3
  59338. for (name in this._colors3) {
  59339. this._effect.setColor3(name, this._colors3[name]);
  59340. }
  59341. for (name in this._colors3Arrays) {
  59342. this._effect.setArray3(name, this._colors3Arrays[name]);
  59343. }
  59344. // Color4
  59345. for (name in this._colors4) {
  59346. var color = this._colors4[name];
  59347. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59348. }
  59349. // Vector2
  59350. for (name in this._vectors2) {
  59351. this._effect.setVector2(name, this._vectors2[name]);
  59352. }
  59353. // Vector3
  59354. for (name in this._vectors3) {
  59355. this._effect.setVector3(name, this._vectors3[name]);
  59356. }
  59357. // Vector4
  59358. for (name in this._vectors4) {
  59359. this._effect.setVector4(name, this._vectors4[name]);
  59360. }
  59361. // Matrix
  59362. for (name in this._matrices) {
  59363. this._effect.setMatrix(name, this._matrices[name]);
  59364. }
  59365. // Matrix 3x3
  59366. for (name in this._matrices3x3) {
  59367. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59368. }
  59369. // Matrix 2x2
  59370. for (name in this._matrices2x2) {
  59371. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59372. }
  59373. // Vector2Array
  59374. for (name in this._vectors2Arrays) {
  59375. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59376. }
  59377. // Vector3Array
  59378. for (name in this._vectors3Arrays) {
  59379. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59380. }
  59381. }
  59382. this._afterBind(mesh);
  59383. };
  59384. ShaderMaterial.prototype.getActiveTextures = function () {
  59385. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59386. for (var name in this._textures) {
  59387. activeTextures.push(this._textures[name]);
  59388. }
  59389. for (var name in this._textureArrays) {
  59390. var array = this._textureArrays[name];
  59391. for (var index = 0; index < array.length; index++) {
  59392. activeTextures.push(array[index]);
  59393. }
  59394. }
  59395. return activeTextures;
  59396. };
  59397. ShaderMaterial.prototype.hasTexture = function (texture) {
  59398. if (_super.prototype.hasTexture.call(this, texture)) {
  59399. return true;
  59400. }
  59401. for (var name in this._textures) {
  59402. if (this._textures[name] === texture) {
  59403. return true;
  59404. }
  59405. }
  59406. for (var name in this._textureArrays) {
  59407. var array = this._textureArrays[name];
  59408. for (var index = 0; index < array.length; index++) {
  59409. if (array[index] === texture) {
  59410. return true;
  59411. }
  59412. }
  59413. }
  59414. return false;
  59415. };
  59416. ShaderMaterial.prototype.clone = function (name) {
  59417. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59418. return newShaderMaterial;
  59419. };
  59420. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59421. if (forceDisposeTextures) {
  59422. var name;
  59423. for (name in this._textures) {
  59424. this._textures[name].dispose();
  59425. }
  59426. for (name in this._textureArrays) {
  59427. var array = this._textureArrays[name];
  59428. for (var index = 0; index < array.length; index++) {
  59429. array[index].dispose();
  59430. }
  59431. }
  59432. }
  59433. this._textures = {};
  59434. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59435. };
  59436. ShaderMaterial.prototype.serialize = function () {
  59437. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59438. serializationObject.customType = "BABYLON.ShaderMaterial";
  59439. serializationObject.options = this._options;
  59440. serializationObject.shaderPath = this._shaderPath;
  59441. var name;
  59442. // Texture
  59443. serializationObject.textures = {};
  59444. for (name in this._textures) {
  59445. serializationObject.textures[name] = this._textures[name].serialize();
  59446. }
  59447. // Texture arrays
  59448. serializationObject.textureArrays = {};
  59449. for (name in this._textureArrays) {
  59450. serializationObject.textureArrays[name] = [];
  59451. var array = this._textureArrays[name];
  59452. for (var index = 0; index < array.length; index++) {
  59453. serializationObject.textureArrays[name].push(array[index].serialize());
  59454. }
  59455. }
  59456. // Float
  59457. serializationObject.floats = {};
  59458. for (name in this._floats) {
  59459. serializationObject.floats[name] = this._floats[name];
  59460. }
  59461. // Float s
  59462. serializationObject.FloatArrays = {};
  59463. for (name in this._floatsArrays) {
  59464. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59465. }
  59466. // Color3
  59467. serializationObject.colors3 = {};
  59468. for (name in this._colors3) {
  59469. serializationObject.colors3[name] = this._colors3[name].asArray();
  59470. }
  59471. // Color3 array
  59472. serializationObject.colors3Arrays = {};
  59473. for (name in this._colors3Arrays) {
  59474. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59475. }
  59476. // Color4
  59477. serializationObject.colors4 = {};
  59478. for (name in this._colors4) {
  59479. serializationObject.colors4[name] = this._colors4[name].asArray();
  59480. }
  59481. // Vector2
  59482. serializationObject.vectors2 = {};
  59483. for (name in this._vectors2) {
  59484. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59485. }
  59486. // Vector3
  59487. serializationObject.vectors3 = {};
  59488. for (name in this._vectors3) {
  59489. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59490. }
  59491. // Vector4
  59492. serializationObject.vectors4 = {};
  59493. for (name in this._vectors4) {
  59494. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59495. }
  59496. // Matrix
  59497. serializationObject.matrices = {};
  59498. for (name in this._matrices) {
  59499. serializationObject.matrices[name] = this._matrices[name].asArray();
  59500. }
  59501. // Matrix 3x3
  59502. serializationObject.matrices3x3 = {};
  59503. for (name in this._matrices3x3) {
  59504. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59505. }
  59506. // Matrix 2x2
  59507. serializationObject.matrices2x2 = {};
  59508. for (name in this._matrices2x2) {
  59509. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59510. }
  59511. // Vector2Array
  59512. serializationObject.vectors2Arrays = {};
  59513. for (name in this._vectors2Arrays) {
  59514. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59515. }
  59516. // Vector3Array
  59517. serializationObject.vectors3Arrays = {};
  59518. for (name in this._vectors3Arrays) {
  59519. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59520. }
  59521. return serializationObject;
  59522. };
  59523. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59524. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59525. var name;
  59526. // Texture
  59527. for (name in source.textures) {
  59528. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59529. }
  59530. // Texture arrays
  59531. for (name in source.textureArrays) {
  59532. var array = source.textureArrays[name];
  59533. var textureArray = new Array();
  59534. for (var index = 0; index < array.length; index++) {
  59535. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59536. }
  59537. material.setTextureArray(name, textureArray);
  59538. }
  59539. // Float
  59540. for (name in source.floats) {
  59541. material.setFloat(name, source.floats[name]);
  59542. }
  59543. // Float s
  59544. for (name in source.floatsArrays) {
  59545. material.setFloats(name, source.floatsArrays[name]);
  59546. }
  59547. // Color3
  59548. for (name in source.colors3) {
  59549. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59550. }
  59551. // Color3 arrays
  59552. for (name in source.colors3Arrays) {
  59553. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59554. if (i % 3 === 0) {
  59555. arr.push([num]);
  59556. }
  59557. else {
  59558. arr[arr.length - 1].push(num);
  59559. }
  59560. return arr;
  59561. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59562. material.setColor3Array(name, colors);
  59563. }
  59564. // Color4
  59565. for (name in source.colors4) {
  59566. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59567. }
  59568. // Vector2
  59569. for (name in source.vectors2) {
  59570. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59571. }
  59572. // Vector3
  59573. for (name in source.vectors3) {
  59574. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59575. }
  59576. // Vector4
  59577. for (name in source.vectors4) {
  59578. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59579. }
  59580. // Matrix
  59581. for (name in source.matrices) {
  59582. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59583. }
  59584. // Matrix 3x3
  59585. for (name in source.matrices3x3) {
  59586. material.setMatrix3x3(name, source.matrices3x3[name]);
  59587. }
  59588. // Matrix 2x2
  59589. for (name in source.matrices2x2) {
  59590. material.setMatrix2x2(name, source.matrices2x2[name]);
  59591. }
  59592. // Vector2Array
  59593. for (name in source.vectors2Arrays) {
  59594. material.setArray2(name, source.vectors2Arrays[name]);
  59595. }
  59596. // Vector3Array
  59597. for (name in source.vectors3Arrays) {
  59598. material.setArray3(name, source.vectors3Arrays[name]);
  59599. }
  59600. return material;
  59601. };
  59602. return ShaderMaterial;
  59603. }(BABYLON.Material));
  59604. BABYLON.ShaderMaterial = ShaderMaterial;
  59605. })(BABYLON || (BABYLON = {}));
  59606. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59607. var BABYLON;
  59608. (function (BABYLON) {
  59609. var GroundMesh = /** @class */ (function (_super) {
  59610. __extends(GroundMesh, _super);
  59611. function GroundMesh(name, scene) {
  59612. var _this = _super.call(this, name, scene) || this;
  59613. _this.generateOctree = false;
  59614. return _this;
  59615. }
  59616. GroundMesh.prototype.getClassName = function () {
  59617. return "GroundMesh";
  59618. };
  59619. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59620. get: function () {
  59621. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59622. },
  59623. enumerable: true,
  59624. configurable: true
  59625. });
  59626. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59627. get: function () {
  59628. return this._subdivisionsX;
  59629. },
  59630. enumerable: true,
  59631. configurable: true
  59632. });
  59633. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59634. get: function () {
  59635. return this._subdivisionsY;
  59636. },
  59637. enumerable: true,
  59638. configurable: true
  59639. });
  59640. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59641. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59642. this._subdivisionsX = chunksCount;
  59643. this._subdivisionsY = chunksCount;
  59644. this.subdivide(chunksCount);
  59645. // Call the octree system optimization if it is defined.
  59646. var thisAsAny = this;
  59647. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  59648. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59649. }
  59650. };
  59651. /**
  59652. * Returns a height (y) value in the Worl system :
  59653. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59654. * Returns the ground y position if (x, z) are outside the ground surface.
  59655. */
  59656. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59657. var world = this.getWorldMatrix();
  59658. var invMat = BABYLON.Tmp.Matrix[5];
  59659. world.invertToRef(invMat);
  59660. var tmpVect = BABYLON.Tmp.Vector3[8];
  59661. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59662. x = tmpVect.x;
  59663. z = tmpVect.z;
  59664. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59665. return this.position.y;
  59666. }
  59667. if (!this._heightQuads || this._heightQuads.length == 0) {
  59668. this._initHeightQuads();
  59669. this._computeHeightQuads();
  59670. }
  59671. var facet = this._getFacetAt(x, z);
  59672. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59673. // return y in the World system
  59674. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59675. return tmpVect.y;
  59676. };
  59677. /**
  59678. * Returns a normalized vector (Vector3) orthogonal to the ground
  59679. * at the ground coordinates (x, z) expressed in the World system.
  59680. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59681. */
  59682. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59683. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59684. this.getNormalAtCoordinatesToRef(x, z, normal);
  59685. return normal;
  59686. };
  59687. /**
  59688. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59689. * at the ground coordinates (x, z) expressed in the World system.
  59690. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59691. * Returns the GroundMesh.
  59692. */
  59693. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59694. var world = this.getWorldMatrix();
  59695. var tmpMat = BABYLON.Tmp.Matrix[5];
  59696. world.invertToRef(tmpMat);
  59697. var tmpVect = BABYLON.Tmp.Vector3[8];
  59698. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59699. x = tmpVect.x;
  59700. z = tmpVect.z;
  59701. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59702. return this;
  59703. }
  59704. if (!this._heightQuads || this._heightQuads.length == 0) {
  59705. this._initHeightQuads();
  59706. this._computeHeightQuads();
  59707. }
  59708. var facet = this._getFacetAt(x, z);
  59709. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59710. return this;
  59711. };
  59712. /**
  59713. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59714. * if the ground has been updated.
  59715. * This can be used in the render loop.
  59716. * Returns the GroundMesh.
  59717. */
  59718. GroundMesh.prototype.updateCoordinateHeights = function () {
  59719. if (!this._heightQuads || this._heightQuads.length == 0) {
  59720. this._initHeightQuads();
  59721. }
  59722. this._computeHeightQuads();
  59723. return this;
  59724. };
  59725. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59726. GroundMesh.prototype._getFacetAt = function (x, z) {
  59727. // retrieve col and row from x, z coordinates in the ground local system
  59728. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59729. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59730. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59731. var facet;
  59732. if (z < quad.slope.x * x + quad.slope.y) {
  59733. facet = quad.facet1;
  59734. }
  59735. else {
  59736. facet = quad.facet2;
  59737. }
  59738. return facet;
  59739. };
  59740. // Creates and populates the heightMap array with "facet" elements :
  59741. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59742. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59743. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59744. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59745. // Returns the GroundMesh.
  59746. GroundMesh.prototype._initHeightQuads = function () {
  59747. var subdivisionsX = this._subdivisionsX;
  59748. var subdivisionsY = this._subdivisionsY;
  59749. this._heightQuads = new Array();
  59750. for (var row = 0; row < subdivisionsY; row++) {
  59751. for (var col = 0; col < subdivisionsX; col++) {
  59752. 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) };
  59753. this._heightQuads[row * subdivisionsX + col] = quad;
  59754. }
  59755. }
  59756. return this;
  59757. };
  59758. // Compute each quad element values and update the the heightMap array :
  59759. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59760. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59761. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59762. // Returns the GroundMesh.
  59763. GroundMesh.prototype._computeHeightQuads = function () {
  59764. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59765. if (!positions) {
  59766. return this;
  59767. }
  59768. var v1 = BABYLON.Tmp.Vector3[3];
  59769. var v2 = BABYLON.Tmp.Vector3[2];
  59770. var v3 = BABYLON.Tmp.Vector3[1];
  59771. var v4 = BABYLON.Tmp.Vector3[0];
  59772. var v1v2 = BABYLON.Tmp.Vector3[4];
  59773. var v1v3 = BABYLON.Tmp.Vector3[5];
  59774. var v1v4 = BABYLON.Tmp.Vector3[6];
  59775. var norm1 = BABYLON.Tmp.Vector3[7];
  59776. var norm2 = BABYLON.Tmp.Vector3[8];
  59777. var i = 0;
  59778. var j = 0;
  59779. var k = 0;
  59780. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59781. var h = 0;
  59782. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59783. var d2 = 0;
  59784. var subdivisionsX = this._subdivisionsX;
  59785. var subdivisionsY = this._subdivisionsY;
  59786. for (var row = 0; row < subdivisionsY; row++) {
  59787. for (var col = 0; col < subdivisionsX; col++) {
  59788. i = col * 3;
  59789. j = row * (subdivisionsX + 1) * 3;
  59790. k = (row + 1) * (subdivisionsX + 1) * 3;
  59791. v1.x = positions[j + i];
  59792. v1.y = positions[j + i + 1];
  59793. v1.z = positions[j + i + 2];
  59794. v2.x = positions[j + i + 3];
  59795. v2.y = positions[j + i + 4];
  59796. v2.z = positions[j + i + 5];
  59797. v3.x = positions[k + i];
  59798. v3.y = positions[k + i + 1];
  59799. v3.z = positions[k + i + 2];
  59800. v4.x = positions[k + i + 3];
  59801. v4.y = positions[k + i + 4];
  59802. v4.z = positions[k + i + 5];
  59803. // 2D slope V1V4
  59804. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59805. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59806. // facet equations :
  59807. // we compute each facet normal vector
  59808. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59809. // we compute the value d by applying the equation to v1 which belongs to the plane
  59810. // then we store the facet equation in a Vector4
  59811. v2.subtractToRef(v1, v1v2);
  59812. v3.subtractToRef(v1, v1v3);
  59813. v4.subtractToRef(v1, v1v4);
  59814. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59815. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59816. norm1.normalize();
  59817. norm2.normalize();
  59818. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59819. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59820. var quad = this._heightQuads[row * subdivisionsX + col];
  59821. quad.slope.copyFromFloats(cd, h);
  59822. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59823. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59824. }
  59825. }
  59826. return this;
  59827. };
  59828. GroundMesh.prototype.serialize = function (serializationObject) {
  59829. _super.prototype.serialize.call(this, serializationObject);
  59830. serializationObject.subdivisionsX = this._subdivisionsX;
  59831. serializationObject.subdivisionsY = this._subdivisionsY;
  59832. serializationObject.minX = this._minX;
  59833. serializationObject.maxX = this._maxX;
  59834. serializationObject.minZ = this._minZ;
  59835. serializationObject.maxZ = this._maxZ;
  59836. serializationObject.width = this._width;
  59837. serializationObject.height = this._height;
  59838. };
  59839. GroundMesh.Parse = function (parsedMesh, scene) {
  59840. var result = new GroundMesh(parsedMesh.name, scene);
  59841. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59842. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59843. result._minX = parsedMesh.minX;
  59844. result._maxX = parsedMesh.maxX;
  59845. result._minZ = parsedMesh.minZ;
  59846. result._maxZ = parsedMesh.maxZ;
  59847. result._width = parsedMesh.width;
  59848. result._height = parsedMesh.height;
  59849. return result;
  59850. };
  59851. return GroundMesh;
  59852. }(BABYLON.Mesh));
  59853. BABYLON.GroundMesh = GroundMesh;
  59854. })(BABYLON || (BABYLON = {}));
  59855. //# sourceMappingURL=babylon.groundMesh.js.map
  59856. var BABYLON;
  59857. (function (BABYLON) {
  59858. /**
  59859. * Creates an instance based on a source mesh.
  59860. */
  59861. var InstancedMesh = /** @class */ (function (_super) {
  59862. __extends(InstancedMesh, _super);
  59863. function InstancedMesh(name, source) {
  59864. var _this = _super.call(this, name, source.getScene()) || this;
  59865. source.instances.push(_this);
  59866. _this._sourceMesh = source;
  59867. _this.position.copyFrom(source.position);
  59868. _this.rotation.copyFrom(source.rotation);
  59869. _this.scaling.copyFrom(source.scaling);
  59870. if (source.rotationQuaternion) {
  59871. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59872. }
  59873. _this.infiniteDistance = source.infiniteDistance;
  59874. _this.setPivotMatrix(source.getPivotMatrix());
  59875. _this.refreshBoundingInfo();
  59876. _this._syncSubMeshes();
  59877. return _this;
  59878. }
  59879. /**
  59880. * Returns the string "InstancedMesh".
  59881. */
  59882. InstancedMesh.prototype.getClassName = function () {
  59883. return "InstancedMesh";
  59884. };
  59885. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59886. // Methods
  59887. get: function () {
  59888. return this._sourceMesh.receiveShadows;
  59889. },
  59890. enumerable: true,
  59891. configurable: true
  59892. });
  59893. Object.defineProperty(InstancedMesh.prototype, "material", {
  59894. get: function () {
  59895. return this._sourceMesh.material;
  59896. },
  59897. enumerable: true,
  59898. configurable: true
  59899. });
  59900. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59901. get: function () {
  59902. return this._sourceMesh.visibility;
  59903. },
  59904. enumerable: true,
  59905. configurable: true
  59906. });
  59907. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59908. get: function () {
  59909. return this._sourceMesh.skeleton;
  59910. },
  59911. enumerable: true,
  59912. configurable: true
  59913. });
  59914. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59915. get: function () {
  59916. return this._sourceMesh.renderingGroupId;
  59917. },
  59918. set: function (value) {
  59919. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59920. return;
  59921. }
  59922. //no-op with warning
  59923. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59924. },
  59925. enumerable: true,
  59926. configurable: true
  59927. });
  59928. /**
  59929. * Returns the total number of vertices (integer).
  59930. */
  59931. InstancedMesh.prototype.getTotalVertices = function () {
  59932. return this._sourceMesh.getTotalVertices();
  59933. };
  59934. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59935. get: function () {
  59936. return this._sourceMesh;
  59937. },
  59938. enumerable: true,
  59939. configurable: true
  59940. });
  59941. /**
  59942. * Is this node ready to be used/rendered
  59943. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59944. * @return {boolean} is it ready
  59945. */
  59946. InstancedMesh.prototype.isReady = function (completeCheck) {
  59947. if (completeCheck === void 0) { completeCheck = false; }
  59948. return this._sourceMesh.isReady(completeCheck, true);
  59949. };
  59950. /**
  59951. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59952. */
  59953. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59954. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59955. };
  59956. /**
  59957. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59958. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59959. * The `data` are either a numeric array either a Float32Array.
  59960. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59961. * 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).
  59962. * Note that a new underlying VertexBuffer object is created each call.
  59963. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59964. *
  59965. * Possible `kind` values :
  59966. * - BABYLON.VertexBuffer.PositionKind
  59967. * - BABYLON.VertexBuffer.UVKind
  59968. * - BABYLON.VertexBuffer.UV2Kind
  59969. * - BABYLON.VertexBuffer.UV3Kind
  59970. * - BABYLON.VertexBuffer.UV4Kind
  59971. * - BABYLON.VertexBuffer.UV5Kind
  59972. * - BABYLON.VertexBuffer.UV6Kind
  59973. * - BABYLON.VertexBuffer.ColorKind
  59974. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59975. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59976. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59977. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59978. *
  59979. * Returns the Mesh.
  59980. */
  59981. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59982. if (this.sourceMesh) {
  59983. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59984. }
  59985. return this.sourceMesh;
  59986. };
  59987. /**
  59988. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59989. * If the mesh has no geometry, it is simply returned as it is.
  59990. * The `data` are either a numeric array either a Float32Array.
  59991. * No new underlying VertexBuffer object is created.
  59992. * 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.
  59993. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59994. *
  59995. * Possible `kind` values :
  59996. * - BABYLON.VertexBuffer.PositionKind
  59997. * - BABYLON.VertexBuffer.UVKind
  59998. * - BABYLON.VertexBuffer.UV2Kind
  59999. * - BABYLON.VertexBuffer.UV3Kind
  60000. * - BABYLON.VertexBuffer.UV4Kind
  60001. * - BABYLON.VertexBuffer.UV5Kind
  60002. * - BABYLON.VertexBuffer.UV6Kind
  60003. * - BABYLON.VertexBuffer.ColorKind
  60004. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60005. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60006. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60007. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60008. *
  60009. * Returns the Mesh.
  60010. */
  60011. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60012. if (this.sourceMesh) {
  60013. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60014. }
  60015. return this.sourceMesh;
  60016. };
  60017. /**
  60018. * Sets the mesh indices.
  60019. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60020. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60021. * This method creates a new index buffer each call.
  60022. * Returns the Mesh.
  60023. */
  60024. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60025. if (totalVertices === void 0) { totalVertices = null; }
  60026. if (this.sourceMesh) {
  60027. this.sourceMesh.setIndices(indices, totalVertices);
  60028. }
  60029. return this.sourceMesh;
  60030. };
  60031. /**
  60032. * Boolean : True if the mesh owns the requested kind of data.
  60033. */
  60034. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60035. return this._sourceMesh.isVerticesDataPresent(kind);
  60036. };
  60037. /**
  60038. * Returns an array of indices (IndicesArray).
  60039. */
  60040. InstancedMesh.prototype.getIndices = function () {
  60041. return this._sourceMesh.getIndices();
  60042. };
  60043. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60044. get: function () {
  60045. return this._sourceMesh._positions;
  60046. },
  60047. enumerable: true,
  60048. configurable: true
  60049. });
  60050. /**
  60051. * Sets a new updated BoundingInfo to the mesh.
  60052. * Returns the mesh.
  60053. */
  60054. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60055. var meshBB = this._sourceMesh.getBoundingInfo();
  60056. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60057. this._updateBoundingInfo();
  60058. return this;
  60059. };
  60060. /** @hidden */
  60061. InstancedMesh.prototype._preActivate = function () {
  60062. if (this._currentLOD) {
  60063. this._currentLOD._preActivate();
  60064. }
  60065. return this;
  60066. };
  60067. /** @hidden */
  60068. InstancedMesh.prototype._activate = function (renderId) {
  60069. if (this._currentLOD) {
  60070. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60071. }
  60072. return this;
  60073. };
  60074. /**
  60075. * Returns the current associated LOD AbstractMesh.
  60076. */
  60077. InstancedMesh.prototype.getLOD = function (camera) {
  60078. if (!camera) {
  60079. return this;
  60080. }
  60081. var boundingInfo = this.getBoundingInfo();
  60082. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60083. if (this._currentLOD === this.sourceMesh) {
  60084. return this;
  60085. }
  60086. return this._currentLOD;
  60087. };
  60088. /** @hidden */
  60089. InstancedMesh.prototype._syncSubMeshes = function () {
  60090. this.releaseSubMeshes();
  60091. if (this._sourceMesh.subMeshes) {
  60092. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60093. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60094. }
  60095. }
  60096. return this;
  60097. };
  60098. /** @hidden */
  60099. InstancedMesh.prototype._generatePointsArray = function () {
  60100. return this._sourceMesh._generatePointsArray();
  60101. };
  60102. /**
  60103. * Creates a new InstancedMesh from the current mesh.
  60104. * - name (string) : the cloned mesh name
  60105. * - newParent (optional Node) : the optional Node to parent the clone to.
  60106. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60107. *
  60108. * Returns the clone.
  60109. */
  60110. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60111. var result = this._sourceMesh.createInstance(name);
  60112. // Deep copy
  60113. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60114. // Bounding info
  60115. this.refreshBoundingInfo();
  60116. // Parent
  60117. if (newParent) {
  60118. result.parent = newParent;
  60119. }
  60120. if (!doNotCloneChildren) {
  60121. // Children
  60122. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60123. var mesh = this.getScene().meshes[index];
  60124. if (mesh.parent === this) {
  60125. mesh.clone(mesh.name, result);
  60126. }
  60127. }
  60128. }
  60129. result.computeWorldMatrix(true);
  60130. return result;
  60131. };
  60132. /**
  60133. * Disposes the InstancedMesh.
  60134. * Returns nothing.
  60135. */
  60136. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60137. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60138. // Remove from mesh
  60139. var index = this._sourceMesh.instances.indexOf(this);
  60140. this._sourceMesh.instances.splice(index, 1);
  60141. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60142. };
  60143. return InstancedMesh;
  60144. }(BABYLON.AbstractMesh));
  60145. BABYLON.InstancedMesh = InstancedMesh;
  60146. })(BABYLON || (BABYLON = {}));
  60147. //# sourceMappingURL=babylon.instancedMesh.js.map
  60148. var BABYLON;
  60149. (function (BABYLON) {
  60150. var LinesMesh = /** @class */ (function (_super) {
  60151. __extends(LinesMesh, _super);
  60152. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60153. if (scene === void 0) { scene = null; }
  60154. if (parent === void 0) { parent = null; }
  60155. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60156. _this.useVertexColor = useVertexColor;
  60157. _this.useVertexAlpha = useVertexAlpha;
  60158. _this.color = new BABYLON.Color3(1, 1, 1);
  60159. _this.alpha = 1;
  60160. if (source) {
  60161. _this.color = source.color.clone();
  60162. _this.alpha = source.alpha;
  60163. _this.useVertexColor = source.useVertexColor;
  60164. _this.useVertexAlpha = source.useVertexAlpha;
  60165. }
  60166. _this._intersectionThreshold = 0.1;
  60167. var defines = [];
  60168. var options = {
  60169. attributes: [BABYLON.VertexBuffer.PositionKind],
  60170. uniforms: ["world", "viewProjection"],
  60171. needAlphaBlending: true,
  60172. defines: defines
  60173. };
  60174. if (useVertexAlpha === false) {
  60175. options.needAlphaBlending = false;
  60176. }
  60177. if (!useVertexColor) {
  60178. options.uniforms.push("color");
  60179. }
  60180. else {
  60181. options.defines.push("#define VERTEXCOLOR");
  60182. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60183. }
  60184. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60185. return _this;
  60186. }
  60187. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60188. /**
  60189. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60190. * This margin is expressed in world space coordinates, so its value may vary.
  60191. * Default value is 0.1
  60192. * @returns the intersection Threshold value.
  60193. */
  60194. get: function () {
  60195. return this._intersectionThreshold;
  60196. },
  60197. /**
  60198. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60199. * This margin is expressed in world space coordinates, so its value may vary.
  60200. * @param value the new threshold to apply
  60201. */
  60202. set: function (value) {
  60203. if (this._intersectionThreshold === value) {
  60204. return;
  60205. }
  60206. this._intersectionThreshold = value;
  60207. if (this.geometry) {
  60208. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60209. }
  60210. },
  60211. enumerable: true,
  60212. configurable: true
  60213. });
  60214. /**
  60215. * Returns the string "LineMesh"
  60216. */
  60217. LinesMesh.prototype.getClassName = function () {
  60218. return "LinesMesh";
  60219. };
  60220. Object.defineProperty(LinesMesh.prototype, "material", {
  60221. /**
  60222. * @hidden
  60223. */
  60224. get: function () {
  60225. return this._colorShader;
  60226. },
  60227. /**
  60228. * @hidden
  60229. */
  60230. set: function (value) {
  60231. // Do nothing
  60232. },
  60233. enumerable: true,
  60234. configurable: true
  60235. });
  60236. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60237. /**
  60238. * @hidden
  60239. */
  60240. get: function () {
  60241. return false;
  60242. },
  60243. enumerable: true,
  60244. configurable: true
  60245. });
  60246. LinesMesh.prototype.createInstance = function (name) {
  60247. throw new Error("LinesMeshes do not support createInstance.");
  60248. };
  60249. /** @hidden */
  60250. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60251. if (!this._geometry) {
  60252. return this;
  60253. }
  60254. // VBOs
  60255. this._geometry._bind(this._colorShader.getEffect());
  60256. // Color
  60257. if (!this.useVertexColor) {
  60258. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60259. }
  60260. return this;
  60261. };
  60262. /** @hidden */
  60263. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60264. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60265. return this;
  60266. }
  60267. var engine = this.getScene().getEngine();
  60268. // Draw order
  60269. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60270. return this;
  60271. };
  60272. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60273. this._colorShader.dispose();
  60274. _super.prototype.dispose.call(this, doNotRecurse);
  60275. };
  60276. /**
  60277. * Returns a new LineMesh object cloned from the current one.
  60278. */
  60279. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60280. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60281. };
  60282. return LinesMesh;
  60283. }(BABYLON.Mesh));
  60284. BABYLON.LinesMesh = LinesMesh;
  60285. })(BABYLON || (BABYLON = {}));
  60286. //# sourceMappingURL=babylon.linesMesh.js.map
  60287. var BABYLON;
  60288. (function (BABYLON) {
  60289. /**
  60290. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60291. * The underlying implementation relies on an associative array to ensure the best performances.
  60292. * The value can be anything including 'null' but except 'undefined'
  60293. */
  60294. var StringDictionary = /** @class */ (function () {
  60295. function StringDictionary() {
  60296. this._count = 0;
  60297. this._data = {};
  60298. }
  60299. /**
  60300. * This will clear this dictionary and copy the content from the 'source' one.
  60301. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60302. * @param source the dictionary to take the content from and copy to this dictionary
  60303. */
  60304. StringDictionary.prototype.copyFrom = function (source) {
  60305. var _this = this;
  60306. this.clear();
  60307. source.forEach(function (t, v) { return _this.add(t, v); });
  60308. };
  60309. /**
  60310. * Get a value based from its key
  60311. * @param key the given key to get the matching value from
  60312. * @return the value if found, otherwise undefined is returned
  60313. */
  60314. StringDictionary.prototype.get = function (key) {
  60315. var val = this._data[key];
  60316. if (val !== undefined) {
  60317. return val;
  60318. }
  60319. return undefined;
  60320. };
  60321. /**
  60322. * Get a value from its key or add it if it doesn't exist.
  60323. * This method will ensure you that a given key/data will be present in the dictionary.
  60324. * @param key the given key to get the matching value from
  60325. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60326. * The factory will only be invoked if there's no data for the given key.
  60327. * @return the value corresponding to the key.
  60328. */
  60329. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60330. var val = this.get(key);
  60331. if (val !== undefined) {
  60332. return val;
  60333. }
  60334. val = factory(key);
  60335. if (val) {
  60336. this.add(key, val);
  60337. }
  60338. return val;
  60339. };
  60340. /**
  60341. * Get a value from its key if present in the dictionary otherwise add it
  60342. * @param key the key to get the value from
  60343. * @param val if there's no such key/value pair in the dictionary add it with this value
  60344. * @return the value corresponding to the key
  60345. */
  60346. StringDictionary.prototype.getOrAdd = function (key, val) {
  60347. var curVal = this.get(key);
  60348. if (curVal !== undefined) {
  60349. return curVal;
  60350. }
  60351. this.add(key, val);
  60352. return val;
  60353. };
  60354. /**
  60355. * Check if there's a given key in the dictionary
  60356. * @param key the key to check for
  60357. * @return true if the key is present, false otherwise
  60358. */
  60359. StringDictionary.prototype.contains = function (key) {
  60360. return this._data[key] !== undefined;
  60361. };
  60362. /**
  60363. * Add a new key and its corresponding value
  60364. * @param key the key to add
  60365. * @param value the value corresponding to the key
  60366. * @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
  60367. */
  60368. StringDictionary.prototype.add = function (key, value) {
  60369. if (this._data[key] !== undefined) {
  60370. return false;
  60371. }
  60372. this._data[key] = value;
  60373. ++this._count;
  60374. return true;
  60375. };
  60376. StringDictionary.prototype.set = function (key, value) {
  60377. if (this._data[key] === undefined) {
  60378. return false;
  60379. }
  60380. this._data[key] = value;
  60381. return true;
  60382. };
  60383. /**
  60384. * Get the element of the given key and remove it from the dictionary
  60385. * @param key
  60386. */
  60387. StringDictionary.prototype.getAndRemove = function (key) {
  60388. var val = this.get(key);
  60389. if (val !== undefined) {
  60390. delete this._data[key];
  60391. --this._count;
  60392. return val;
  60393. }
  60394. return null;
  60395. };
  60396. /**
  60397. * Remove a key/value from the dictionary.
  60398. * @param key the key to remove
  60399. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60400. */
  60401. StringDictionary.prototype.remove = function (key) {
  60402. if (this.contains(key)) {
  60403. delete this._data[key];
  60404. --this._count;
  60405. return true;
  60406. }
  60407. return false;
  60408. };
  60409. /**
  60410. * Clear the whole content of the dictionary
  60411. */
  60412. StringDictionary.prototype.clear = function () {
  60413. this._data = {};
  60414. this._count = 0;
  60415. };
  60416. Object.defineProperty(StringDictionary.prototype, "count", {
  60417. get: function () {
  60418. return this._count;
  60419. },
  60420. enumerable: true,
  60421. configurable: true
  60422. });
  60423. /**
  60424. * Execute a callback on each key/val of the dictionary.
  60425. * Note that you can remove any element in this dictionary in the callback implementation
  60426. * @param callback the callback to execute on a given key/value pair
  60427. */
  60428. StringDictionary.prototype.forEach = function (callback) {
  60429. for (var cur in this._data) {
  60430. var val = this._data[cur];
  60431. callback(cur, val);
  60432. }
  60433. };
  60434. /**
  60435. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60436. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60437. * Note that you can remove any element in this dictionary in the callback implementation
  60438. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60439. */
  60440. StringDictionary.prototype.first = function (callback) {
  60441. for (var cur in this._data) {
  60442. var val = this._data[cur];
  60443. var res = callback(cur, val);
  60444. if (res) {
  60445. return res;
  60446. }
  60447. }
  60448. return null;
  60449. };
  60450. return StringDictionary;
  60451. }());
  60452. BABYLON.StringDictionary = StringDictionary;
  60453. })(BABYLON || (BABYLON = {}));
  60454. //# sourceMappingURL=babylon.stringDictionary.js.map
  60455. var BABYLON;
  60456. (function (BABYLON) {
  60457. var Debug;
  60458. (function (Debug) {
  60459. /**
  60460. * Class used to render a debug view of a given skeleton
  60461. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  60462. */
  60463. var SkeletonViewer = /** @class */ (function () {
  60464. /**
  60465. * Creates a new SkeletonViewer
  60466. * @param skeleton defines the skeleton to render
  60467. * @param mesh defines the mesh attached to the skeleton
  60468. * @param scene defines the hosting scene
  60469. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  60470. * @param renderingGroupId defines the rendering group id to use with the viewer
  60471. */
  60472. function SkeletonViewer(
  60473. /** defines the skeleton to render */
  60474. skeleton,
  60475. /** defines the mesh attached to the skeleton */
  60476. mesh, scene,
  60477. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  60478. autoUpdateBonesMatrices,
  60479. /** defines the rendering group id to use with the viewer */
  60480. renderingGroupId) {
  60481. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  60482. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  60483. this.skeleton = skeleton;
  60484. this.mesh = mesh;
  60485. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  60486. this.renderingGroupId = renderingGroupId;
  60487. /** Gets or sets the color used to render the skeleton */
  60488. this.color = BABYLON.Color3.White();
  60489. this._debugLines = new Array();
  60490. this._isEnabled = false;
  60491. this._scene = scene;
  60492. this.update();
  60493. this._renderFunction = this.update.bind(this);
  60494. }
  60495. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  60496. get: function () {
  60497. return this._isEnabled;
  60498. },
  60499. /** Gets or sets a boolean indicating if the viewer is enabled */
  60500. set: function (value) {
  60501. if (this._isEnabled === value) {
  60502. return;
  60503. }
  60504. this._isEnabled = value;
  60505. if (value) {
  60506. this._scene.registerBeforeRender(this._renderFunction);
  60507. }
  60508. else {
  60509. this._scene.unregisterBeforeRender(this._renderFunction);
  60510. }
  60511. },
  60512. enumerable: true,
  60513. configurable: true
  60514. });
  60515. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  60516. if (x === void 0) { x = 0; }
  60517. if (y === void 0) { y = 0; }
  60518. if (z === void 0) { z = 0; }
  60519. var tmat = BABYLON.Tmp.Matrix[0];
  60520. var parentBone = bone.getParent();
  60521. tmat.copyFrom(bone.getLocalMatrix());
  60522. if (x !== 0 || y !== 0 || z !== 0) {
  60523. var tmat2 = BABYLON.Tmp.Matrix[1];
  60524. BABYLON.Matrix.IdentityToRef(tmat2);
  60525. tmat2.m[12] = x;
  60526. tmat2.m[13] = y;
  60527. tmat2.m[14] = z;
  60528. tmat2.multiplyToRef(tmat, tmat);
  60529. }
  60530. if (parentBone) {
  60531. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  60532. }
  60533. tmat.multiplyToRef(meshMat, tmat);
  60534. position.x = tmat.m[12];
  60535. position.y = tmat.m[13];
  60536. position.z = tmat.m[14];
  60537. };
  60538. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  60539. var len = bones.length;
  60540. var meshPos = this.mesh.position;
  60541. for (var i = 0; i < len; i++) {
  60542. var bone = bones[i];
  60543. var points = this._debugLines[i];
  60544. if (!points) {
  60545. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60546. this._debugLines[i] = points;
  60547. }
  60548. this._getBonePosition(points[0], bone, meshMat);
  60549. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  60550. points[0].subtractInPlace(meshPos);
  60551. points[1].subtractInPlace(meshPos);
  60552. }
  60553. };
  60554. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  60555. var len = bones.length;
  60556. var boneNum = 0;
  60557. var meshPos = this.mesh.position;
  60558. for (var i = len - 1; i >= 0; i--) {
  60559. var childBone = bones[i];
  60560. var parentBone = childBone.getParent();
  60561. if (!parentBone) {
  60562. continue;
  60563. }
  60564. var points = this._debugLines[boneNum];
  60565. if (!points) {
  60566. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60567. this._debugLines[boneNum] = points;
  60568. }
  60569. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  60570. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  60571. points[0].subtractInPlace(meshPos);
  60572. points[1].subtractInPlace(meshPos);
  60573. boneNum++;
  60574. }
  60575. };
  60576. /** Update the viewer to sync with current skeleton state */
  60577. SkeletonViewer.prototype.update = function () {
  60578. if (this.autoUpdateBonesMatrices) {
  60579. this.skeleton.computeAbsoluteTransforms();
  60580. }
  60581. if (this.skeleton.bones[0].length === undefined) {
  60582. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60583. }
  60584. else {
  60585. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60586. }
  60587. if (!this._debugMesh) {
  60588. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  60589. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60590. }
  60591. else {
  60592. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60593. }
  60594. this._debugMesh.position.copyFrom(this.mesh.position);
  60595. this._debugMesh.color = this.color;
  60596. };
  60597. /** Release associated resources */
  60598. SkeletonViewer.prototype.dispose = function () {
  60599. if (this._debugMesh) {
  60600. this.isEnabled = false;
  60601. this._debugMesh.dispose();
  60602. this._debugMesh = null;
  60603. }
  60604. };
  60605. return SkeletonViewer;
  60606. }());
  60607. Debug.SkeletonViewer = SkeletonViewer;
  60608. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60609. })(BABYLON || (BABYLON = {}));
  60610. //# sourceMappingURL=babylon.skeletonViewer.js.map
  60611. /**
  60612. * Module Debug contains the (visual) components to debug a scene correctly
  60613. */
  60614. var BABYLON;
  60615. (function (BABYLON) {
  60616. var Debug;
  60617. (function (Debug) {
  60618. /**
  60619. * The Axes viewer will show 3 axes in a specific point in space
  60620. */
  60621. var AxesViewer = /** @class */ (function () {
  60622. /**
  60623. * Creates a new AxesViewer
  60624. * @param scene defines the hosting scene
  60625. * @param scaleLines defines a number used to scale line length (1 by default)
  60626. */
  60627. function AxesViewer(scene, scaleLines) {
  60628. if (scaleLines === void 0) { scaleLines = 1; }
  60629. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60630. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60631. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60632. /**
  60633. * Gets or sets a number used to scale line length
  60634. */
  60635. this.scaleLines = 1;
  60636. this.scaleLines = scaleLines;
  60637. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  60638. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  60639. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  60640. this._xmesh.renderingGroupId = 2;
  60641. this._ymesh.renderingGroupId = 2;
  60642. this._zmesh.renderingGroupId = 2;
  60643. this._xmesh.material.checkReadyOnlyOnce = true;
  60644. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  60645. this._ymesh.material.checkReadyOnlyOnce = true;
  60646. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  60647. this._zmesh.material.checkReadyOnlyOnce = true;
  60648. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  60649. this.scene = scene;
  60650. }
  60651. /**
  60652. * Force the viewer to update
  60653. * @param position defines the position of the viewer
  60654. * @param xaxis defines the x axis of the viewer
  60655. * @param yaxis defines the y axis of the viewer
  60656. * @param zaxis defines the z axis of the viewer
  60657. */
  60658. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  60659. var scaleLines = this.scaleLines;
  60660. if (this._xmesh) {
  60661. this._xmesh.position.copyFrom(position);
  60662. }
  60663. if (this._ymesh) {
  60664. this._ymesh.position.copyFrom(position);
  60665. }
  60666. if (this._zmesh) {
  60667. this._zmesh.position.copyFrom(position);
  60668. }
  60669. var point2 = this._xline[1];
  60670. point2.x = xaxis.x * scaleLines;
  60671. point2.y = xaxis.y * scaleLines;
  60672. point2.z = xaxis.z * scaleLines;
  60673. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  60674. point2 = this._yline[1];
  60675. point2.x = yaxis.x * scaleLines;
  60676. point2.y = yaxis.y * scaleLines;
  60677. point2.z = yaxis.z * scaleLines;
  60678. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  60679. point2 = this._zline[1];
  60680. point2.x = zaxis.x * scaleLines;
  60681. point2.y = zaxis.y * scaleLines;
  60682. point2.z = zaxis.z * scaleLines;
  60683. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  60684. };
  60685. /** Releases resources */
  60686. AxesViewer.prototype.dispose = function () {
  60687. if (this._xmesh) {
  60688. this._xmesh.dispose();
  60689. }
  60690. if (this._ymesh) {
  60691. this._ymesh.dispose();
  60692. }
  60693. if (this._zmesh) {
  60694. this._zmesh.dispose();
  60695. }
  60696. this._xmesh = null;
  60697. this._ymesh = null;
  60698. this._zmesh = null;
  60699. this.scene = null;
  60700. };
  60701. return AxesViewer;
  60702. }());
  60703. Debug.AxesViewer = AxesViewer;
  60704. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60705. })(BABYLON || (BABYLON = {}));
  60706. //# sourceMappingURL=babylon.axesViewer.js.map
  60707. var BABYLON;
  60708. (function (BABYLON) {
  60709. var Debug;
  60710. (function (Debug) {
  60711. /**
  60712. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  60713. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  60714. */
  60715. var BoneAxesViewer = /** @class */ (function (_super) {
  60716. __extends(BoneAxesViewer, _super);
  60717. /**
  60718. * Creates a new BoneAxesViewer
  60719. * @param scene defines the hosting scene
  60720. * @param bone defines the target bone
  60721. * @param mesh defines the target mesh
  60722. * @param scaleLines defines a scaling factor for line length (1 by default)
  60723. */
  60724. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  60725. if (scaleLines === void 0) { scaleLines = 1; }
  60726. var _this = _super.call(this, scene, scaleLines) || this;
  60727. /** Gets current position */
  60728. _this.pos = BABYLON.Vector3.Zero();
  60729. /** Gets direction of X axis */
  60730. _this.xaxis = BABYLON.Vector3.Zero();
  60731. /** Gets direction of Y axis */
  60732. _this.yaxis = BABYLON.Vector3.Zero();
  60733. /** Gets direction of Z axis */
  60734. _this.zaxis = BABYLON.Vector3.Zero();
  60735. _this.mesh = mesh;
  60736. _this.bone = bone;
  60737. return _this;
  60738. }
  60739. /**
  60740. * Force the viewer to update
  60741. */
  60742. BoneAxesViewer.prototype.update = function () {
  60743. if (!this.mesh || !this.bone) {
  60744. return;
  60745. }
  60746. var bone = this.bone;
  60747. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  60748. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  60749. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  60750. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  60751. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  60752. };
  60753. /** Releases resources */
  60754. BoneAxesViewer.prototype.dispose = function () {
  60755. if (this.mesh) {
  60756. this.mesh = null;
  60757. this.bone = null;
  60758. _super.prototype.dispose.call(this);
  60759. }
  60760. };
  60761. return BoneAxesViewer;
  60762. }(Debug.AxesViewer));
  60763. Debug.BoneAxesViewer = BoneAxesViewer;
  60764. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60765. })(BABYLON || (BABYLON = {}));
  60766. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  60767. var BABYLON;
  60768. (function (BABYLON) {
  60769. var RayHelper = /** @class */ (function () {
  60770. function RayHelper(ray) {
  60771. this.ray = ray;
  60772. }
  60773. RayHelper.CreateAndShow = function (ray, scene, color) {
  60774. var helper = new RayHelper(ray);
  60775. helper.show(scene, color);
  60776. return helper;
  60777. };
  60778. RayHelper.prototype.show = function (scene, color) {
  60779. if (!this._renderFunction && this.ray) {
  60780. var ray = this.ray;
  60781. this._renderFunction = this._render.bind(this);
  60782. this._scene = scene;
  60783. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  60784. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  60785. if (this._renderFunction) {
  60786. this._scene.registerBeforeRender(this._renderFunction);
  60787. }
  60788. }
  60789. if (color && this._renderLine) {
  60790. this._renderLine.color.copyFrom(color);
  60791. }
  60792. };
  60793. RayHelper.prototype.hide = function () {
  60794. if (this._renderFunction && this._scene) {
  60795. this._scene.unregisterBeforeRender(this._renderFunction);
  60796. this._scene = null;
  60797. this._renderFunction = null;
  60798. if (this._renderLine) {
  60799. this._renderLine.dispose();
  60800. this._renderLine = null;
  60801. }
  60802. this._renderPoints = [];
  60803. }
  60804. };
  60805. RayHelper.prototype._render = function () {
  60806. var ray = this.ray;
  60807. if (!ray) {
  60808. return;
  60809. }
  60810. var point = this._renderPoints[1];
  60811. var len = Math.min(ray.length, 1000000);
  60812. point.copyFrom(ray.direction);
  60813. point.scaleInPlace(len);
  60814. point.addInPlace(ray.origin);
  60815. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  60816. };
  60817. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  60818. this._attachedToMesh = mesh;
  60819. var ray = this.ray;
  60820. if (!ray) {
  60821. return;
  60822. }
  60823. if (!ray.direction) {
  60824. ray.direction = BABYLON.Vector3.Zero();
  60825. }
  60826. if (!ray.origin) {
  60827. ray.origin = BABYLON.Vector3.Zero();
  60828. }
  60829. if (length) {
  60830. ray.length = length;
  60831. }
  60832. if (!meshSpaceOrigin) {
  60833. meshSpaceOrigin = BABYLON.Vector3.Zero();
  60834. }
  60835. if (!meshSpaceDirection) {
  60836. // -1 so that this will work with Mesh.lookAt
  60837. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  60838. }
  60839. if (!this._meshSpaceDirection) {
  60840. this._meshSpaceDirection = meshSpaceDirection.clone();
  60841. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  60842. }
  60843. else {
  60844. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  60845. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  60846. }
  60847. if (!this._updateToMeshFunction) {
  60848. this._updateToMeshFunction = this._updateToMesh.bind(this);
  60849. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  60850. }
  60851. this._updateToMesh();
  60852. };
  60853. RayHelper.prototype.detachFromMesh = function () {
  60854. if (this._attachedToMesh) {
  60855. if (this._updateToMeshFunction) {
  60856. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  60857. }
  60858. this._attachedToMesh = null;
  60859. this._updateToMeshFunction = null;
  60860. }
  60861. };
  60862. RayHelper.prototype._updateToMesh = function () {
  60863. var ray = this.ray;
  60864. if (!this._attachedToMesh || !ray) {
  60865. return;
  60866. }
  60867. if (this._attachedToMesh._isDisposed) {
  60868. this.detachFromMesh();
  60869. return;
  60870. }
  60871. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  60872. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  60873. };
  60874. RayHelper.prototype.dispose = function () {
  60875. this.hide();
  60876. this.detachFromMesh();
  60877. this.ray = null;
  60878. };
  60879. return RayHelper;
  60880. }());
  60881. BABYLON.RayHelper = RayHelper;
  60882. })(BABYLON || (BABYLON = {}));
  60883. //# sourceMappingURL=babylon.rayHelper.js.map
  60884. var BABYLON;
  60885. (function (BABYLON) {
  60886. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  60887. get: function () {
  60888. if (!this._debugLayer) {
  60889. this._debugLayer = new DebugLayer(this);
  60890. }
  60891. return this._debugLayer;
  60892. },
  60893. enumerable: true,
  60894. configurable: true
  60895. });
  60896. var DebugLayer = /** @class */ (function () {
  60897. function DebugLayer(scene) {
  60898. var _this = this;
  60899. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60900. this.onPropertyChangedObservable = new BABYLON.Observable();
  60901. this._scene = scene;
  60902. this._scene.onDisposeObservable.add(function () {
  60903. // Debug layer
  60904. if (_this._scene._debugLayer) {
  60905. _this._scene._debugLayer.hide();
  60906. }
  60907. });
  60908. }
  60909. /** Creates the inspector window. */
  60910. DebugLayer.prototype._createInspector = function (config) {
  60911. if (config === void 0) { config = {}; }
  60912. var popup = config.popup || false;
  60913. var initialTab = config.initialTab || 0;
  60914. var parentElement = config.parentElement || null;
  60915. if (!this._inspector) {
  60916. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60917. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  60918. } // else nothing to do as instance is already created
  60919. };
  60920. DebugLayer.prototype.isVisible = function () {
  60921. if (!this._inspector) {
  60922. return false;
  60923. }
  60924. return true;
  60925. };
  60926. DebugLayer.prototype.hide = function () {
  60927. if (this._inspector) {
  60928. try {
  60929. this._inspector.dispose();
  60930. }
  60931. catch (e) {
  60932. // If the inspector has been removed directly from the inspector tool
  60933. }
  60934. this.onPropertyChangedObservable.clear();
  60935. this._inspector = null;
  60936. }
  60937. };
  60938. /**
  60939. *
  60940. * Launch the debugLayer.
  60941. *
  60942. * initialTab:
  60943. * | Value | Tab Name |
  60944. * | --- | --- |
  60945. * | 0 | Scene |
  60946. * | 1 | Console |
  60947. * | 2 | Stats |
  60948. * | 3 | Textures |
  60949. * | 4 | Mesh |
  60950. * | 5 | Light |
  60951. * | 6 | Material |
  60952. * | 7 | GLTF |
  60953. * | 8 | GUI |
  60954. * | 9 | Physics |
  60955. * | 10 | Camera |
  60956. * | 11 | Audio |
  60957. *
  60958. */
  60959. DebugLayer.prototype.show = function (config) {
  60960. if (config === void 0) { config = {}; }
  60961. if (typeof this.BJSINSPECTOR == 'undefined') {
  60962. // Load inspector and add it to the DOM
  60963. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  60964. }
  60965. else {
  60966. // Otherwise creates the inspector
  60967. this._createInspector(config);
  60968. }
  60969. };
  60970. /**
  60971. * Gets the active tab
  60972. * @return the index of the active tab or -1 if the inspector is hidden
  60973. */
  60974. DebugLayer.prototype.getActiveTab = function () {
  60975. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  60976. };
  60977. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  60978. return DebugLayer;
  60979. }());
  60980. BABYLON.DebugLayer = DebugLayer;
  60981. })(BABYLON || (BABYLON = {}));
  60982. //# sourceMappingURL=babylon.debugLayer.js.map
  60983. var BABYLON;
  60984. (function (BABYLON) {
  60985. var Debug;
  60986. (function (Debug) {
  60987. /**
  60988. * Used to show the physics impostor around the specific mesh
  60989. */
  60990. var PhysicsViewer = /** @class */ (function () {
  60991. /**
  60992. * Creates a new PhysicsViewer
  60993. * @param scene defines the hosting scene
  60994. */
  60995. function PhysicsViewer(scene) {
  60996. /** @hidden */
  60997. this._impostors = [];
  60998. /** @hidden */
  60999. this._meshes = [];
  61000. /** @hidden */
  61001. this._numMeshes = 0;
  61002. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61003. var physicEngine = this._scene.getPhysicsEngine();
  61004. if (physicEngine) {
  61005. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  61006. }
  61007. }
  61008. /** @hidden */
  61009. PhysicsViewer.prototype._updateDebugMeshes = function () {
  61010. var plugin = this._physicsEnginePlugin;
  61011. for (var i = 0; i < this._numMeshes; i++) {
  61012. var impostor = this._impostors[i];
  61013. if (!impostor) {
  61014. continue;
  61015. }
  61016. if (impostor.isDisposed) {
  61017. this.hideImpostor(this._impostors[i--]);
  61018. }
  61019. else {
  61020. var mesh = this._meshes[i];
  61021. if (mesh && plugin) {
  61022. plugin.syncMeshWithImpostor(mesh, impostor);
  61023. }
  61024. }
  61025. }
  61026. };
  61027. /**
  61028. * Renders a specified physic impostor
  61029. * @param impostor defines the impostor to render
  61030. */
  61031. PhysicsViewer.prototype.showImpostor = function (impostor) {
  61032. if (!this._scene) {
  61033. return;
  61034. }
  61035. for (var i = 0; i < this._numMeshes; i++) {
  61036. if (this._impostors[i] == impostor) {
  61037. return;
  61038. }
  61039. }
  61040. var debugMesh = this._getDebugMesh(impostor, this._scene);
  61041. if (debugMesh) {
  61042. this._impostors[this._numMeshes] = impostor;
  61043. this._meshes[this._numMeshes] = debugMesh;
  61044. if (this._numMeshes === 0) {
  61045. this._renderFunction = this._updateDebugMeshes.bind(this);
  61046. this._scene.registerBeforeRender(this._renderFunction);
  61047. }
  61048. this._numMeshes++;
  61049. }
  61050. };
  61051. /**
  61052. * Hides a specified physic impostor
  61053. * @param impostor defines the impostor to hide
  61054. */
  61055. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  61056. if (!impostor || !this._scene) {
  61057. return;
  61058. }
  61059. var removed = false;
  61060. for (var i = 0; i < this._numMeshes; i++) {
  61061. if (this._impostors[i] == impostor) {
  61062. var mesh = this._meshes[i];
  61063. if (!mesh) {
  61064. continue;
  61065. }
  61066. this._scene.removeMesh(mesh);
  61067. mesh.dispose();
  61068. this._numMeshes--;
  61069. if (this._numMeshes > 0) {
  61070. this._meshes[i] = this._meshes[this._numMeshes];
  61071. this._impostors[i] = this._impostors[this._numMeshes];
  61072. this._meshes[this._numMeshes] = null;
  61073. this._impostors[this._numMeshes] = null;
  61074. }
  61075. else {
  61076. this._meshes[0] = null;
  61077. this._impostors[0] = null;
  61078. }
  61079. removed = true;
  61080. break;
  61081. }
  61082. }
  61083. if (removed && this._numMeshes === 0) {
  61084. this._scene.unregisterBeforeRender(this._renderFunction);
  61085. }
  61086. };
  61087. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  61088. if (!this._debugMaterial) {
  61089. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  61090. this._debugMaterial.wireframe = true;
  61091. }
  61092. return this._debugMaterial;
  61093. };
  61094. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  61095. if (!this._debugBoxMesh) {
  61096. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  61097. this._debugBoxMesh.renderingGroupId = 1;
  61098. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61099. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  61100. scene.removeMesh(this._debugBoxMesh);
  61101. }
  61102. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  61103. };
  61104. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  61105. if (!this._debugSphereMesh) {
  61106. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  61107. this._debugSphereMesh.renderingGroupId = 1;
  61108. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61109. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  61110. scene.removeMesh(this._debugSphereMesh);
  61111. }
  61112. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  61113. };
  61114. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  61115. var mesh = null;
  61116. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  61117. mesh = this._getDebugBoxMesh(scene);
  61118. impostor.getBoxSizeToRef(mesh.scaling);
  61119. }
  61120. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  61121. mesh = this._getDebugSphereMesh(scene);
  61122. var radius = impostor.getRadius();
  61123. mesh.scaling.x = radius * 2;
  61124. mesh.scaling.y = radius * 2;
  61125. mesh.scaling.z = radius * 2;
  61126. }
  61127. return mesh;
  61128. };
  61129. /** Releases all resources */
  61130. PhysicsViewer.prototype.dispose = function () {
  61131. for (var i = 0; i < this._numMeshes; i++) {
  61132. this.hideImpostor(this._impostors[i]);
  61133. }
  61134. if (this._debugBoxMesh) {
  61135. this._debugBoxMesh.dispose();
  61136. }
  61137. if (this._debugSphereMesh) {
  61138. this._debugSphereMesh.dispose();
  61139. }
  61140. if (this._debugMaterial) {
  61141. this._debugMaterial.dispose();
  61142. }
  61143. this._impostors.length = 0;
  61144. this._scene = null;
  61145. this._physicsEnginePlugin = null;
  61146. };
  61147. return PhysicsViewer;
  61148. }());
  61149. Debug.PhysicsViewer = PhysicsViewer;
  61150. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61151. })(BABYLON || (BABYLON = {}));
  61152. //# sourceMappingURL=babylon.physicsViewer.js.map
  61153. var BABYLON;
  61154. (function (BABYLON) {
  61155. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  61156. get: function () {
  61157. return this._forceShowBoundingBoxes || false;
  61158. },
  61159. set: function (value) {
  61160. this._forceShowBoundingBoxes = value;
  61161. // Lazyly creates a BB renderer if needed.
  61162. if (value) {
  61163. this.getBoundingBoxRenderer();
  61164. }
  61165. },
  61166. enumerable: true,
  61167. configurable: true
  61168. });
  61169. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  61170. if (!this._boundingBoxRenderer) {
  61171. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  61172. }
  61173. return this._boundingBoxRenderer;
  61174. };
  61175. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  61176. get: function () {
  61177. return this._showBoundingBox || false;
  61178. },
  61179. set: function (value) {
  61180. this._showBoundingBox = value;
  61181. // Lazyly creates a BB renderer if needed.
  61182. if (value) {
  61183. this.getScene().getBoundingBoxRenderer();
  61184. }
  61185. },
  61186. enumerable: true,
  61187. configurable: true
  61188. });
  61189. var BoundingBoxRenderer = /** @class */ (function () {
  61190. function BoundingBoxRenderer(scene) {
  61191. /**
  61192. * The component name helpfull to identify the component in the list of scene components.
  61193. */
  61194. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  61195. this.frontColor = new BABYLON.Color3(1, 1, 1);
  61196. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  61197. this.showBackLines = true;
  61198. this.renderList = new BABYLON.SmartArray(32);
  61199. this._vertexBuffers = {};
  61200. this.scene = scene;
  61201. scene._addComponent(this);
  61202. }
  61203. /**
  61204. * Registers the component in a given scene
  61205. */
  61206. BoundingBoxRenderer.prototype.register = function () {
  61207. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  61208. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  61209. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  61210. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  61211. };
  61212. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  61213. if (mesh.showSubMeshesBoundingBox) {
  61214. var boundingInfo = subMesh.getBoundingInfo();
  61215. if (boundingInfo !== null && boundingInfo !== undefined) {
  61216. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  61217. this.renderList.push(boundingInfo.boundingBox);
  61218. }
  61219. }
  61220. };
  61221. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  61222. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  61223. var boundingInfo = sourceMesh.getBoundingInfo();
  61224. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  61225. this.renderList.push(boundingInfo.boundingBox);
  61226. }
  61227. };
  61228. BoundingBoxRenderer.prototype._prepareRessources = function () {
  61229. if (this._colorShader) {
  61230. return;
  61231. }
  61232. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  61233. attributes: [BABYLON.VertexBuffer.PositionKind],
  61234. uniforms: ["world", "viewProjection", "color"]
  61235. });
  61236. var engine = this.scene.getEngine();
  61237. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  61238. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  61239. this._createIndexBuffer();
  61240. };
  61241. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  61242. var engine = this.scene.getEngine();
  61243. 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]);
  61244. };
  61245. /**
  61246. * Rebuilds the elements related to this component in case of
  61247. * context lost for instance.
  61248. */
  61249. BoundingBoxRenderer.prototype.rebuild = function () {
  61250. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61251. if (vb) {
  61252. vb._rebuild();
  61253. }
  61254. this._createIndexBuffer();
  61255. };
  61256. BoundingBoxRenderer.prototype.reset = function () {
  61257. this.renderList.reset();
  61258. };
  61259. /**
  61260. * Render the bounding boxes of a specific rendering group
  61261. * @param renderingGroupId defines the rendering group to render
  61262. */
  61263. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  61264. if (this.renderList.length === 0) {
  61265. return;
  61266. }
  61267. this._prepareRessources();
  61268. if (!this._colorShader.isReady()) {
  61269. return;
  61270. }
  61271. var engine = this.scene.getEngine();
  61272. engine.setDepthWrite(false);
  61273. this._colorShader._preBind();
  61274. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  61275. var boundingBox = this.renderList.data[boundingBoxIndex];
  61276. if (boundingBox._tag !== renderingGroupId) {
  61277. continue;
  61278. }
  61279. var min = boundingBox.minimum;
  61280. var max = boundingBox.maximum;
  61281. var diff = max.subtract(min);
  61282. var median = min.add(diff.scale(0.5));
  61283. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61284. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61285. .multiply(boundingBox.getWorldMatrix());
  61286. // VBOs
  61287. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61288. if (this.showBackLines) {
  61289. // Back
  61290. engine.setDepthFunctionToGreaterOrEqual();
  61291. this.scene.resetCachedMaterial();
  61292. this._colorShader.setColor4("color", this.backColor.toColor4());
  61293. this._colorShader.bind(worldMatrix);
  61294. // Draw order
  61295. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61296. }
  61297. // Front
  61298. engine.setDepthFunctionToLess();
  61299. this.scene.resetCachedMaterial();
  61300. this._colorShader.setColor4("color", this.frontColor.toColor4());
  61301. this._colorShader.bind(worldMatrix);
  61302. // Draw order
  61303. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61304. }
  61305. this._colorShader.unbind();
  61306. engine.setDepthFunctionToLessOrEqual();
  61307. engine.setDepthWrite(true);
  61308. };
  61309. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  61310. this._prepareRessources();
  61311. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  61312. return;
  61313. }
  61314. var engine = this.scene.getEngine();
  61315. engine.setDepthWrite(false);
  61316. engine.setColorWrite(false);
  61317. this._colorShader._preBind();
  61318. var boundingBox = mesh._boundingInfo.boundingBox;
  61319. var min = boundingBox.minimum;
  61320. var max = boundingBox.maximum;
  61321. var diff = max.subtract(min);
  61322. var median = min.add(diff.scale(0.5));
  61323. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61324. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61325. .multiply(boundingBox.getWorldMatrix());
  61326. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61327. engine.setDepthFunctionToLess();
  61328. this.scene.resetCachedMaterial();
  61329. this._colorShader.bind(worldMatrix);
  61330. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61331. this._colorShader.unbind();
  61332. engine.setDepthFunctionToLessOrEqual();
  61333. engine.setDepthWrite(true);
  61334. engine.setColorWrite(true);
  61335. };
  61336. BoundingBoxRenderer.prototype.dispose = function () {
  61337. if (!this._colorShader) {
  61338. return;
  61339. }
  61340. this.renderList.dispose();
  61341. this._colorShader.dispose();
  61342. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61343. if (buffer) {
  61344. buffer.dispose();
  61345. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61346. }
  61347. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  61348. };
  61349. return BoundingBoxRenderer;
  61350. }());
  61351. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  61352. })(BABYLON || (BABYLON = {}));
  61353. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  61354. var BABYLON;
  61355. (function (BABYLON) {
  61356. BABYLON.Engine.prototype.createTransformFeedback = function () {
  61357. return this._gl.createTransformFeedback();
  61358. };
  61359. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  61360. this._gl.deleteTransformFeedback(value);
  61361. };
  61362. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  61363. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  61364. };
  61365. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  61366. if (usePoints === void 0) { usePoints = true; }
  61367. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  61368. };
  61369. BABYLON.Engine.prototype.endTransformFeedback = function () {
  61370. this._gl.endTransformFeedback();
  61371. };
  61372. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  61373. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  61374. };
  61375. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  61376. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  61377. };
  61378. })(BABYLON || (BABYLON = {}));
  61379. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  61380. var BABYLON;
  61381. (function (BABYLON) {
  61382. /**
  61383. * This represents a GPU particle system in Babylon
  61384. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  61385. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  61386. */
  61387. var GPUParticleSystem = /** @class */ (function (_super) {
  61388. __extends(GPUParticleSystem, _super);
  61389. /**
  61390. * Instantiates a GPU particle system.
  61391. * 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.
  61392. * @param name The name of the particle system
  61393. * @param options The options used to create the system
  61394. * @param scene The scene the particle system belongs to
  61395. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  61396. */
  61397. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  61398. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61399. var _this = _super.call(this, name) || this;
  61400. /**
  61401. * The layer mask we are rendering the particles through.
  61402. */
  61403. _this.layerMask = 0x0FFFFFFF;
  61404. _this._accumulatedCount = 0;
  61405. _this._targetIndex = 0;
  61406. _this._currentRenderId = -1;
  61407. _this._started = false;
  61408. _this._stopped = false;
  61409. _this._timeDelta = 0;
  61410. _this._attributesStrideSize = 21;
  61411. _this._actualFrame = 0;
  61412. _this._rawTextureWidth = 256;
  61413. /**
  61414. * An event triggered when the system is disposed.
  61415. */
  61416. _this.onDisposeObservable = new BABYLON.Observable();
  61417. /**
  61418. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  61419. * to override the particles.
  61420. */
  61421. _this.forceDepthWrite = false;
  61422. _this._preWarmDone = false;
  61423. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61424. // Setup the default processing configuration to the scene.
  61425. _this._attachImageProcessingConfiguration(null);
  61426. _this._engine = _this._scene.getEngine();
  61427. if (!options.randomTextureSize) {
  61428. delete options.randomTextureSize;
  61429. }
  61430. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  61431. var optionsAsNumber = options;
  61432. if (isFinite(optionsAsNumber)) {
  61433. fullOptions.capacity = optionsAsNumber;
  61434. }
  61435. _this._capacity = fullOptions.capacity;
  61436. _this._activeCount = fullOptions.capacity;
  61437. _this._currentActiveCount = 0;
  61438. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  61439. _this._scene.particleSystems.push(_this);
  61440. _this._updateEffectOptions = {
  61441. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  61442. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  61443. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  61444. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  61445. uniformBuffersNames: [],
  61446. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  61447. defines: "",
  61448. fallbacks: null,
  61449. onCompiled: null,
  61450. onError: null,
  61451. indexParameters: null,
  61452. maxSimultaneousLights: 0,
  61453. transformFeedbackVaryings: []
  61454. };
  61455. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  61456. // Random data
  61457. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  61458. var d = [];
  61459. for (var i = 0; i < maxTextureSize; ++i) {
  61460. d.push(Math.random());
  61461. d.push(Math.random());
  61462. d.push(Math.random());
  61463. d.push(Math.random());
  61464. }
  61465. _this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, _this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  61466. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61467. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61468. d = [];
  61469. for (var i = 0; i < maxTextureSize; ++i) {
  61470. d.push(Math.random());
  61471. d.push(Math.random());
  61472. d.push(Math.random());
  61473. d.push(Math.random());
  61474. }
  61475. _this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, _this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  61476. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61477. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61478. _this._randomTextureSize = maxTextureSize;
  61479. return _this;
  61480. }
  61481. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  61482. /**
  61483. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  61484. */
  61485. get: function () {
  61486. if (!BABYLON.Engine.LastCreatedEngine) {
  61487. return false;
  61488. }
  61489. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  61490. },
  61491. enumerable: true,
  61492. configurable: true
  61493. });
  61494. /**
  61495. * Gets the maximum number of particles active at the same time.
  61496. * @returns The max number of active particles.
  61497. */
  61498. GPUParticleSystem.prototype.getCapacity = function () {
  61499. return this._capacity;
  61500. };
  61501. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  61502. /**
  61503. * Gets or set the number of active particles
  61504. */
  61505. get: function () {
  61506. return this._activeCount;
  61507. },
  61508. set: function (value) {
  61509. this._activeCount = Math.min(value, this._capacity);
  61510. },
  61511. enumerable: true,
  61512. configurable: true
  61513. });
  61514. /**
  61515. * Is this system ready to be used/rendered
  61516. * @return true if the system is ready
  61517. */
  61518. GPUParticleSystem.prototype.isReady = function () {
  61519. if (!this._updateEffect) {
  61520. this._recreateUpdateEffect();
  61521. this._recreateRenderEffect();
  61522. return false;
  61523. }
  61524. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  61525. return false;
  61526. }
  61527. return true;
  61528. };
  61529. /**
  61530. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61531. * @returns True if it has been started, otherwise false.
  61532. */
  61533. GPUParticleSystem.prototype.isStarted = function () {
  61534. return this._started;
  61535. };
  61536. /**
  61537. * Starts the particle system and begins to emit
  61538. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  61539. */
  61540. GPUParticleSystem.prototype.start = function (delay) {
  61541. var _this = this;
  61542. if (delay === void 0) { delay = this.startDelay; }
  61543. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  61544. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  61545. }
  61546. if (delay) {
  61547. setTimeout(function () {
  61548. _this.start(0);
  61549. }, delay);
  61550. return;
  61551. }
  61552. this._started = true;
  61553. this._stopped = false;
  61554. this._preWarmDone = false;
  61555. };
  61556. /**
  61557. * Stops the particle system.
  61558. */
  61559. GPUParticleSystem.prototype.stop = function () {
  61560. this._stopped = true;
  61561. };
  61562. /**
  61563. * Remove all active particles
  61564. */
  61565. GPUParticleSystem.prototype.reset = function () {
  61566. this._releaseBuffers();
  61567. this._releaseVAOs();
  61568. this._currentActiveCount = 0;
  61569. this._targetIndex = 0;
  61570. };
  61571. /**
  61572. * Returns the string "GPUParticleSystem"
  61573. * @returns a string containing the class name
  61574. */
  61575. GPUParticleSystem.prototype.getClassName = function () {
  61576. return "GPUParticleSystem";
  61577. };
  61578. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  61579. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  61580. this._releaseBuffers();
  61581. return this;
  61582. };
  61583. /**
  61584. * Adds a new color gradient
  61585. * @param gradient defines the gradient to use (between 0 and 1)
  61586. * @param color defines the color to affect to the specified gradient
  61587. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61588. * @returns the current particle system
  61589. */
  61590. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61591. if (!this._colorGradients) {
  61592. this._colorGradients = [];
  61593. }
  61594. var colorGradient = new BABYLON.ColorGradient();
  61595. colorGradient.gradient = gradient;
  61596. colorGradient.color1 = color1;
  61597. this._colorGradients.push(colorGradient);
  61598. this._colorGradients.sort(function (a, b) {
  61599. if (a.gradient < b.gradient) {
  61600. return -1;
  61601. }
  61602. else if (a.gradient > b.gradient) {
  61603. return 1;
  61604. }
  61605. return 0;
  61606. });
  61607. if (this._colorGradientsTexture) {
  61608. this._colorGradientsTexture.dispose();
  61609. this._colorGradientsTexture = null;
  61610. }
  61611. this._releaseBuffers();
  61612. return this;
  61613. };
  61614. /**
  61615. * Remove a specific color gradient
  61616. * @param gradient defines the gradient to remove
  61617. * @returns the current particle system
  61618. */
  61619. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  61620. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  61621. this._colorGradientsTexture = null;
  61622. return this;
  61623. };
  61624. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  61625. var valueGradient = new BABYLON.FactorGradient();
  61626. valueGradient.gradient = gradient;
  61627. valueGradient.factor1 = factor;
  61628. factorGradients.push(valueGradient);
  61629. factorGradients.sort(function (a, b) {
  61630. if (a.gradient < b.gradient) {
  61631. return -1;
  61632. }
  61633. else if (a.gradient > b.gradient) {
  61634. return 1;
  61635. }
  61636. return 0;
  61637. });
  61638. this._releaseBuffers();
  61639. };
  61640. /**
  61641. * Adds a new size gradient
  61642. * @param gradient defines the gradient to use (between 0 and 1)
  61643. * @param factor defines the size factor to affect to the specified gradient
  61644. * @returns the current particle system
  61645. */
  61646. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  61647. if (!this._sizeGradients) {
  61648. this._sizeGradients = [];
  61649. }
  61650. this._addFactorGradient(this._sizeGradients, gradient, factor);
  61651. if (this._sizeGradientsTexture) {
  61652. this._sizeGradientsTexture.dispose();
  61653. this._sizeGradientsTexture = null;
  61654. }
  61655. this._releaseBuffers();
  61656. return this;
  61657. };
  61658. /**
  61659. * Remove a specific size gradient
  61660. * @param gradient defines the gradient to remove
  61661. * @returns the current particle system
  61662. */
  61663. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  61664. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  61665. this._sizeGradientsTexture = null;
  61666. return this;
  61667. };
  61668. /**
  61669. * Adds a new angular speed gradient
  61670. * @param gradient defines the gradient to use (between 0 and 1)
  61671. * @param factor defines the angular speed to affect to the specified gradient
  61672. * @returns the current particle system
  61673. */
  61674. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  61675. if (!this._angularSpeedGradients) {
  61676. this._angularSpeedGradients = [];
  61677. }
  61678. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  61679. if (this._angularSpeedGradientsTexture) {
  61680. this._angularSpeedGradientsTexture.dispose();
  61681. this._angularSpeedGradientsTexture = null;
  61682. }
  61683. this._releaseBuffers();
  61684. return this;
  61685. };
  61686. /**
  61687. * Remove a specific angular speed gradient
  61688. * @param gradient defines the gradient to remove
  61689. * @returns the current particle system
  61690. */
  61691. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  61692. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  61693. this._angularSpeedGradientsTexture = null;
  61694. return this;
  61695. };
  61696. /**
  61697. * Adds a new velocity gradient
  61698. * @param gradient defines the gradient to use (between 0 and 1)
  61699. * @param factor defines the velocity to affect to the specified gradient
  61700. * @returns the current particle system
  61701. */
  61702. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  61703. if (!this._velocityGradients) {
  61704. this._velocityGradients = [];
  61705. }
  61706. this._addFactorGradient(this._velocityGradients, gradient, factor);
  61707. if (this._velocityGradientsTexture) {
  61708. this._velocityGradientsTexture.dispose();
  61709. this._velocityGradientsTexture = null;
  61710. }
  61711. this._releaseBuffers();
  61712. return this;
  61713. };
  61714. /**
  61715. * Remove a specific velocity gradient
  61716. * @param gradient defines the gradient to remove
  61717. * @returns the current particle system
  61718. */
  61719. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  61720. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  61721. this._velocityGradientsTexture = null;
  61722. return this;
  61723. };
  61724. /**
  61725. * Adds a new limit velocity gradient
  61726. * @param gradient defines the gradient to use (between 0 and 1)
  61727. * @param factor defines the limit velocity value to affect to the specified gradient
  61728. * @returns the current particle system
  61729. */
  61730. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  61731. if (!this._limitVelocityGradients) {
  61732. this._limitVelocityGradients = [];
  61733. }
  61734. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  61735. if (this._limitVelocityGradientsTexture) {
  61736. this._limitVelocityGradientsTexture.dispose();
  61737. this._limitVelocityGradientsTexture = null;
  61738. }
  61739. this._releaseBuffers();
  61740. return this;
  61741. };
  61742. /**
  61743. * Remove a specific limit velocity gradient
  61744. * @param gradient defines the gradient to remove
  61745. * @returns the current particle system
  61746. */
  61747. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  61748. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  61749. this._limitVelocityGradientsTexture = null;
  61750. return this;
  61751. };
  61752. /**
  61753. * Adds a new drag gradient
  61754. * @param gradient defines the gradient to use (between 0 and 1)
  61755. * @param factor defines the drag value to affect to the specified gradient
  61756. * @returns the current particle system
  61757. */
  61758. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  61759. if (!this._dragGradients) {
  61760. this._dragGradients = [];
  61761. }
  61762. this._addFactorGradient(this._dragGradients, gradient, factor);
  61763. if (this._dragGradientsTexture) {
  61764. this._dragGradientsTexture.dispose();
  61765. this._dragGradientsTexture = null;
  61766. }
  61767. this._releaseBuffers();
  61768. return this;
  61769. };
  61770. /**
  61771. * Remove a specific drag gradient
  61772. * @param gradient defines the gradient to remove
  61773. * @returns the current particle system
  61774. */
  61775. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  61776. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  61777. this._dragGradientsTexture = null;
  61778. return this;
  61779. };
  61780. /**
  61781. * Not supported by GPUParticleSystem
  61782. * @param gradient defines the gradient to use (between 0 and 1)
  61783. * @param factor defines the emit rate value to affect to the specified gradient
  61784. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61785. * @returns the current particle system
  61786. */
  61787. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  61788. // Do nothing as emit rate is not supported by GPUParticleSystem
  61789. return this;
  61790. };
  61791. /**
  61792. * Not supported by GPUParticleSystem
  61793. * @param gradient defines the gradient to remove
  61794. * @returns the current particle system
  61795. */
  61796. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  61797. // Do nothing as emit rate is not supported by GPUParticleSystem
  61798. return this;
  61799. };
  61800. /**
  61801. * Not supported by GPUParticleSystem
  61802. * @param gradient defines the gradient to use (between 0 and 1)
  61803. * @param factor defines the start size value to affect to the specified gradient
  61804. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61805. * @returns the current particle system
  61806. */
  61807. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  61808. // Do nothing as start size is not supported by GPUParticleSystem
  61809. return this;
  61810. };
  61811. /**
  61812. * Not supported by GPUParticleSystem
  61813. * @param gradient defines the gradient to remove
  61814. * @returns the current particle system
  61815. */
  61816. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  61817. // Do nothing as start size is not supported by GPUParticleSystem
  61818. return this;
  61819. };
  61820. /**
  61821. * Not supported by GPUParticleSystem
  61822. * @param gradient defines the gradient to use (between 0 and 1)
  61823. * @param min defines the color remap minimal range
  61824. * @param max defines the color remap maximal range
  61825. * @returns the current particle system
  61826. */
  61827. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  61828. // Do nothing as start size is not supported by GPUParticleSystem
  61829. return this;
  61830. };
  61831. /**
  61832. * Not supported by GPUParticleSystem
  61833. * @param gradient defines the gradient to remove
  61834. * @returns the current particle system
  61835. */
  61836. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  61837. // Do nothing as start size is not supported by GPUParticleSystem
  61838. return this;
  61839. };
  61840. /**
  61841. * Not supported by GPUParticleSystem
  61842. * @param gradient defines the gradient to use (between 0 and 1)
  61843. * @param min defines the alpha remap minimal range
  61844. * @param max defines the alpha remap maximal range
  61845. * @returns the current particle system
  61846. */
  61847. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  61848. // Do nothing as start size is not supported by GPUParticleSystem
  61849. return this;
  61850. };
  61851. /**
  61852. * Not supported by GPUParticleSystem
  61853. * @param gradient defines the gradient to remove
  61854. * @returns the current particle system
  61855. */
  61856. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  61857. // Do nothing as start size is not supported by GPUParticleSystem
  61858. return this;
  61859. };
  61860. /**
  61861. * Not supported by GPUParticleSystem
  61862. * @param gradient defines the gradient to use (between 0 and 1)
  61863. * @param color defines the color to affect to the specified gradient
  61864. * @returns the current particle system
  61865. */
  61866. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  61867. //Not supported by GPUParticleSystem
  61868. return this;
  61869. };
  61870. /**
  61871. * Not supported by GPUParticleSystem
  61872. * @param gradient defines the gradient to remove
  61873. * @returns the current particle system
  61874. */
  61875. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  61876. //Not supported by GPUParticleSystem
  61877. return this;
  61878. };
  61879. /**
  61880. * Not supported by GPUParticleSystem
  61881. * @returns the list of ramp gradients
  61882. */
  61883. GPUParticleSystem.prototype.getRampGradients = function () {
  61884. return null;
  61885. };
  61886. GPUParticleSystem.prototype._reset = function () {
  61887. this._releaseBuffers();
  61888. };
  61889. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  61890. var updateVertexBuffers = {};
  61891. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  61892. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  61893. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  61894. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  61895. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  61896. var offset = 12;
  61897. if (!this._colorGradientsTexture) {
  61898. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  61899. offset += 4;
  61900. }
  61901. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  61902. offset += 3;
  61903. if (!this._isBillboardBased) {
  61904. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  61905. offset += 3;
  61906. }
  61907. if (this._angularSpeedGradientsTexture) {
  61908. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  61909. offset += 1;
  61910. }
  61911. else {
  61912. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  61913. offset += 2;
  61914. }
  61915. if (this._isAnimationSheetEnabled) {
  61916. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  61917. offset += 1;
  61918. if (this.spriteRandomStartCell) {
  61919. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  61920. offset += 1;
  61921. }
  61922. }
  61923. if (this.noiseTexture) {
  61924. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  61925. offset += 3;
  61926. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  61927. offset += 3;
  61928. }
  61929. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  61930. this._engine.bindArrayBuffer(null);
  61931. return vao;
  61932. };
  61933. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  61934. var renderVertexBuffers = {};
  61935. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  61936. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  61937. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  61938. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  61939. var offset = 12;
  61940. if (!this._colorGradientsTexture) {
  61941. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  61942. offset += 4;
  61943. }
  61944. offset += 3; // Direction
  61945. if (!this._isBillboardBased) {
  61946. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  61947. offset += 3;
  61948. }
  61949. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  61950. if (this._angularSpeedGradientsTexture) {
  61951. offset++;
  61952. }
  61953. else {
  61954. offset += 2;
  61955. }
  61956. if (this._isAnimationSheetEnabled) {
  61957. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  61958. offset += 1;
  61959. if (this.spriteRandomStartCell) {
  61960. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  61961. offset += 1;
  61962. }
  61963. }
  61964. if (this.noiseTexture) {
  61965. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  61966. offset += 3;
  61967. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  61968. offset += 3;
  61969. }
  61970. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  61971. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  61972. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  61973. this._engine.bindArrayBuffer(null);
  61974. return vao;
  61975. };
  61976. GPUParticleSystem.prototype._initialize = function (force) {
  61977. if (force === void 0) { force = false; }
  61978. if (this._buffer0 && !force) {
  61979. return;
  61980. }
  61981. var engine = this._scene.getEngine();
  61982. var data = new Array();
  61983. if (!this.isBillboardBased) {
  61984. this._attributesStrideSize += 3;
  61985. }
  61986. if (this._colorGradientsTexture) {
  61987. this._attributesStrideSize -= 4;
  61988. }
  61989. if (this._angularSpeedGradientsTexture) {
  61990. this._attributesStrideSize -= 1;
  61991. }
  61992. if (this._isAnimationSheetEnabled) {
  61993. this._attributesStrideSize += 1;
  61994. if (this.spriteRandomStartCell) {
  61995. this._attributesStrideSize += 1;
  61996. }
  61997. }
  61998. if (this.noiseTexture) {
  61999. this._attributesStrideSize += 6;
  62000. }
  62001. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  62002. // position
  62003. data.push(0.0);
  62004. data.push(0.0);
  62005. data.push(0.0);
  62006. // Age and life
  62007. data.push(0.0); // create the particle as a dead one to create a new one at start
  62008. data.push(0.0);
  62009. // Seed
  62010. data.push(Math.random());
  62011. data.push(Math.random());
  62012. data.push(Math.random());
  62013. data.push(Math.random());
  62014. // Size
  62015. data.push(0.0);
  62016. data.push(0.0);
  62017. data.push(0.0);
  62018. if (!this._colorGradientsTexture) {
  62019. // color
  62020. data.push(0.0);
  62021. data.push(0.0);
  62022. data.push(0.0);
  62023. data.push(0.0);
  62024. }
  62025. // direction
  62026. data.push(0.0);
  62027. data.push(0.0);
  62028. data.push(0.0);
  62029. if (!this.isBillboardBased) {
  62030. // initialDirection
  62031. data.push(0.0);
  62032. data.push(0.0);
  62033. data.push(0.0);
  62034. }
  62035. // angle
  62036. data.push(0.0);
  62037. if (!this._angularSpeedGradientsTexture) {
  62038. data.push(0.0);
  62039. }
  62040. if (this._isAnimationSheetEnabled) {
  62041. data.push(0.0);
  62042. if (this.spriteRandomStartCell) {
  62043. data.push(0.0);
  62044. }
  62045. }
  62046. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  62047. data.push(Math.random());
  62048. data.push(Math.random());
  62049. data.push(Math.random());
  62050. data.push(Math.random());
  62051. data.push(Math.random());
  62052. data.push(Math.random());
  62053. }
  62054. }
  62055. // Sprite data
  62056. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  62057. -0.5, 0.5, 0, 1,
  62058. -0.5, -0.5, 0, 0,
  62059. 0.5, -0.5, 1, 0]);
  62060. // Buffers
  62061. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  62062. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  62063. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  62064. // Update VAO
  62065. this._updateVAO = [];
  62066. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  62067. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  62068. // Render VAO
  62069. this._renderVAO = [];
  62070. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  62071. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  62072. // Links
  62073. this._sourceBuffer = this._buffer0;
  62074. this._targetBuffer = this._buffer1;
  62075. };
  62076. /** @hidden */
  62077. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  62078. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  62079. if (this._isBillboardBased) {
  62080. defines += "\n#define BILLBOARD";
  62081. }
  62082. if (this._colorGradientsTexture) {
  62083. defines += "\n#define COLORGRADIENTS";
  62084. }
  62085. if (this._sizeGradientsTexture) {
  62086. defines += "\n#define SIZEGRADIENTS";
  62087. }
  62088. if (this._angularSpeedGradientsTexture) {
  62089. defines += "\n#define ANGULARSPEEDGRADIENTS";
  62090. }
  62091. if (this._velocityGradientsTexture) {
  62092. defines += "\n#define VELOCITYGRADIENTS";
  62093. }
  62094. if (this._limitVelocityGradientsTexture) {
  62095. defines += "\n#define LIMITVELOCITYGRADIENTS";
  62096. }
  62097. if (this._dragGradientsTexture) {
  62098. defines += "\n#define DRAGGRADIENTS";
  62099. }
  62100. if (this.isAnimationSheetEnabled) {
  62101. defines += "\n#define ANIMATESHEET";
  62102. if (this.spriteRandomStartCell) {
  62103. defines += "\n#define ANIMATESHEETRANDOMSTART";
  62104. }
  62105. }
  62106. if (this.noiseTexture) {
  62107. defines += "\n#define NOISE";
  62108. }
  62109. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  62110. return;
  62111. }
  62112. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  62113. if (!this._colorGradientsTexture) {
  62114. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  62115. }
  62116. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  62117. if (!this._isBillboardBased) {
  62118. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  62119. }
  62120. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  62121. if (this.isAnimationSheetEnabled) {
  62122. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  62123. if (this.spriteRandomStartCell) {
  62124. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  62125. }
  62126. }
  62127. if (this.noiseTexture) {
  62128. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  62129. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  62130. }
  62131. this._updateEffectOptions.defines = defines;
  62132. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  62133. };
  62134. /** @hidden */
  62135. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  62136. var defines = "";
  62137. if (this._scene.clipPlane) {
  62138. defines = "\n#define CLIPPLANE";
  62139. }
  62140. if (this._scene.clipPlane2) {
  62141. defines = "\n#define CLIPPLANE2";
  62142. }
  62143. if (this._scene.clipPlane3) {
  62144. defines = "\n#define CLIPPLANE3";
  62145. }
  62146. if (this._scene.clipPlane4) {
  62147. defines = "\n#define CLIPPLANE4";
  62148. }
  62149. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  62150. defines = "\n#define BLENDMULTIPLYMODE";
  62151. }
  62152. if (this._isBillboardBased) {
  62153. defines += "\n#define BILLBOARD";
  62154. switch (this.billboardMode) {
  62155. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  62156. defines += "\n#define BILLBOARDY";
  62157. break;
  62158. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  62159. default:
  62160. break;
  62161. }
  62162. }
  62163. if (this._colorGradientsTexture) {
  62164. defines += "\n#define COLORGRADIENTS";
  62165. }
  62166. if (this.isAnimationSheetEnabled) {
  62167. defines += "\n#define ANIMATESHEET";
  62168. }
  62169. if (this._imageProcessingConfiguration) {
  62170. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  62171. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  62172. }
  62173. if (this._renderEffect && this._renderEffect.defines === defines) {
  62174. return;
  62175. }
  62176. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  62177. var samplers = ["textureSampler", "colorGradientSampler"];
  62178. if (BABYLON.ImageProcessingConfiguration) {
  62179. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  62180. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  62181. }
  62182. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  62183. };
  62184. /**
  62185. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  62186. * @param preWarm defines if we are in the pre-warmimg phase
  62187. */
  62188. GPUParticleSystem.prototype.animate = function (preWarm) {
  62189. if (preWarm === void 0) { preWarm = false; }
  62190. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  62191. this._actualFrame += this._timeDelta;
  62192. if (!this._stopped) {
  62193. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  62194. this.stop();
  62195. }
  62196. }
  62197. };
  62198. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  62199. var texture = this[textureName];
  62200. if (!factorGradients || !factorGradients.length || texture) {
  62201. return;
  62202. }
  62203. var data = new Float32Array(this._rawTextureWidth);
  62204. for (var x = 0; x < this._rawTextureWidth; x++) {
  62205. var ratio = x / this._rawTextureWidth;
  62206. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  62207. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  62208. });
  62209. }
  62210. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62211. };
  62212. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  62213. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  62214. };
  62215. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  62216. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  62217. };
  62218. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  62219. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  62220. };
  62221. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  62222. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  62223. };
  62224. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  62225. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  62226. };
  62227. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  62228. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  62229. return;
  62230. }
  62231. var data = new Uint8Array(this._rawTextureWidth * 4);
  62232. var tmpColor = BABYLON.Tmp.Color4[0];
  62233. for (var x = 0; x < this._rawTextureWidth; x++) {
  62234. var ratio = x / this._rawTextureWidth;
  62235. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  62236. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  62237. data[x * 4] = tmpColor.r * 255;
  62238. data[x * 4 + 1] = tmpColor.g * 255;
  62239. data[x * 4 + 2] = tmpColor.b * 255;
  62240. data[x * 4 + 3] = tmpColor.a * 255;
  62241. });
  62242. }
  62243. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62244. };
  62245. /**
  62246. * Renders the particle system in its current state
  62247. * @param preWarm defines if the system should only update the particles but not render them
  62248. * @returns the current number of particles
  62249. */
  62250. GPUParticleSystem.prototype.render = function (preWarm) {
  62251. if (preWarm === void 0) { preWarm = false; }
  62252. if (!this._started) {
  62253. return 0;
  62254. }
  62255. this._createColorGradientTexture();
  62256. this._createSizeGradientTexture();
  62257. this._createAngularSpeedGradientTexture();
  62258. this._createVelocityGradientTexture();
  62259. this._createLimitVelocityGradientTexture();
  62260. this._createDragGradientTexture();
  62261. this._recreateUpdateEffect();
  62262. this._recreateRenderEffect();
  62263. if (!this.isReady()) {
  62264. return 0;
  62265. }
  62266. if (!preWarm) {
  62267. if (!this._preWarmDone && this.preWarmCycles) {
  62268. for (var index = 0; index < this.preWarmCycles; index++) {
  62269. this.animate(true);
  62270. this.render(true);
  62271. }
  62272. this._preWarmDone = true;
  62273. }
  62274. if (this._currentRenderId === this._scene.getRenderId()) {
  62275. return 0;
  62276. }
  62277. this._currentRenderId = this._scene.getRenderId();
  62278. }
  62279. // Get everything ready to render
  62280. this._initialize();
  62281. this._accumulatedCount += this.emitRate * this._timeDelta;
  62282. if (this._accumulatedCount > 1) {
  62283. var intPart = this._accumulatedCount | 0;
  62284. this._accumulatedCount -= intPart;
  62285. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  62286. }
  62287. if (!this._currentActiveCount) {
  62288. return 0;
  62289. }
  62290. // Enable update effect
  62291. this._engine.enableEffect(this._updateEffect);
  62292. this._engine.setState(false);
  62293. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  62294. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  62295. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  62296. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  62297. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  62298. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  62299. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  62300. if (!this._colorGradientsTexture) {
  62301. this._updateEffect.setDirectColor4("color1", this.color1);
  62302. this._updateEffect.setDirectColor4("color2", this.color2);
  62303. }
  62304. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  62305. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  62306. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  62307. this._updateEffect.setVector3("gravity", this.gravity);
  62308. if (this._sizeGradientsTexture) {
  62309. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  62310. }
  62311. if (this._angularSpeedGradientsTexture) {
  62312. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  62313. }
  62314. if (this._velocityGradientsTexture) {
  62315. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  62316. }
  62317. if (this._limitVelocityGradientsTexture) {
  62318. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  62319. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  62320. }
  62321. if (this._dragGradientsTexture) {
  62322. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  62323. }
  62324. if (this.particleEmitterType) {
  62325. this.particleEmitterType.applyToShader(this._updateEffect);
  62326. }
  62327. if (this._isAnimationSheetEnabled) {
  62328. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  62329. }
  62330. if (this.noiseTexture) {
  62331. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  62332. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  62333. }
  62334. var emitterWM;
  62335. if (this.emitter.position) {
  62336. var emitterMesh = this.emitter;
  62337. emitterWM = emitterMesh.getWorldMatrix();
  62338. }
  62339. else {
  62340. var emitterPosition = this.emitter;
  62341. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  62342. }
  62343. this._updateEffect.setMatrix("emitterWM", emitterWM);
  62344. // Bind source VAO
  62345. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  62346. // Update
  62347. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  62348. this._engine.setRasterizerState(false);
  62349. this._engine.beginTransformFeedback(true);
  62350. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  62351. this._engine.endTransformFeedback();
  62352. this._engine.setRasterizerState(true);
  62353. this._engine.bindTransformFeedbackBuffer(null);
  62354. if (!preWarm) {
  62355. // Enable render effect
  62356. this._engine.enableEffect(this._renderEffect);
  62357. var viewMatrix = this._scene.getViewMatrix();
  62358. this._renderEffect.setMatrix("view", viewMatrix);
  62359. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  62360. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  62361. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  62362. if (this._colorGradientsTexture) {
  62363. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  62364. }
  62365. else {
  62366. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  62367. }
  62368. if (this._isAnimationSheetEnabled && this.particleTexture) {
  62369. var baseSize = this.particleTexture.getBaseSize();
  62370. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  62371. }
  62372. if (this._isBillboardBased) {
  62373. var camera = this._scene.activeCamera;
  62374. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  62375. }
  62376. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  62377. var invView = viewMatrix.clone();
  62378. invView.invert();
  62379. this._renderEffect.setMatrix("invView", invView);
  62380. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  62381. }
  62382. // image processing
  62383. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  62384. this._imageProcessingConfiguration.bind(this._renderEffect);
  62385. }
  62386. // Draw order
  62387. switch (this.blendMode) {
  62388. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  62389. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  62390. break;
  62391. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  62392. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  62393. break;
  62394. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  62395. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62396. break;
  62397. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  62398. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  62399. break;
  62400. }
  62401. if (this.forceDepthWrite) {
  62402. this._engine.setDepthWrite(true);
  62403. }
  62404. // Bind source VAO
  62405. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  62406. // Render
  62407. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  62408. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62409. }
  62410. // Switch VAOs
  62411. this._targetIndex++;
  62412. if (this._targetIndex === 2) {
  62413. this._targetIndex = 0;
  62414. }
  62415. // Switch buffers
  62416. var tmpBuffer = this._sourceBuffer;
  62417. this._sourceBuffer = this._targetBuffer;
  62418. this._targetBuffer = tmpBuffer;
  62419. return this._currentActiveCount;
  62420. };
  62421. /**
  62422. * Rebuilds the particle system
  62423. */
  62424. GPUParticleSystem.prototype.rebuild = function () {
  62425. this._initialize(true);
  62426. };
  62427. GPUParticleSystem.prototype._releaseBuffers = function () {
  62428. if (this._buffer0) {
  62429. this._buffer0.dispose();
  62430. this._buffer0 = null;
  62431. }
  62432. if (this._buffer1) {
  62433. this._buffer1.dispose();
  62434. this._buffer1 = null;
  62435. }
  62436. if (this._spriteBuffer) {
  62437. this._spriteBuffer.dispose();
  62438. this._spriteBuffer = null;
  62439. }
  62440. };
  62441. GPUParticleSystem.prototype._releaseVAOs = function () {
  62442. if (!this._updateVAO) {
  62443. return;
  62444. }
  62445. for (var index = 0; index < this._updateVAO.length; index++) {
  62446. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  62447. }
  62448. this._updateVAO = [];
  62449. for (var index = 0; index < this._renderVAO.length; index++) {
  62450. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  62451. }
  62452. this._renderVAO = [];
  62453. };
  62454. /**
  62455. * Disposes the particle system and free the associated resources
  62456. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  62457. */
  62458. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  62459. if (disposeTexture === void 0) { disposeTexture = true; }
  62460. var index = this._scene.particleSystems.indexOf(this);
  62461. if (index > -1) {
  62462. this._scene.particleSystems.splice(index, 1);
  62463. }
  62464. this._releaseBuffers();
  62465. this._releaseVAOs();
  62466. if (this._colorGradientsTexture) {
  62467. this._colorGradientsTexture.dispose();
  62468. this._colorGradientsTexture = null;
  62469. }
  62470. if (this._sizeGradientsTexture) {
  62471. this._sizeGradientsTexture.dispose();
  62472. this._sizeGradientsTexture = null;
  62473. }
  62474. if (this._angularSpeedGradientsTexture) {
  62475. this._angularSpeedGradientsTexture.dispose();
  62476. this._angularSpeedGradientsTexture = null;
  62477. }
  62478. if (this._velocityGradientsTexture) {
  62479. this._velocityGradientsTexture.dispose();
  62480. this._velocityGradientsTexture = null;
  62481. }
  62482. if (this._limitVelocityGradientsTexture) {
  62483. this._limitVelocityGradientsTexture.dispose();
  62484. this._limitVelocityGradientsTexture = null;
  62485. }
  62486. if (this._dragGradientsTexture) {
  62487. this._dragGradientsTexture.dispose();
  62488. this._dragGradientsTexture = null;
  62489. }
  62490. if (this._randomTexture) {
  62491. this._randomTexture.dispose();
  62492. this._randomTexture = null;
  62493. }
  62494. if (this._randomTexture2) {
  62495. this._randomTexture2.dispose();
  62496. this._randomTexture2 = null;
  62497. }
  62498. if (disposeTexture && this.particleTexture) {
  62499. this.particleTexture.dispose();
  62500. this.particleTexture = null;
  62501. }
  62502. if (disposeTexture && this.noiseTexture) {
  62503. this.noiseTexture.dispose();
  62504. this.noiseTexture = null;
  62505. }
  62506. // Callback
  62507. this.onDisposeObservable.notifyObservers(this);
  62508. this.onDisposeObservable.clear();
  62509. };
  62510. /**
  62511. * Clones the particle system.
  62512. * @param name The name of the cloned object
  62513. * @param newEmitter The new emitter to use
  62514. * @returns the cloned particle system
  62515. */
  62516. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  62517. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  62518. BABYLON.Tools.DeepCopy(this, result);
  62519. if (newEmitter === undefined) {
  62520. newEmitter = this.emitter;
  62521. }
  62522. result.emitter = newEmitter;
  62523. if (this.particleTexture) {
  62524. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  62525. }
  62526. return result;
  62527. };
  62528. /**
  62529. * Serializes the particle system to a JSON object.
  62530. * @returns the JSON object
  62531. */
  62532. GPUParticleSystem.prototype.serialize = function () {
  62533. var serializationObject = {};
  62534. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  62535. serializationObject.activeParticleCount = this.activeParticleCount;
  62536. return serializationObject;
  62537. };
  62538. /**
  62539. * Parses a JSON object to create a GPU particle system.
  62540. * @param parsedParticleSystem The JSON object to parse
  62541. * @param scene The scene to create the particle system in
  62542. * @param rootUrl The root url to use to load external dependencies like texture
  62543. * @returns the parsed GPU particle system
  62544. */
  62545. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  62546. var name = parsedParticleSystem.name;
  62547. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  62548. if (parsedParticleSystem.activeParticleCount) {
  62549. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  62550. }
  62551. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  62552. return particleSystem;
  62553. };
  62554. return GPUParticleSystem;
  62555. }(BABYLON.BaseParticleSystem));
  62556. BABYLON.GPUParticleSystem = GPUParticleSystem;
  62557. })(BABYLON || (BABYLON = {}));
  62558. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  62559. var BABYLON;
  62560. (function (BABYLON) {
  62561. /**
  62562. * Represents one particle of a solid particle system.
  62563. */
  62564. var SolidParticle = /** @class */ (function () {
  62565. /**
  62566. * Creates a Solid Particle object.
  62567. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  62568. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  62569. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  62570. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  62571. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  62572. * @param shapeId (integer) is the model shape identifier in the SPS.
  62573. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  62574. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  62575. */
  62576. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  62577. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  62578. /**
  62579. * particle global index
  62580. */
  62581. this.idx = 0;
  62582. /**
  62583. * The color of the particle
  62584. */
  62585. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  62586. /**
  62587. * The world space position of the particle.
  62588. */
  62589. this.position = BABYLON.Vector3.Zero();
  62590. /**
  62591. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  62592. */
  62593. this.rotation = BABYLON.Vector3.Zero();
  62594. /**
  62595. * The scaling of the particle.
  62596. */
  62597. this.scaling = BABYLON.Vector3.One();
  62598. /**
  62599. * The uvs of the particle.
  62600. */
  62601. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  62602. /**
  62603. * The current speed of the particle.
  62604. */
  62605. this.velocity = BABYLON.Vector3.Zero();
  62606. /**
  62607. * The pivot point in the particle local space.
  62608. */
  62609. this.pivot = BABYLON.Vector3.Zero();
  62610. /**
  62611. * Must the particle be translated from its pivot point in its local space ?
  62612. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  62613. * Default : false
  62614. */
  62615. this.translateFromPivot = false;
  62616. /**
  62617. * Is the particle active or not ?
  62618. */
  62619. this.alive = true;
  62620. /**
  62621. * Is the particle visible or not ?
  62622. */
  62623. this.isVisible = true;
  62624. /**
  62625. * Index of this particle in the global "positions" array (Internal use)
  62626. * @hidden
  62627. */
  62628. this._pos = 0;
  62629. /**
  62630. * @hidden Index of this particle in the global "indices" array (Internal use)
  62631. */
  62632. this._ind = 0;
  62633. /**
  62634. * ModelShape id of this particle
  62635. */
  62636. this.shapeId = 0;
  62637. /**
  62638. * Index of the particle in its shape id (Internal use)
  62639. */
  62640. this.idxInShape = 0;
  62641. /**
  62642. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  62643. */
  62644. this._stillInvisible = false;
  62645. /**
  62646. * @hidden Last computed particle rotation matrix
  62647. */
  62648. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  62649. /**
  62650. * Parent particle Id, if any.
  62651. * Default null.
  62652. */
  62653. this.parentId = null;
  62654. /**
  62655. * @hidden Internal global position in the SPS.
  62656. */
  62657. this._globalPosition = BABYLON.Vector3.Zero();
  62658. this.idx = particleIndex;
  62659. this._pos = positionIndex;
  62660. this._ind = indiceIndex;
  62661. this._model = model;
  62662. this.shapeId = shapeId;
  62663. this.idxInShape = idxInShape;
  62664. this._sps = sps;
  62665. if (modelBoundingInfo) {
  62666. this._modelBoundingInfo = modelBoundingInfo;
  62667. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  62668. }
  62669. }
  62670. Object.defineProperty(SolidParticle.prototype, "scale", {
  62671. /**
  62672. * Legacy support, changed scale to scaling
  62673. */
  62674. get: function () {
  62675. return this.scaling;
  62676. },
  62677. /**
  62678. * Legacy support, changed scale to scaling
  62679. */
  62680. set: function (scale) {
  62681. this.scaling = scale;
  62682. },
  62683. enumerable: true,
  62684. configurable: true
  62685. });
  62686. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  62687. /**
  62688. * Legacy support, changed quaternion to rotationQuaternion
  62689. */
  62690. get: function () {
  62691. return this.rotationQuaternion;
  62692. },
  62693. /**
  62694. * Legacy support, changed quaternion to rotationQuaternion
  62695. */
  62696. set: function (q) {
  62697. this.rotationQuaternion = q;
  62698. },
  62699. enumerable: true,
  62700. configurable: true
  62701. });
  62702. /**
  62703. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  62704. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  62705. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  62706. * @returns true if it intersects
  62707. */
  62708. SolidParticle.prototype.intersectsMesh = function (target) {
  62709. if (!this._boundingInfo || !target._boundingInfo) {
  62710. return false;
  62711. }
  62712. if (this._sps._bSphereOnly) {
  62713. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  62714. }
  62715. return this._boundingInfo.intersects(target._boundingInfo, false);
  62716. };
  62717. return SolidParticle;
  62718. }());
  62719. BABYLON.SolidParticle = SolidParticle;
  62720. /**
  62721. * Represents the shape of the model used by one particle of a solid particle system.
  62722. * SPS internal tool, don't use it manually.
  62723. */
  62724. var ModelShape = /** @class */ (function () {
  62725. /**
  62726. * 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.
  62727. * SPS internal tool, don't use it manually.
  62728. * @hidden
  62729. */
  62730. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  62731. /**
  62732. * length of the shape in the model indices array (internal use)
  62733. * @hidden
  62734. */
  62735. this._indicesLength = 0;
  62736. this.shapeID = id;
  62737. this._shape = shape;
  62738. this._indicesLength = indicesLength;
  62739. this._shapeUV = shapeUV;
  62740. this._positionFunction = posFunction;
  62741. this._vertexFunction = vtxFunction;
  62742. }
  62743. return ModelShape;
  62744. }());
  62745. BABYLON.ModelShape = ModelShape;
  62746. /**
  62747. * Represents a Depth Sorted Particle in the solid particle system.
  62748. */
  62749. var DepthSortedParticle = /** @class */ (function () {
  62750. function DepthSortedParticle() {
  62751. /**
  62752. * Index of the particle in the "indices" array
  62753. */
  62754. this.ind = 0;
  62755. /**
  62756. * Length of the particle shape in the "indices" array
  62757. */
  62758. this.indicesLength = 0;
  62759. /**
  62760. * Squared distance from the particle to the camera
  62761. */
  62762. this.sqDistance = 0.0;
  62763. }
  62764. return DepthSortedParticle;
  62765. }());
  62766. BABYLON.DepthSortedParticle = DepthSortedParticle;
  62767. })(BABYLON || (BABYLON = {}));
  62768. //# sourceMappingURL=babylon.solidParticle.js.map
  62769. var BABYLON;
  62770. (function (BABYLON) {
  62771. /**
  62772. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  62773. *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.
  62774. * The SPS is also a particle system. It provides some methods to manage the particles.
  62775. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  62776. *
  62777. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  62778. */
  62779. var SolidParticleSystem = /** @class */ (function () {
  62780. /**
  62781. * Creates a SPS (Solid Particle System) object.
  62782. * @param name (String) is the SPS name, this will be the underlying mesh name.
  62783. * @param scene (Scene) is the scene in which the SPS is added.
  62784. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  62785. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  62786. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  62787. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  62788. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  62789. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  62790. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  62791. */
  62792. function SolidParticleSystem(name, scene, options) {
  62793. /**
  62794. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  62795. * Example : var p = SPS.particles[i];
  62796. */
  62797. this.particles = new Array();
  62798. /**
  62799. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  62800. */
  62801. this.nbParticles = 0;
  62802. /**
  62803. * If the particles must ever face the camera (default false). Useful for planar particles.
  62804. */
  62805. this.billboard = false;
  62806. /**
  62807. * Recompute normals when adding a shape
  62808. */
  62809. this.recomputeNormals = true;
  62810. /**
  62811. * This a counter ofr your own usage. It's not set by any SPS functions.
  62812. */
  62813. this.counter = 0;
  62814. /**
  62815. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  62816. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  62817. */
  62818. this.vars = {};
  62819. /**
  62820. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  62821. * @hidden
  62822. */
  62823. this._bSphereOnly = false;
  62824. /**
  62825. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  62826. * @hidden
  62827. */
  62828. this._bSphereRadiusFactor = 1.0;
  62829. this._positions = new Array();
  62830. this._indices = new Array();
  62831. this._normals = new Array();
  62832. this._colors = new Array();
  62833. this._uvs = new Array();
  62834. this._index = 0; // indices index
  62835. this._updatable = true;
  62836. this._pickable = false;
  62837. this._isVisibilityBoxLocked = false;
  62838. this._alwaysVisible = false;
  62839. this._depthSort = false;
  62840. this._shapeCounter = 0;
  62841. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  62842. this._color = new BABYLON.Color4(0, 0, 0, 0);
  62843. this._computeParticleColor = true;
  62844. this._computeParticleTexture = true;
  62845. this._computeParticleRotation = true;
  62846. this._computeParticleVertex = false;
  62847. this._computeBoundingBox = false;
  62848. this._depthSortParticles = true;
  62849. this._cam_axisZ = BABYLON.Vector3.Zero();
  62850. this._cam_axisY = BABYLON.Vector3.Zero();
  62851. this._cam_axisX = BABYLON.Vector3.Zero();
  62852. this._axisZ = BABYLON.Axis.Z;
  62853. this._camDir = BABYLON.Vector3.Zero();
  62854. this._camInvertedPosition = BABYLON.Vector3.Zero();
  62855. this._rotMatrix = new BABYLON.Matrix();
  62856. this._invertMatrix = new BABYLON.Matrix();
  62857. this._rotated = BABYLON.Vector3.Zero();
  62858. this._quaternion = new BABYLON.Quaternion();
  62859. this._vertex = BABYLON.Vector3.Zero();
  62860. this._normal = BABYLON.Vector3.Zero();
  62861. this._yaw = 0.0;
  62862. this._pitch = 0.0;
  62863. this._roll = 0.0;
  62864. this._halfroll = 0.0;
  62865. this._halfpitch = 0.0;
  62866. this._halfyaw = 0.0;
  62867. this._sinRoll = 0.0;
  62868. this._cosRoll = 0.0;
  62869. this._sinPitch = 0.0;
  62870. this._cosPitch = 0.0;
  62871. this._sinYaw = 0.0;
  62872. this._cosYaw = 0.0;
  62873. this._mustUnrotateFixedNormals = false;
  62874. this._minimum = BABYLON.Vector3.Zero();
  62875. this._maximum = BABYLON.Vector3.Zero();
  62876. this._minBbox = BABYLON.Vector3.Zero();
  62877. this._maxBbox = BABYLON.Vector3.Zero();
  62878. this._particlesIntersect = false;
  62879. this._depthSortFunction = function (p1, p2) {
  62880. return (p2.sqDistance - p1.sqDistance);
  62881. };
  62882. this._needs32Bits = false;
  62883. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  62884. this._scaledPivot = BABYLON.Vector3.Zero();
  62885. this._particleHasParent = false;
  62886. this.name = name;
  62887. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62888. this._camera = scene.activeCamera;
  62889. this._pickable = options ? options.isPickable : false;
  62890. this._depthSort = options ? options.enableDepthSort : false;
  62891. this._particlesIntersect = options ? options.particleIntersection : false;
  62892. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  62893. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  62894. if (options && options.updatable !== undefined) {
  62895. this._updatable = options.updatable;
  62896. }
  62897. else {
  62898. this._updatable = true;
  62899. }
  62900. if (this._pickable) {
  62901. this.pickedParticles = [];
  62902. }
  62903. if (this._depthSort) {
  62904. this.depthSortedParticles = [];
  62905. }
  62906. }
  62907. /**
  62908. * Builds the SPS underlying mesh. Returns a standard Mesh.
  62909. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  62910. * @returns the created mesh
  62911. */
  62912. SolidParticleSystem.prototype.buildMesh = function () {
  62913. if (this.nbParticles === 0) {
  62914. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  62915. this.addShape(triangle, 1);
  62916. triangle.dispose();
  62917. }
  62918. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  62919. this._positions32 = new Float32Array(this._positions);
  62920. this._uvs32 = new Float32Array(this._uvs);
  62921. this._colors32 = new Float32Array(this._colors);
  62922. if (this.recomputeNormals) {
  62923. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  62924. }
  62925. this._normals32 = new Float32Array(this._normals);
  62926. this._fixedNormal32 = new Float32Array(this._normals);
  62927. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  62928. this._unrotateFixedNormals();
  62929. }
  62930. var vertexData = new BABYLON.VertexData();
  62931. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  62932. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  62933. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  62934. if (this._uvs32.length > 0) {
  62935. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  62936. }
  62937. if (this._colors32.length > 0) {
  62938. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  62939. }
  62940. var mesh = new BABYLON.Mesh(this.name, this._scene);
  62941. vertexData.applyToMesh(mesh, this._updatable);
  62942. this.mesh = mesh;
  62943. this.mesh.isPickable = this._pickable;
  62944. // free memory
  62945. if (!this._depthSort) {
  62946. this._indices = null;
  62947. }
  62948. this._positions = null;
  62949. this._normals = null;
  62950. this._uvs = null;
  62951. this._colors = null;
  62952. if (!this._updatable) {
  62953. this.particles.length = 0;
  62954. }
  62955. return mesh;
  62956. };
  62957. /**
  62958. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  62959. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  62960. * Thus the particles generated from `digest()` have their property `position` set yet.
  62961. * @param mesh ( Mesh ) is the mesh to be digested
  62962. * @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
  62963. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  62964. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  62965. * @returns the current SPS
  62966. */
  62967. SolidParticleSystem.prototype.digest = function (mesh, options) {
  62968. var size = (options && options.facetNb) || 1;
  62969. var number = (options && options.number) || 0;
  62970. var delta = (options && options.delta) || 0;
  62971. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62972. var meshInd = mesh.getIndices();
  62973. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62974. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62975. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62976. var f = 0; // facet counter
  62977. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  62978. // compute size from number
  62979. if (number) {
  62980. number = (number > totalFacets) ? totalFacets : number;
  62981. size = Math.round(totalFacets / number);
  62982. delta = 0;
  62983. }
  62984. else {
  62985. size = (size > totalFacets) ? totalFacets : size;
  62986. }
  62987. var facetPos = []; // submesh positions
  62988. var facetInd = []; // submesh indices
  62989. var facetUV = []; // submesh UV
  62990. var facetCol = []; // submesh colors
  62991. var barycenter = BABYLON.Vector3.Zero();
  62992. var sizeO = size;
  62993. while (f < totalFacets) {
  62994. size = sizeO + Math.floor((1 + delta) * Math.random());
  62995. if (f > totalFacets - size) {
  62996. size = totalFacets - f;
  62997. }
  62998. // reset temp arrays
  62999. facetPos.length = 0;
  63000. facetInd.length = 0;
  63001. facetUV.length = 0;
  63002. facetCol.length = 0;
  63003. // iterate over "size" facets
  63004. var fi = 0;
  63005. for (var j = f * 3; j < (f + size) * 3; j++) {
  63006. facetInd.push(fi);
  63007. var i = meshInd[j];
  63008. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  63009. if (meshUV) {
  63010. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  63011. }
  63012. if (meshCol) {
  63013. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  63014. }
  63015. fi++;
  63016. }
  63017. // create a model shape for each single particle
  63018. var idx = this.nbParticles;
  63019. var shape = this._posToShape(facetPos);
  63020. var shapeUV = this._uvsToShapeUV(facetUV);
  63021. // compute the barycenter of the shape
  63022. var v;
  63023. for (v = 0; v < shape.length; v++) {
  63024. barycenter.addInPlace(shape[v]);
  63025. }
  63026. barycenter.scaleInPlace(1 / shape.length);
  63027. // shift the shape from its barycenter to the origin
  63028. for (v = 0; v < shape.length; v++) {
  63029. shape[v].subtractInPlace(barycenter);
  63030. }
  63031. var bInfo;
  63032. if (this._particlesIntersect) {
  63033. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  63034. }
  63035. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  63036. // add the particle in the SPS
  63037. var currentPos = this._positions.length;
  63038. var currentInd = this._indices.length;
  63039. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  63040. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  63041. // initialize the particle position
  63042. this.particles[this.nbParticles].position.addInPlace(barycenter);
  63043. this._index += shape.length;
  63044. idx++;
  63045. this.nbParticles++;
  63046. this._shapeCounter++;
  63047. f += size;
  63048. }
  63049. return this;
  63050. };
  63051. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  63052. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  63053. var index = 0;
  63054. var idx = 0;
  63055. for (var p = 0; p < this.particles.length; p++) {
  63056. this._particle = this.particles[p];
  63057. this._shape = this._particle._model._shape;
  63058. if (this._particle.rotationQuaternion) {
  63059. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63060. }
  63061. else {
  63062. this._yaw = this._particle.rotation.y;
  63063. this._pitch = this._particle.rotation.x;
  63064. this._roll = this._particle.rotation.z;
  63065. this._quaternionRotationYPR();
  63066. }
  63067. this._quaternionToRotationMatrix();
  63068. this._rotMatrix.invertToRef(this._invertMatrix);
  63069. for (var pt = 0; pt < this._shape.length; pt++) {
  63070. idx = index + pt * 3;
  63071. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  63072. this._fixedNormal32[idx] = this._normal.x;
  63073. this._fixedNormal32[idx + 1] = this._normal.y;
  63074. this._fixedNormal32[idx + 2] = this._normal.z;
  63075. }
  63076. index = idx + 3;
  63077. }
  63078. };
  63079. //reset copy
  63080. SolidParticleSystem.prototype._resetCopy = function () {
  63081. this._copy.position.x = 0;
  63082. this._copy.position.y = 0;
  63083. this._copy.position.z = 0;
  63084. this._copy.rotation.x = 0;
  63085. this._copy.rotation.y = 0;
  63086. this._copy.rotation.z = 0;
  63087. this._copy.rotationQuaternion = null;
  63088. this._copy.scaling.x = 1.0;
  63089. this._copy.scaling.y = 1.0;
  63090. this._copy.scaling.z = 1.0;
  63091. this._copy.uvs.x = 0;
  63092. this._copy.uvs.y = 0;
  63093. this._copy.uvs.z = 1.0;
  63094. this._copy.uvs.w = 1.0;
  63095. this._copy.color = null;
  63096. this._copy.translateFromPivot = false;
  63097. };
  63098. // _meshBuilder : inserts the shape model in the global SPS mesh
  63099. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  63100. var i;
  63101. var u = 0;
  63102. var c = 0;
  63103. var n = 0;
  63104. this._resetCopy();
  63105. if (options && options.positionFunction) { // call to custom positionFunction
  63106. options.positionFunction(this._copy, idx, idxInShape);
  63107. this._mustUnrotateFixedNormals = true;
  63108. }
  63109. if (this._copy.rotationQuaternion) {
  63110. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  63111. }
  63112. else {
  63113. this._yaw = this._copy.rotation.y;
  63114. this._pitch = this._copy.rotation.x;
  63115. this._roll = this._copy.rotation.z;
  63116. this._quaternionRotationYPR();
  63117. }
  63118. this._quaternionToRotationMatrix();
  63119. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  63120. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  63121. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  63122. if (this._copy.translateFromPivot) {
  63123. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  63124. }
  63125. else {
  63126. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  63127. }
  63128. for (i = 0; i < shape.length; i++) {
  63129. this._vertex.x = shape[i].x;
  63130. this._vertex.y = shape[i].y;
  63131. this._vertex.z = shape[i].z;
  63132. if (options && options.vertexFunction) {
  63133. options.vertexFunction(this._copy, this._vertex, i);
  63134. }
  63135. this._vertex.x *= this._copy.scaling.x;
  63136. this._vertex.y *= this._copy.scaling.y;
  63137. this._vertex.z *= this._copy.scaling.z;
  63138. this._vertex.x -= this._scaledPivot.x;
  63139. this._vertex.y -= this._scaledPivot.y;
  63140. this._vertex.z -= this._scaledPivot.z;
  63141. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  63142. this._rotated.addInPlace(this._pivotBackTranslation);
  63143. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  63144. if (meshUV) {
  63145. 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);
  63146. u += 2;
  63147. }
  63148. if (this._copy.color) {
  63149. this._color = this._copy.color;
  63150. }
  63151. else if (meshCol && meshCol[c] !== undefined) {
  63152. this._color.r = meshCol[c];
  63153. this._color.g = meshCol[c + 1];
  63154. this._color.b = meshCol[c + 2];
  63155. this._color.a = meshCol[c + 3];
  63156. }
  63157. else {
  63158. this._color.r = 1.0;
  63159. this._color.g = 1.0;
  63160. this._color.b = 1.0;
  63161. this._color.a = 1.0;
  63162. }
  63163. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  63164. c += 4;
  63165. if (!this.recomputeNormals && meshNor) {
  63166. this._normal.x = meshNor[n];
  63167. this._normal.y = meshNor[n + 1];
  63168. this._normal.z = meshNor[n + 2];
  63169. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  63170. normals.push(this._normal.x, this._normal.y, this._normal.z);
  63171. n += 3;
  63172. }
  63173. }
  63174. for (i = 0; i < meshInd.length; i++) {
  63175. var current_ind = p + meshInd[i];
  63176. indices.push(current_ind);
  63177. if (current_ind > 65535) {
  63178. this._needs32Bits = true;
  63179. }
  63180. }
  63181. if (this._pickable) {
  63182. var nbfaces = meshInd.length / 3;
  63183. for (i = 0; i < nbfaces; i++) {
  63184. this.pickedParticles.push({ idx: idx, faceId: i });
  63185. }
  63186. }
  63187. if (this._depthSort) {
  63188. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  63189. }
  63190. return this._copy;
  63191. };
  63192. // returns a shape array from positions array
  63193. SolidParticleSystem.prototype._posToShape = function (positions) {
  63194. var shape = [];
  63195. for (var i = 0; i < positions.length; i += 3) {
  63196. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  63197. }
  63198. return shape;
  63199. };
  63200. // returns a shapeUV array from a Vector4 uvs
  63201. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  63202. var shapeUV = [];
  63203. if (uvs) {
  63204. for (var i = 0; i < uvs.length; i++)
  63205. shapeUV.push(uvs[i]);
  63206. }
  63207. return shapeUV;
  63208. };
  63209. // adds a new particle object in the particles array
  63210. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  63211. if (bInfo === void 0) { bInfo = null; }
  63212. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  63213. this.particles.push(sp);
  63214. return sp;
  63215. };
  63216. /**
  63217. * Adds some particles to the SPS from the model shape. Returns the shape id.
  63218. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  63219. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  63220. * @param nb (positive integer) the number of particles to be created from this model
  63221. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  63222. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  63223. * @returns the number of shapes in the system
  63224. */
  63225. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  63226. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63227. var meshInd = mesh.getIndices();
  63228. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63229. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63230. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63231. var bbInfo;
  63232. if (this._particlesIntersect) {
  63233. bbInfo = mesh.getBoundingInfo();
  63234. }
  63235. var shape = this._posToShape(meshPos);
  63236. var shapeUV = this._uvsToShapeUV(meshUV);
  63237. var posfunc = options ? options.positionFunction : null;
  63238. var vtxfunc = options ? options.vertexFunction : null;
  63239. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  63240. // particles
  63241. var sp;
  63242. var currentCopy;
  63243. var idx = this.nbParticles;
  63244. for (var i = 0; i < nb; i++) {
  63245. var currentPos = this._positions.length;
  63246. var currentInd = this._indices.length;
  63247. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  63248. if (this._updatable) {
  63249. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  63250. sp.position.copyFrom(currentCopy.position);
  63251. sp.rotation.copyFrom(currentCopy.rotation);
  63252. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  63253. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  63254. }
  63255. if (currentCopy.color && sp.color) {
  63256. sp.color.copyFrom(currentCopy.color);
  63257. }
  63258. sp.scaling.copyFrom(currentCopy.scaling);
  63259. sp.uvs.copyFrom(currentCopy.uvs);
  63260. }
  63261. this._index += shape.length;
  63262. idx++;
  63263. }
  63264. this.nbParticles += nb;
  63265. this._shapeCounter++;
  63266. return this._shapeCounter - 1;
  63267. };
  63268. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  63269. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  63270. this._resetCopy();
  63271. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  63272. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  63273. }
  63274. if (this._copy.rotationQuaternion) {
  63275. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  63276. }
  63277. else {
  63278. this._yaw = this._copy.rotation.y;
  63279. this._pitch = this._copy.rotation.x;
  63280. this._roll = this._copy.rotation.z;
  63281. this._quaternionRotationYPR();
  63282. }
  63283. this._quaternionToRotationMatrix();
  63284. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63285. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63286. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63287. if (this._copy.translateFromPivot) {
  63288. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  63289. }
  63290. else {
  63291. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  63292. }
  63293. this._shape = particle._model._shape;
  63294. for (var pt = 0; pt < this._shape.length; pt++) {
  63295. this._vertex.x = this._shape[pt].x;
  63296. this._vertex.y = this._shape[pt].y;
  63297. this._vertex.z = this._shape[pt].z;
  63298. if (particle._model._vertexFunction) {
  63299. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  63300. }
  63301. this._vertex.x *= this._copy.scaling.x;
  63302. this._vertex.y *= this._copy.scaling.y;
  63303. this._vertex.z *= this._copy.scaling.z;
  63304. this._vertex.x -= this._scaledPivot.x;
  63305. this._vertex.y -= this._scaledPivot.y;
  63306. this._vertex.z -= this._scaledPivot.z;
  63307. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  63308. this._rotated.addInPlace(this._pivotBackTranslation);
  63309. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  63310. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  63311. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  63312. }
  63313. particle.position.x = 0.0;
  63314. particle.position.y = 0.0;
  63315. particle.position.z = 0.0;
  63316. particle.rotation.x = 0.0;
  63317. particle.rotation.y = 0.0;
  63318. particle.rotation.z = 0.0;
  63319. particle.rotationQuaternion = null;
  63320. particle.scaling.x = 1.0;
  63321. particle.scaling.y = 1.0;
  63322. particle.scaling.z = 1.0;
  63323. particle.uvs.x = 0.0;
  63324. particle.uvs.y = 0.0;
  63325. particle.uvs.z = 1.0;
  63326. particle.uvs.w = 1.0;
  63327. particle.pivot.x = 0.0;
  63328. particle.pivot.y = 0.0;
  63329. particle.pivot.z = 0.0;
  63330. particle.translateFromPivot = false;
  63331. particle.parentId = null;
  63332. };
  63333. /**
  63334. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  63335. * @returns the SPS.
  63336. */
  63337. SolidParticleSystem.prototype.rebuildMesh = function () {
  63338. for (var p = 0; p < this.particles.length; p++) {
  63339. this._rebuildParticle(this.particles[p]);
  63340. }
  63341. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63342. return this;
  63343. };
  63344. /**
  63345. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  63346. * This method calls `updateParticle()` for each particle of the SPS.
  63347. * For an animated SPS, it is usually called within the render loop.
  63348. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  63349. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  63350. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  63351. * @returns the SPS.
  63352. */
  63353. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  63354. if (start === void 0) { start = 0; }
  63355. if (end === void 0) { end = this.nbParticles - 1; }
  63356. if (update === void 0) { update = true; }
  63357. if (!this._updatable) {
  63358. return this;
  63359. }
  63360. // custom beforeUpdate
  63361. this.beforeUpdateParticles(start, end, update);
  63362. this._cam_axisX.x = 1.0;
  63363. this._cam_axisX.y = 0.0;
  63364. this._cam_axisX.z = 0.0;
  63365. this._cam_axisY.x = 0.0;
  63366. this._cam_axisY.y = 1.0;
  63367. this._cam_axisY.z = 0.0;
  63368. this._cam_axisZ.x = 0.0;
  63369. this._cam_axisZ.y = 0.0;
  63370. this._cam_axisZ.z = 1.0;
  63371. // cases when the World Matrix is to be computed first
  63372. if (this.billboard || this._depthSort) {
  63373. this.mesh.computeWorldMatrix(true);
  63374. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  63375. }
  63376. // if the particles will always face the camera
  63377. if (this.billboard) {
  63378. // compute the camera position and un-rotate it by the current mesh rotation
  63379. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  63380. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  63381. this._cam_axisZ.normalize();
  63382. // same for camera up vector extracted from the cam view matrix
  63383. var view = this._camera.getViewMatrix(true);
  63384. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  63385. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  63386. this._cam_axisY.normalize();
  63387. this._cam_axisX.normalize();
  63388. }
  63389. // if depthSort, compute the camera global position in the mesh local system
  63390. if (this._depthSort) {
  63391. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  63392. }
  63393. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  63394. var idx = 0; // current position index in the global array positions32
  63395. var index = 0; // position start index in the global array positions32 of the current particle
  63396. var colidx = 0; // current color index in the global array colors32
  63397. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  63398. var uvidx = 0; // current uv index in the global array uvs32
  63399. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  63400. var pt = 0; // current index in the particle model shape
  63401. if (this.mesh.isFacetDataEnabled) {
  63402. this._computeBoundingBox = true;
  63403. }
  63404. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  63405. if (this._computeBoundingBox) {
  63406. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  63407. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  63408. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  63409. }
  63410. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  63411. if (this.mesh._boundingInfo) {
  63412. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  63413. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  63414. }
  63415. }
  63416. }
  63417. // particle loop
  63418. index = this.particles[start]._pos;
  63419. var vpos = (index / 3) | 0;
  63420. colorIndex = vpos * 4;
  63421. uvIndex = vpos * 2;
  63422. for (var p = start; p <= end; p++) {
  63423. this._particle = this.particles[p];
  63424. this._shape = this._particle._model._shape;
  63425. this._shapeUV = this._particle._model._shapeUV;
  63426. // call to custom user function to update the particle properties
  63427. this.updateParticle(this._particle);
  63428. // camera-particle distance for depth sorting
  63429. if (this._depthSort && this._depthSortParticles) {
  63430. var dsp = this.depthSortedParticles[p];
  63431. dsp.ind = this._particle._ind;
  63432. dsp.indicesLength = this._particle._model._indicesLength;
  63433. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  63434. }
  63435. // skip the computations for inactive or already invisible particles
  63436. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  63437. // increment indexes for the next particle
  63438. pt = this._shape.length;
  63439. index += pt * 3;
  63440. colorIndex += pt * 4;
  63441. uvIndex += pt * 2;
  63442. continue;
  63443. }
  63444. if (this._particle.isVisible) {
  63445. this._particle._stillInvisible = false; // un-mark permanent invisibility
  63446. this._particleHasParent = (this._particle.parentId !== null);
  63447. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63448. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63449. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63450. // particle rotation matrix
  63451. if (this.billboard) {
  63452. this._particle.rotation.x = 0.0;
  63453. this._particle.rotation.y = 0.0;
  63454. }
  63455. if (this._computeParticleRotation || this.billboard) {
  63456. if (this._particle.rotationQuaternion) {
  63457. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63458. }
  63459. else {
  63460. this._yaw = this._particle.rotation.y;
  63461. this._pitch = this._particle.rotation.x;
  63462. this._roll = this._particle.rotation.z;
  63463. this._quaternionRotationYPR();
  63464. }
  63465. this._quaternionToRotationMatrix();
  63466. }
  63467. if (this._particleHasParent) {
  63468. this._parent = this.particles[this._particle.parentId];
  63469. 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];
  63470. 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];
  63471. 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];
  63472. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  63473. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  63474. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  63475. if (this._computeParticleRotation || this.billboard) {
  63476. 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];
  63477. 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];
  63478. 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];
  63479. 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];
  63480. 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];
  63481. 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];
  63482. 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];
  63483. 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];
  63484. 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];
  63485. }
  63486. }
  63487. else {
  63488. this._particle._globalPosition.x = this._particle.position.x;
  63489. this._particle._globalPosition.y = this._particle.position.y;
  63490. this._particle._globalPosition.z = this._particle.position.z;
  63491. if (this._computeParticleRotation || this.billboard) {
  63492. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  63493. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  63494. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  63495. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  63496. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  63497. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  63498. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  63499. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  63500. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  63501. }
  63502. }
  63503. if (this._particle.translateFromPivot) {
  63504. this._pivotBackTranslation.x = 0.0;
  63505. this._pivotBackTranslation.y = 0.0;
  63506. this._pivotBackTranslation.z = 0.0;
  63507. }
  63508. else {
  63509. this._pivotBackTranslation.x = this._scaledPivot.x;
  63510. this._pivotBackTranslation.y = this._scaledPivot.y;
  63511. this._pivotBackTranslation.z = this._scaledPivot.z;
  63512. }
  63513. // particle vertex loop
  63514. for (pt = 0; pt < this._shape.length; pt++) {
  63515. idx = index + pt * 3;
  63516. colidx = colorIndex + pt * 4;
  63517. uvidx = uvIndex + pt * 2;
  63518. this._vertex.x = this._shape[pt].x;
  63519. this._vertex.y = this._shape[pt].y;
  63520. this._vertex.z = this._shape[pt].z;
  63521. if (this._computeParticleVertex) {
  63522. this.updateParticleVertex(this._particle, this._vertex, pt);
  63523. }
  63524. // positions
  63525. this._vertex.x *= this._particle.scaling.x;
  63526. this._vertex.y *= this._particle.scaling.y;
  63527. this._vertex.z *= this._particle.scaling.z;
  63528. this._vertex.x -= this._scaledPivot.x;
  63529. this._vertex.y -= this._scaledPivot.y;
  63530. this._vertex.z -= this._scaledPivot.z;
  63531. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63532. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63533. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63534. this._rotated.x += this._pivotBackTranslation.x;
  63535. this._rotated.y += this._pivotBackTranslation.y;
  63536. this._rotated.z += this._pivotBackTranslation.z;
  63537. 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;
  63538. 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;
  63539. 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;
  63540. if (this._computeBoundingBox) {
  63541. if (this._positions32[idx] < this._minimum.x) {
  63542. this._minimum.x = this._positions32[idx];
  63543. }
  63544. if (this._positions32[idx] > this._maximum.x) {
  63545. this._maximum.x = this._positions32[idx];
  63546. }
  63547. if (this._positions32[idx + 1] < this._minimum.y) {
  63548. this._minimum.y = this._positions32[idx + 1];
  63549. }
  63550. if (this._positions32[idx + 1] > this._maximum.y) {
  63551. this._maximum.y = this._positions32[idx + 1];
  63552. }
  63553. if (this._positions32[idx + 2] < this._minimum.z) {
  63554. this._minimum.z = this._positions32[idx + 2];
  63555. }
  63556. if (this._positions32[idx + 2] > this._maximum.z) {
  63557. this._maximum.z = this._positions32[idx + 2];
  63558. }
  63559. }
  63560. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  63561. if (!this._computeParticleVertex) {
  63562. this._normal.x = this._fixedNormal32[idx];
  63563. this._normal.y = this._fixedNormal32[idx + 1];
  63564. this._normal.z = this._fixedNormal32[idx + 2];
  63565. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  63566. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  63567. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  63568. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  63569. 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;
  63570. 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;
  63571. }
  63572. if (this._computeParticleColor && this._particle.color) {
  63573. this._colors32[colidx] = this._particle.color.r;
  63574. this._colors32[colidx + 1] = this._particle.color.g;
  63575. this._colors32[colidx + 2] = this._particle.color.b;
  63576. this._colors32[colidx + 3] = this._particle.color.a;
  63577. }
  63578. if (this._computeParticleTexture) {
  63579. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63580. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63581. }
  63582. }
  63583. }
  63584. // particle just set invisible : scaled to zero and positioned at the origin
  63585. else {
  63586. this._particle._stillInvisible = true; // mark the particle as invisible
  63587. for (pt = 0; pt < this._shape.length; pt++) {
  63588. idx = index + pt * 3;
  63589. colidx = colorIndex + pt * 4;
  63590. uvidx = uvIndex + pt * 2;
  63591. this._positions32[idx] = 0.0;
  63592. this._positions32[idx + 1] = 0.0;
  63593. this._positions32[idx + 2] = 0.0;
  63594. this._normals32[idx] = 0.0;
  63595. this._normals32[idx + 1] = 0.0;
  63596. this._normals32[idx + 2] = 0.0;
  63597. if (this._computeParticleColor && this._particle.color) {
  63598. this._colors32[colidx] = this._particle.color.r;
  63599. this._colors32[colidx + 1] = this._particle.color.g;
  63600. this._colors32[colidx + 2] = this._particle.color.b;
  63601. this._colors32[colidx + 3] = this._particle.color.a;
  63602. }
  63603. if (this._computeParticleTexture) {
  63604. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63605. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63606. }
  63607. }
  63608. }
  63609. // if the particle intersections must be computed : update the bbInfo
  63610. if (this._particlesIntersect) {
  63611. var bInfo = this._particle._boundingInfo;
  63612. var bBox = bInfo.boundingBox;
  63613. var bSphere = bInfo.boundingSphere;
  63614. if (!this._bSphereOnly) {
  63615. // place, scale and rotate the particle bbox within the SPS local system, then update it
  63616. for (var b = 0; b < bBox.vectors.length; b++) {
  63617. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  63618. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  63619. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  63620. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63621. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63622. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63623. 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;
  63624. 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;
  63625. 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;
  63626. }
  63627. bBox._update(this.mesh._worldMatrix);
  63628. }
  63629. // place and scale the particle bouding sphere in the SPS local system, then update it
  63630. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  63631. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  63632. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  63633. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  63634. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  63635. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  63636. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  63637. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  63638. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  63639. 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));
  63640. bSphere._update(this.mesh._worldMatrix);
  63641. }
  63642. // increment indexes for the next particle
  63643. index = idx + 3;
  63644. colorIndex = colidx + 4;
  63645. uvIndex = uvidx + 2;
  63646. }
  63647. // if the VBO must be updated
  63648. if (update) {
  63649. if (this._computeParticleColor) {
  63650. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  63651. }
  63652. if (this._computeParticleTexture) {
  63653. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  63654. }
  63655. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63656. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  63657. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  63658. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  63659. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  63660. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  63661. for (var i = 0; i < this._normals32.length; i++) {
  63662. this._fixedNormal32[i] = this._normals32[i];
  63663. }
  63664. }
  63665. if (!this.mesh.areNormalsFrozen) {
  63666. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  63667. }
  63668. }
  63669. if (this._depthSort && this._depthSortParticles) {
  63670. this.depthSortedParticles.sort(this._depthSortFunction);
  63671. var dspl = this.depthSortedParticles.length;
  63672. var sorted = 0;
  63673. var lind = 0;
  63674. var sind = 0;
  63675. var sid = 0;
  63676. for (sorted = 0; sorted < dspl; sorted++) {
  63677. lind = this.depthSortedParticles[sorted].indicesLength;
  63678. sind = this.depthSortedParticles[sorted].ind;
  63679. for (var i = 0; i < lind; i++) {
  63680. this._indices32[sid] = this._indices[sind + i];
  63681. sid++;
  63682. }
  63683. }
  63684. this.mesh.updateIndices(this._indices32);
  63685. }
  63686. }
  63687. if (this._computeBoundingBox) {
  63688. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  63689. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  63690. }
  63691. this.afterUpdateParticles(start, end, update);
  63692. return this;
  63693. };
  63694. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  63695. this._halfroll = this._roll * 0.5;
  63696. this._halfpitch = this._pitch * 0.5;
  63697. this._halfyaw = this._yaw * 0.5;
  63698. this._sinRoll = Math.sin(this._halfroll);
  63699. this._cosRoll = Math.cos(this._halfroll);
  63700. this._sinPitch = Math.sin(this._halfpitch);
  63701. this._cosPitch = Math.cos(this._halfpitch);
  63702. this._sinYaw = Math.sin(this._halfyaw);
  63703. this._cosYaw = Math.cos(this._halfyaw);
  63704. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  63705. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  63706. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  63707. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  63708. };
  63709. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  63710. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  63711. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  63712. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  63713. this._rotMatrix.m[3] = 0;
  63714. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  63715. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  63716. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  63717. this._rotMatrix.m[7] = 0;
  63718. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  63719. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  63720. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  63721. this._rotMatrix.m[11] = 0;
  63722. this._rotMatrix.m[12] = 0;
  63723. this._rotMatrix.m[13] = 0;
  63724. this._rotMatrix.m[14] = 0;
  63725. this._rotMatrix.m[15] = 1.0;
  63726. };
  63727. /**
  63728. * Disposes the SPS.
  63729. */
  63730. SolidParticleSystem.prototype.dispose = function () {
  63731. this.mesh.dispose();
  63732. this.vars = null;
  63733. // drop references to internal big arrays for the GC
  63734. this._positions = null;
  63735. this._indices = null;
  63736. this._normals = null;
  63737. this._uvs = null;
  63738. this._colors = null;
  63739. this._indices32 = null;
  63740. this._positions32 = null;
  63741. this._normals32 = null;
  63742. this._fixedNormal32 = null;
  63743. this._uvs32 = null;
  63744. this._colors32 = null;
  63745. this.pickedParticles = null;
  63746. };
  63747. /**
  63748. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  63749. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63750. * @returns the SPS.
  63751. */
  63752. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  63753. if (!this._isVisibilityBoxLocked) {
  63754. this.mesh.refreshBoundingInfo();
  63755. }
  63756. return this;
  63757. };
  63758. /**
  63759. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  63760. * @param size the size (float) of the visibility box
  63761. * note : this doesn't lock the SPS mesh bounding box.
  63762. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63763. */
  63764. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  63765. var vis = size / 2;
  63766. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  63767. };
  63768. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  63769. /**
  63770. * Gets whether the SPS as always visible or not
  63771. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63772. */
  63773. get: function () {
  63774. return this._alwaysVisible;
  63775. },
  63776. /**
  63777. * Sets the SPS as always visible or not
  63778. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63779. */
  63780. set: function (val) {
  63781. this._alwaysVisible = val;
  63782. this.mesh.alwaysSelectAsActiveMesh = val;
  63783. },
  63784. enumerable: true,
  63785. configurable: true
  63786. });
  63787. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  63788. /**
  63789. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63790. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63791. */
  63792. get: function () {
  63793. return this._isVisibilityBoxLocked;
  63794. },
  63795. /**
  63796. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63797. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63798. */
  63799. set: function (val) {
  63800. this._isVisibilityBoxLocked = val;
  63801. var boundingInfo = this.mesh.getBoundingInfo();
  63802. boundingInfo.isLocked = val;
  63803. },
  63804. enumerable: true,
  63805. configurable: true
  63806. });
  63807. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  63808. /**
  63809. * Gets if `setParticles()` computes the particle rotations or not.
  63810. * Default value : true. The SPS is faster when it's set to false.
  63811. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63812. */
  63813. get: function () {
  63814. return this._computeParticleRotation;
  63815. },
  63816. /**
  63817. * Tells to `setParticles()` to compute the particle rotations or not.
  63818. * Default value : true. The SPS is faster when it's set to false.
  63819. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63820. */
  63821. set: function (val) {
  63822. this._computeParticleRotation = val;
  63823. },
  63824. enumerable: true,
  63825. configurable: true
  63826. });
  63827. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  63828. /**
  63829. * Gets if `setParticles()` computes the particle colors or not.
  63830. * Default value : true. The SPS is faster when it's set to false.
  63831. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63832. */
  63833. get: function () {
  63834. return this._computeParticleColor;
  63835. },
  63836. /**
  63837. * Tells to `setParticles()` to compute the particle colors or not.
  63838. * Default value : true. The SPS is faster when it's set to false.
  63839. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63840. */
  63841. set: function (val) {
  63842. this._computeParticleColor = val;
  63843. },
  63844. enumerable: true,
  63845. configurable: true
  63846. });
  63847. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  63848. /**
  63849. * Gets if `setParticles()` computes the particle textures or not.
  63850. * Default value : true. The SPS is faster when it's set to false.
  63851. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  63852. */
  63853. get: function () {
  63854. return this._computeParticleTexture;
  63855. },
  63856. set: function (val) {
  63857. this._computeParticleTexture = val;
  63858. },
  63859. enumerable: true,
  63860. configurable: true
  63861. });
  63862. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  63863. /**
  63864. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  63865. * Default value : false. The SPS is faster when it's set to false.
  63866. * Note : the particle custom vertex positions aren't stored values.
  63867. */
  63868. get: function () {
  63869. return this._computeParticleVertex;
  63870. },
  63871. /**
  63872. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  63873. * Default value : false. The SPS is faster when it's set to false.
  63874. * Note : the particle custom vertex positions aren't stored values.
  63875. */
  63876. set: function (val) {
  63877. this._computeParticleVertex = val;
  63878. },
  63879. enumerable: true,
  63880. configurable: true
  63881. });
  63882. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  63883. /**
  63884. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  63885. */
  63886. get: function () {
  63887. return this._computeBoundingBox;
  63888. },
  63889. /**
  63890. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  63891. */
  63892. set: function (val) {
  63893. this._computeBoundingBox = val;
  63894. },
  63895. enumerable: true,
  63896. configurable: true
  63897. });
  63898. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  63899. /**
  63900. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  63901. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63902. * Default : `true`
  63903. */
  63904. get: function () {
  63905. return this._depthSortParticles;
  63906. },
  63907. /**
  63908. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  63909. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63910. * Default : `true`
  63911. */
  63912. set: function (val) {
  63913. this._depthSortParticles = val;
  63914. },
  63915. enumerable: true,
  63916. configurable: true
  63917. });
  63918. // =======================================================================
  63919. // Particle behavior logic
  63920. // these following methods may be overwritten by the user to fit his needs
  63921. /**
  63922. * This function does nothing. It may be overwritten to set all the particle first values.
  63923. * The SPS doesn't call this function, you may have to call it by your own.
  63924. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63925. */
  63926. SolidParticleSystem.prototype.initParticles = function () {
  63927. };
  63928. /**
  63929. * This function does nothing. It may be overwritten to recycle a particle.
  63930. * The SPS doesn't call this function, you may have to call it by your own.
  63931. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63932. * @param particle The particle to recycle
  63933. * @returns the recycled particle
  63934. */
  63935. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  63936. return particle;
  63937. };
  63938. /**
  63939. * Updates a particle : this function should be overwritten by the user.
  63940. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  63941. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63942. * @example : just set a particle position or velocity and recycle conditions
  63943. * @param particle The particle to update
  63944. * @returns the updated particle
  63945. */
  63946. SolidParticleSystem.prototype.updateParticle = function (particle) {
  63947. return particle;
  63948. };
  63949. /**
  63950. * Updates a vertex of a particle : it can be overwritten by the user.
  63951. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  63952. * @param particle the current particle
  63953. * @param vertex the current index of the current particle
  63954. * @param pt the index of the current vertex in the particle shape
  63955. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  63956. * @example : just set a vertex particle position
  63957. * @returns the updated vertex
  63958. */
  63959. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  63960. return vertex;
  63961. };
  63962. /**
  63963. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  63964. * This does nothing and may be overwritten by the user.
  63965. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63966. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63967. * @param update the boolean update value actually passed to setParticles()
  63968. */
  63969. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  63970. };
  63971. /**
  63972. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  63973. * This will be passed three parameters.
  63974. * This does nothing and may be overwritten by the user.
  63975. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63976. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63977. * @param update the boolean update value actually passed to setParticles()
  63978. */
  63979. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  63980. };
  63981. return SolidParticleSystem;
  63982. }());
  63983. BABYLON.SolidParticleSystem = SolidParticleSystem;
  63984. })(BABYLON || (BABYLON = {}));
  63985. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  63986. var BABYLON;
  63987. (function (BABYLON) {
  63988. /**
  63989. * Class containing static functions to help procedurally build meshes
  63990. */
  63991. var MeshBuilder = /** @class */ (function () {
  63992. function MeshBuilder() {
  63993. }
  63994. MeshBuilder.updateSideOrientation = function (orientation) {
  63995. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  63996. return BABYLON.Mesh.DOUBLESIDE;
  63997. }
  63998. if (orientation === undefined || orientation === null) {
  63999. return BABYLON.Mesh.FRONTSIDE;
  64000. }
  64001. return orientation;
  64002. };
  64003. /**
  64004. * Creates a box mesh
  64005. * * The parameter `size` sets the size (float) of each box side (default 1)
  64006. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  64007. * * 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)
  64008. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64009. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64010. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64011. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64012. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  64013. * @param name defines the name of the mesh
  64014. * @param options defines the options used to create the mesh
  64015. * @param scene defines the hosting scene
  64016. * @returns the box mesh
  64017. */
  64018. MeshBuilder.CreateBox = function (name, options, scene) {
  64019. if (scene === void 0) { scene = null; }
  64020. var box = new BABYLON.Mesh(name, scene);
  64021. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64022. box._originalBuilderSideOrientation = options.sideOrientation;
  64023. var vertexData = BABYLON.VertexData.CreateBox(options);
  64024. vertexData.applyToMesh(box, options.updatable);
  64025. return box;
  64026. };
  64027. /**
  64028. * Creates a sphere mesh
  64029. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  64030. * * 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`)
  64031. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  64032. * * 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
  64033. * * 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)
  64034. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64035. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64036. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64037. * @param name defines the name of the mesh
  64038. * @param options defines the options used to create the mesh
  64039. * @param scene defines the hosting scene
  64040. * @returns the sphere mesh
  64041. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  64042. */
  64043. MeshBuilder.CreateSphere = function (name, options, scene) {
  64044. var sphere = new BABYLON.Mesh(name, scene);
  64045. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64046. sphere._originalBuilderSideOrientation = options.sideOrientation;
  64047. var vertexData = BABYLON.VertexData.CreateSphere(options);
  64048. vertexData.applyToMesh(sphere, options.updatable);
  64049. return sphere;
  64050. };
  64051. /**
  64052. * Creates a plane polygonal mesh. By default, this is a disc
  64053. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  64054. * * 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
  64055. * * 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
  64056. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64057. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64058. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64059. * @param name defines the name of the mesh
  64060. * @param options defines the options used to create the mesh
  64061. * @param scene defines the hosting scene
  64062. * @returns the plane polygonal mesh
  64063. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  64064. */
  64065. MeshBuilder.CreateDisc = function (name, options, scene) {
  64066. if (scene === void 0) { scene = null; }
  64067. var disc = new BABYLON.Mesh(name, scene);
  64068. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64069. disc._originalBuilderSideOrientation = options.sideOrientation;
  64070. var vertexData = BABYLON.VertexData.CreateDisc(options);
  64071. vertexData.applyToMesh(disc, options.updatable);
  64072. return disc;
  64073. };
  64074. /**
  64075. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  64076. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  64077. * * 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`)
  64078. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  64079. * * 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
  64080. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64081. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64082. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64083. * @param name defines the name of the mesh
  64084. * @param options defines the options used to create the mesh
  64085. * @param scene defines the hosting scene
  64086. * @returns the icosahedron mesh
  64087. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  64088. */
  64089. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  64090. var sphere = new BABYLON.Mesh(name, scene);
  64091. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64092. sphere._originalBuilderSideOrientation = options.sideOrientation;
  64093. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  64094. vertexData.applyToMesh(sphere, options.updatable);
  64095. return sphere;
  64096. };
  64097. ;
  64098. /**
  64099. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64100. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  64101. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  64102. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  64103. * * 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
  64104. * * 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
  64105. * * 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
  64106. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64107. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64108. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64109. * * 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
  64110. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  64111. * * 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 if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  64112. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  64113. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64114. * @param name defines the name of the mesh
  64115. * @param options defines the options used to create the mesh
  64116. * @param scene defines the hosting scene
  64117. * @returns the ribbon mesh
  64118. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  64119. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64120. */
  64121. MeshBuilder.CreateRibbon = function (name, options, scene) {
  64122. if (scene === void 0) { scene = null; }
  64123. var pathArray = options.pathArray;
  64124. var closeArray = options.closeArray;
  64125. var closePath = options.closePath;
  64126. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64127. var instance = options.instance;
  64128. var updatable = options.updatable;
  64129. if (instance) { // existing ribbon instance update
  64130. // positionFunction : ribbon case
  64131. // only pathArray and sideOrientation parameters are taken into account for positions update
  64132. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  64133. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  64134. var positionFunction = function (positions) {
  64135. var minlg = pathArray[0].length;
  64136. var i = 0;
  64137. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  64138. for (var si = 1; si <= ns; si++) {
  64139. for (var p = 0; p < pathArray.length; p++) {
  64140. var path = pathArray[p];
  64141. var l = path.length;
  64142. minlg = (minlg < l) ? minlg : l;
  64143. var j = 0;
  64144. while (j < minlg) {
  64145. positions[i] = path[j].x;
  64146. positions[i + 1] = path[j].y;
  64147. positions[i + 2] = path[j].z;
  64148. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  64149. BABYLON.Tmp.Vector3[0].x = path[j].x;
  64150. }
  64151. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  64152. BABYLON.Tmp.Vector3[1].x = path[j].x;
  64153. }
  64154. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  64155. BABYLON.Tmp.Vector3[0].y = path[j].y;
  64156. }
  64157. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  64158. BABYLON.Tmp.Vector3[1].y = path[j].y;
  64159. }
  64160. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  64161. BABYLON.Tmp.Vector3[0].z = path[j].z;
  64162. }
  64163. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  64164. BABYLON.Tmp.Vector3[1].z = path[j].z;
  64165. }
  64166. j++;
  64167. i += 3;
  64168. }
  64169. if (instance._closePath) {
  64170. positions[i] = path[0].x;
  64171. positions[i + 1] = path[0].y;
  64172. positions[i + 2] = path[0].z;
  64173. i += 3;
  64174. }
  64175. }
  64176. }
  64177. };
  64178. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64179. positionFunction(positions);
  64180. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  64181. instance._boundingInfo.update(instance._worldMatrix);
  64182. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64183. if (options.colors) {
  64184. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64185. for (var c = 0; c < options.colors.length; c++) {
  64186. colors[c * 4] = options.colors[c].r;
  64187. colors[c * 4 + 1] = options.colors[c].g;
  64188. colors[c * 4 + 2] = options.colors[c].b;
  64189. colors[c * 4 + 3] = options.colors[c].a;
  64190. }
  64191. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  64192. }
  64193. if (options.uvs) {
  64194. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64195. for (var i = 0; i < options.uvs.length; i++) {
  64196. uvs[i * 2] = options.uvs[i].x;
  64197. uvs[i * 2 + 1] = options.uvs[i].y;
  64198. }
  64199. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  64200. }
  64201. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  64202. var indices = instance.getIndices();
  64203. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64204. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  64205. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  64206. if (instance._closePath) {
  64207. var indexFirst = 0;
  64208. var indexLast = 0;
  64209. for (var p = 0; p < pathArray.length; p++) {
  64210. indexFirst = instance._idx[p] * 3;
  64211. if (p + 1 < pathArray.length) {
  64212. indexLast = (instance._idx[p + 1] - 1) * 3;
  64213. }
  64214. else {
  64215. indexLast = normals.length - 3;
  64216. }
  64217. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  64218. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  64219. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  64220. normals[indexLast] = normals[indexFirst];
  64221. normals[indexLast + 1] = normals[indexFirst + 1];
  64222. normals[indexLast + 2] = normals[indexFirst + 2];
  64223. }
  64224. }
  64225. if (!(instance.areNormalsFrozen)) {
  64226. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  64227. }
  64228. }
  64229. return instance;
  64230. }
  64231. else { // new ribbon creation
  64232. var ribbon = new BABYLON.Mesh(name, scene);
  64233. ribbon._originalBuilderSideOrientation = sideOrientation;
  64234. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  64235. if (closePath) {
  64236. ribbon._idx = vertexData._idx;
  64237. }
  64238. ribbon._closePath = closePath;
  64239. ribbon._closeArray = closeArray;
  64240. vertexData.applyToMesh(ribbon, updatable);
  64241. return ribbon;
  64242. }
  64243. };
  64244. /**
  64245. * Creates a cylinder or a cone mesh
  64246. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  64247. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  64248. * * 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.
  64249. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  64250. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  64251. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  64252. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  64253. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  64254. * * 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).
  64255. * * 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
  64256. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  64257. * * 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
  64258. * * 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.
  64259. * * If `enclose` is false, a ring surface is one element.
  64260. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  64261. * * 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
  64262. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64263. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64264. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64265. * @param name defines the name of the mesh
  64266. * @param options defines the options used to create the mesh
  64267. * @param scene defines the hosting scene
  64268. * @returns the cylinder mesh
  64269. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  64270. */
  64271. MeshBuilder.CreateCylinder = function (name, options, scene) {
  64272. var cylinder = new BABYLON.Mesh(name, scene);
  64273. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64274. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  64275. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  64276. vertexData.applyToMesh(cylinder, options.updatable);
  64277. return cylinder;
  64278. };
  64279. /**
  64280. * Creates a torus mesh
  64281. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  64282. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  64283. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  64284. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64285. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64286. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64287. * @param name defines the name of the mesh
  64288. * @param options defines the options used to create the mesh
  64289. * @param scene defines the hosting scene
  64290. * @returns the torus mesh
  64291. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  64292. */
  64293. MeshBuilder.CreateTorus = function (name, options, scene) {
  64294. var torus = new BABYLON.Mesh(name, scene);
  64295. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64296. torus._originalBuilderSideOrientation = options.sideOrientation;
  64297. var vertexData = BABYLON.VertexData.CreateTorus(options);
  64298. vertexData.applyToMesh(torus, options.updatable);
  64299. return torus;
  64300. };
  64301. /**
  64302. * Creates a torus knot mesh
  64303. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  64304. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  64305. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  64306. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  64307. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64308. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64309. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64310. * @param name defines the name of the mesh
  64311. * @param options defines the options used to create the mesh
  64312. * @param scene defines the hosting scene
  64313. * @returns the torus knot mesh
  64314. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  64315. */
  64316. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  64317. var torusKnot = new BABYLON.Mesh(name, scene);
  64318. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64319. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  64320. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  64321. vertexData.applyToMesh(torusKnot, options.updatable);
  64322. return torusKnot;
  64323. };
  64324. /**
  64325. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  64326. * * 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
  64327. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  64328. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  64329. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  64330. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  64331. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  64332. * * 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
  64333. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  64334. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64335. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  64336. * @param name defines the name of the new line system
  64337. * @param options defines the options used to create the line system
  64338. * @param scene defines the hosting scene
  64339. * @returns a new line system mesh
  64340. */
  64341. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  64342. var instance = options.instance;
  64343. var lines = options.lines;
  64344. var colors = options.colors;
  64345. if (instance) { // lines update
  64346. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64347. var vertexColor;
  64348. var lineColors;
  64349. if (colors) {
  64350. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64351. }
  64352. var i = 0;
  64353. var c = 0;
  64354. for (var l = 0; l < lines.length; l++) {
  64355. var points = lines[l];
  64356. for (var p = 0; p < points.length; p++) {
  64357. positions[i] = points[p].x;
  64358. positions[i + 1] = points[p].y;
  64359. positions[i + 2] = points[p].z;
  64360. if (colors && vertexColor) {
  64361. lineColors = colors[l];
  64362. vertexColor[c] = lineColors[p].r;
  64363. vertexColor[c + 1] = lineColors[p].g;
  64364. vertexColor[c + 2] = lineColors[p].b;
  64365. vertexColor[c + 3] = lineColors[p].a;
  64366. c += 4;
  64367. }
  64368. i += 3;
  64369. }
  64370. }
  64371. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64372. if (colors && vertexColor) {
  64373. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  64374. }
  64375. return instance;
  64376. }
  64377. // line system creation
  64378. var useVertexColor = (colors) ? true : false;
  64379. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  64380. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  64381. vertexData.applyToMesh(lineSystem, options.updatable);
  64382. return lineSystem;
  64383. };
  64384. /**
  64385. * Creates a line mesh
  64386. * 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
  64387. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64388. * * The parameter `points` is an array successive Vector3
  64389. * * 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
  64390. * * The optional parameter `colors` is an array of successive Color4, one per line point
  64391. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  64392. * * When updating an instance, remember that only point positions can change, not the number of points
  64393. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64394. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  64395. * @param name defines the name of the new line system
  64396. * @param options defines the options used to create the line system
  64397. * @param scene defines the hosting scene
  64398. * @returns a new line mesh
  64399. */
  64400. MeshBuilder.CreateLines = function (name, options, scene) {
  64401. if (scene === void 0) { scene = null; }
  64402. var colors = (options.colors) ? [options.colors] : null;
  64403. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  64404. return lines;
  64405. };
  64406. /**
  64407. * Creates a dashed line mesh
  64408. * * 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
  64409. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64410. * * The parameter `points` is an array successive Vector3
  64411. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  64412. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  64413. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  64414. * * 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
  64415. * * When updating an instance, remember that only point positions can change, not the number of points
  64416. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64417. * @param name defines the name of the mesh
  64418. * @param options defines the options used to create the mesh
  64419. * @param scene defines the hosting scene
  64420. * @returns the dashed line mesh
  64421. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  64422. */
  64423. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  64424. if (scene === void 0) { scene = null; }
  64425. var points = options.points;
  64426. var instance = options.instance;
  64427. var gapSize = options.gapSize || 1;
  64428. var dashSize = options.dashSize || 3;
  64429. if (instance) { // dashed lines update
  64430. var positionFunction = function (positions) {
  64431. var curvect = BABYLON.Vector3.Zero();
  64432. var nbSeg = positions.length / 6;
  64433. var lg = 0;
  64434. var nb = 0;
  64435. var shft = 0;
  64436. var dashshft = 0;
  64437. var curshft = 0;
  64438. var p = 0;
  64439. var i = 0;
  64440. var j = 0;
  64441. for (i = 0; i < points.length - 1; i++) {
  64442. points[i + 1].subtractToRef(points[i], curvect);
  64443. lg += curvect.length();
  64444. }
  64445. shft = lg / nbSeg;
  64446. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  64447. for (i = 0; i < points.length - 1; i++) {
  64448. points[i + 1].subtractToRef(points[i], curvect);
  64449. nb = Math.floor(curvect.length() / shft);
  64450. curvect.normalize();
  64451. j = 0;
  64452. while (j < nb && p < positions.length) {
  64453. curshft = shft * j;
  64454. positions[p] = points[i].x + curshft * curvect.x;
  64455. positions[p + 1] = points[i].y + curshft * curvect.y;
  64456. positions[p + 2] = points[i].z + curshft * curvect.z;
  64457. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  64458. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  64459. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  64460. p += 6;
  64461. j++;
  64462. }
  64463. }
  64464. while (p < positions.length) {
  64465. positions[p] = points[i].x;
  64466. positions[p + 1] = points[i].y;
  64467. positions[p + 2] = points[i].z;
  64468. p += 3;
  64469. }
  64470. };
  64471. instance.updateMeshPositions(positionFunction, false);
  64472. return instance;
  64473. }
  64474. // dashed lines creation
  64475. var dashedLines = new BABYLON.LinesMesh(name, scene);
  64476. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  64477. vertexData.applyToMesh(dashedLines, options.updatable);
  64478. dashedLines.dashSize = dashSize;
  64479. dashedLines.gapSize = gapSize;
  64480. return dashedLines;
  64481. };
  64482. /**
  64483. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  64484. * * 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 extruded along the Z axis.
  64485. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64486. * * 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.
  64487. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  64488. * * 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
  64489. * * 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
  64490. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  64491. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64492. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64493. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  64494. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64495. * @param name defines the name of the mesh
  64496. * @param options defines the options used to create the mesh
  64497. * @param scene defines the hosting scene
  64498. * @returns the extruded shape mesh
  64499. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64500. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64501. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64502. */
  64503. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  64504. if (scene === void 0) { scene = null; }
  64505. var path = options.path;
  64506. var shape = options.shape;
  64507. var scale = options.scale || 1;
  64508. var rotation = options.rotation || 0;
  64509. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64510. var updatable = options.updatable;
  64511. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64512. var instance = options.instance || null;
  64513. var invertUV = options.invertUV || false;
  64514. 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);
  64515. };
  64516. /**
  64517. * Creates an custom extruded shape mesh.
  64518. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  64519. * * 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 extruded along the Z axis.
  64520. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64521. * * 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 and the distance of this point from the begining of the path
  64522. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  64523. * * 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 and the distance of this point from the begining of the path
  64524. * * It must returns a float value that will be the scale value applied to the shape on each path point
  64525. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  64526. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  64527. * * 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
  64528. * * 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
  64529. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  64530. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64531. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64532. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64533. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64534. * @param name defines the name of the mesh
  64535. * @param options defines the options used to create the mesh
  64536. * @param scene defines the hosting scene
  64537. * @returns the custom extruded shape mesh
  64538. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  64539. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64540. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64541. */
  64542. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  64543. var path = options.path;
  64544. var shape = options.shape;
  64545. var scaleFunction = options.scaleFunction || (function () { return 1; });
  64546. var rotationFunction = options.rotationFunction || (function () { return 0; });
  64547. var ribbonCloseArray = options.ribbonCloseArray || false;
  64548. var ribbonClosePath = options.ribbonClosePath || false;
  64549. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64550. var updatable = options.updatable;
  64551. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64552. var instance = options.instance;
  64553. var invertUV = options.invertUV || false;
  64554. 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);
  64555. };
  64556. /**
  64557. * Creates lathe mesh.
  64558. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  64559. * * 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 rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  64560. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  64561. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  64562. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  64563. * * 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
  64564. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  64565. * * 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
  64566. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64567. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64568. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64569. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64570. * @param name defines the name of the mesh
  64571. * @param options defines the options used to create the mesh
  64572. * @param scene defines the hosting scene
  64573. * @returns the lathe mesh
  64574. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  64575. */
  64576. MeshBuilder.CreateLathe = function (name, options, scene) {
  64577. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  64578. var closed = (options.closed === undefined) ? true : options.closed;
  64579. var shape = options.shape;
  64580. var radius = options.radius || 1;
  64581. var tessellation = options.tessellation || 64;
  64582. var clip = options.clip || 0;
  64583. var updatable = options.updatable;
  64584. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64585. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64586. var pi2 = Math.PI * 2;
  64587. var paths = new Array();
  64588. var invertUV = options.invertUV || false;
  64589. var i = 0;
  64590. var p = 0;
  64591. var step = pi2 / tessellation * arc;
  64592. var rotated;
  64593. var path = new Array();
  64594. for (i = 0; i <= tessellation - clip; i++) {
  64595. var path = [];
  64596. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  64597. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  64598. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  64599. }
  64600. for (p = 0; p < shape.length; p++) {
  64601. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  64602. path.push(rotated);
  64603. }
  64604. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  64605. 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));
  64606. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  64607. }
  64608. paths.push(path);
  64609. }
  64610. // lathe ribbon
  64611. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64612. return lathe;
  64613. };
  64614. /**
  64615. * Creates a plane mesh
  64616. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  64617. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  64618. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  64619. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64620. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64621. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64622. * @param name defines the name of the mesh
  64623. * @param options defines the options used to create the mesh
  64624. * @param scene defines the hosting scene
  64625. * @returns the plane mesh
  64626. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64627. */
  64628. MeshBuilder.CreatePlane = function (name, options, scene) {
  64629. var plane = new BABYLON.Mesh(name, scene);
  64630. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64631. plane._originalBuilderSideOrientation = options.sideOrientation;
  64632. var vertexData = BABYLON.VertexData.CreatePlane(options);
  64633. vertexData.applyToMesh(plane, options.updatable);
  64634. if (options.sourcePlane) {
  64635. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  64636. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  64637. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  64638. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  64639. plane.rotate(vectorProduct, product);
  64640. }
  64641. }
  64642. return plane;
  64643. };
  64644. /**
  64645. * Creates a ground mesh
  64646. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  64647. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  64648. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64649. * @param name defines the name of the mesh
  64650. * @param options defines the options used to create the mesh
  64651. * @param scene defines the hosting scene
  64652. * @returns the ground mesh
  64653. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64654. */
  64655. MeshBuilder.CreateGround = function (name, options, scene) {
  64656. var ground = new BABYLON.GroundMesh(name, scene);
  64657. ground._setReady(false);
  64658. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  64659. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  64660. ground._width = options.width || 1;
  64661. ground._height = options.height || 1;
  64662. ground._maxX = ground._width / 2;
  64663. ground._maxZ = ground._height / 2;
  64664. ground._minX = -ground._maxX;
  64665. ground._minZ = -ground._maxZ;
  64666. var vertexData = BABYLON.VertexData.CreateGround(options);
  64667. vertexData.applyToMesh(ground, options.updatable);
  64668. ground._setReady(true);
  64669. return ground;
  64670. };
  64671. /**
  64672. * Creates a tiled ground mesh
  64673. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  64674. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  64675. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  64676. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  64677. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64678. * @param name defines the name of the mesh
  64679. * @param options defines the options used to create the mesh
  64680. * @param scene defines the hosting scene
  64681. * @returns the tiled ground mesh
  64682. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  64683. */
  64684. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  64685. var tiledGround = new BABYLON.Mesh(name, scene);
  64686. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  64687. vertexData.applyToMesh(tiledGround, options.updatable);
  64688. return tiledGround;
  64689. };
  64690. /**
  64691. * Creates a ground mesh from a height map
  64692. * * The parameter `url` sets the URL of the height map image resource.
  64693. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  64694. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  64695. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  64696. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  64697. * * 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.
  64698. * * 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).
  64699. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  64700. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64701. * @param name defines the name of the mesh
  64702. * @param url defines the url to the height map
  64703. * @param options defines the options used to create the mesh
  64704. * @param scene defines the hosting scene
  64705. * @returns the ground mesh
  64706. * @see http://doc.babylonjs.com/babylon101/height_map
  64707. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  64708. */
  64709. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  64710. var width = options.width || 10.0;
  64711. var height = options.height || 10.0;
  64712. var subdivisions = options.subdivisions || 1 | 0;
  64713. var minHeight = options.minHeight || 0.0;
  64714. var maxHeight = options.maxHeight || 1.0;
  64715. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  64716. var alphaFilter = options.alphaFilter || 0.0;
  64717. var updatable = options.updatable;
  64718. var onReady = options.onReady;
  64719. var ground = new BABYLON.GroundMesh(name, scene);
  64720. ground._subdivisionsX = subdivisions;
  64721. ground._subdivisionsY = subdivisions;
  64722. ground._width = width;
  64723. ground._height = height;
  64724. ground._maxX = ground._width / 2.0;
  64725. ground._maxZ = ground._height / 2.0;
  64726. ground._minX = -ground._maxX;
  64727. ground._minZ = -ground._maxZ;
  64728. ground._setReady(false);
  64729. var onload = function (img) {
  64730. // Getting height map data
  64731. var canvas = document.createElement("canvas");
  64732. var context = canvas.getContext("2d");
  64733. if (!context) {
  64734. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  64735. }
  64736. if (scene.isDisposed) {
  64737. return;
  64738. }
  64739. var bufferWidth = img.width;
  64740. var bufferHeight = img.height;
  64741. canvas.width = bufferWidth;
  64742. canvas.height = bufferHeight;
  64743. context.drawImage(img, 0, 0);
  64744. // Create VertexData from map data
  64745. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  64746. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  64747. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  64748. width: width, height: height,
  64749. subdivisions: subdivisions,
  64750. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  64751. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  64752. alphaFilter: alphaFilter
  64753. });
  64754. vertexData.applyToMesh(ground, updatable);
  64755. //execute ready callback, if set
  64756. if (onReady) {
  64757. onReady(ground);
  64758. }
  64759. ground._setReady(true);
  64760. };
  64761. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  64762. return ground;
  64763. };
  64764. /**
  64765. * Creates a polygon mesh
  64766. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  64767. * * 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
  64768. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64769. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64770. * * 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)
  64771. * * Remember you can only change the shape positions, not their number when updating a polygon
  64772. * @param name defines the name of the mesh
  64773. * @param options defines the options used to create the mesh
  64774. * @param scene defines the hosting scene
  64775. * @returns the polygon mesh
  64776. */
  64777. MeshBuilder.CreatePolygon = function (name, options, scene) {
  64778. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64779. var shape = options.shape;
  64780. var holes = options.holes || [];
  64781. var depth = options.depth || 0;
  64782. var contours = [];
  64783. var hole = [];
  64784. for (var i = 0; i < shape.length; i++) {
  64785. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  64786. }
  64787. var epsilon = 0.00000001;
  64788. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  64789. contours.pop();
  64790. }
  64791. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  64792. for (var hNb = 0; hNb < holes.length; hNb++) {
  64793. hole = [];
  64794. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  64795. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  64796. }
  64797. polygonTriangulation.addHole(hole);
  64798. }
  64799. var polygon = polygonTriangulation.build(options.updatable, depth);
  64800. polygon._originalBuilderSideOrientation = options.sideOrientation;
  64801. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  64802. vertexData.applyToMesh(polygon, options.updatable);
  64803. return polygon;
  64804. };
  64805. ;
  64806. /**
  64807. * Creates an extruded polygon mesh, with depth in the Y direction.
  64808. * * 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)
  64809. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64810. * @param name defines the name of the mesh
  64811. * @param options defines the options used to create the mesh
  64812. * @param scene defines the hosting scene
  64813. * @returns the polygon mesh
  64814. */
  64815. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  64816. return MeshBuilder.CreatePolygon(name, options, scene);
  64817. };
  64818. ;
  64819. /**
  64820. * Creates a tube mesh.
  64821. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64822. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  64823. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  64824. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  64825. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  64826. * * 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. It must return a radius value (positive float)
  64827. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  64828. * * 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
  64829. * * 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
  64830. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64831. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64832. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64833. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64834. * @param name defines the name of the mesh
  64835. * @param options defines the options used to create the mesh
  64836. * @param scene defines the hosting scene
  64837. * @returns the tube mesh
  64838. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64839. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  64840. */
  64841. MeshBuilder.CreateTube = function (name, options, scene) {
  64842. var path = options.path;
  64843. var instance = options.instance;
  64844. var radius = 1.0;
  64845. if (instance) {
  64846. radius = instance.radius;
  64847. }
  64848. if (options.radius !== undefined) {
  64849. radius = options.radius;
  64850. }
  64851. ;
  64852. var tessellation = options.tessellation || 64 | 0;
  64853. var radiusFunction = options.radiusFunction || null;
  64854. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64855. var invertUV = options.invertUV || false;
  64856. var updatable = options.updatable;
  64857. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64858. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  64859. // tube geometry
  64860. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  64861. var tangents = path3D.getTangents();
  64862. var normals = path3D.getNormals();
  64863. var distances = path3D.getDistances();
  64864. var pi2 = Math.PI * 2;
  64865. var step = pi2 / tessellation * arc;
  64866. var returnRadius = function () { return radius; };
  64867. var radiusFunctionFinal = radiusFunction || returnRadius;
  64868. var circlePath;
  64869. var rad;
  64870. var normal;
  64871. var rotated;
  64872. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64873. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64874. for (var i = 0; i < path.length; i++) {
  64875. rad = radiusFunctionFinal(i, distances[i]); // current radius
  64876. circlePath = Array(); // current circle array
  64877. normal = normals[i]; // current normal
  64878. for (var t = 0; t < tessellation; t++) {
  64879. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  64880. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  64881. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  64882. rotated.scaleInPlace(rad).addInPlace(path[i]);
  64883. circlePath[t] = rotated;
  64884. }
  64885. circlePaths[index] = circlePath;
  64886. index++;
  64887. }
  64888. // cap
  64889. var capPath = function (nbPoints, pathIndex) {
  64890. var pointCap = Array();
  64891. for (var i = 0; i < nbPoints; i++) {
  64892. pointCap.push(path[pathIndex]);
  64893. }
  64894. return pointCap;
  64895. };
  64896. switch (cap) {
  64897. case BABYLON.Mesh.NO_CAP:
  64898. break;
  64899. case BABYLON.Mesh.CAP_START:
  64900. circlePaths[0] = capPath(tessellation, 0);
  64901. circlePaths[1] = circlePaths[2].slice(0);
  64902. break;
  64903. case BABYLON.Mesh.CAP_END:
  64904. circlePaths[index] = circlePaths[index - 1].slice(0);
  64905. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64906. break;
  64907. case BABYLON.Mesh.CAP_ALL:
  64908. circlePaths[0] = capPath(tessellation, 0);
  64909. circlePaths[1] = circlePaths[2].slice(0);
  64910. circlePaths[index] = circlePaths[index - 1].slice(0);
  64911. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64912. break;
  64913. default:
  64914. break;
  64915. }
  64916. return circlePaths;
  64917. };
  64918. var path3D;
  64919. var pathArray;
  64920. if (instance) { // tube update
  64921. var arc = options.arc || instance.arc;
  64922. path3D = (instance.path3D).update(path);
  64923. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  64924. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  64925. instance.path3D = path3D;
  64926. instance.pathArray = pathArray;
  64927. instance.arc = arc;
  64928. instance.radius = radius;
  64929. return instance;
  64930. }
  64931. // tube creation
  64932. path3D = new BABYLON.Path3D(path);
  64933. var newPathArray = new Array();
  64934. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64935. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  64936. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64937. tube.pathArray = pathArray;
  64938. tube.path3D = path3D;
  64939. tube.tessellation = tessellation;
  64940. tube.cap = cap;
  64941. tube.arc = options.arc;
  64942. tube.radius = radius;
  64943. return tube;
  64944. };
  64945. /**
  64946. * Creates a polyhedron mesh
  64947. * * 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 to choose the wanted type
  64948. * * The parameter `size` (positive float, default 1) sets the polygon size
  64949. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  64950. * * 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`
  64951. * * 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
  64952. * * 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)`)
  64953. * * 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
  64954. * * 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
  64955. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64956. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64957. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64958. * @param name defines the name of the mesh
  64959. * @param options defines the options used to create the mesh
  64960. * @param scene defines the hosting scene
  64961. * @returns the polyhedron mesh
  64962. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  64963. */
  64964. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  64965. var polyhedron = new BABYLON.Mesh(name, scene);
  64966. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64967. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  64968. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  64969. vertexData.applyToMesh(polyhedron, options.updatable);
  64970. return polyhedron;
  64971. };
  64972. /**
  64973. * Creates a decal mesh.
  64974. * 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
  64975. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  64976. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  64977. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  64978. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  64979. * @param name defines the name of the mesh
  64980. * @param sourceMesh defines the mesh where the decal must be applied
  64981. * @param options defines the options used to create the mesh
  64982. * @param scene defines the hosting scene
  64983. * @returns the decal mesh
  64984. * @see http://doc.babylonjs.com/how_to/decals
  64985. */
  64986. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  64987. var indices = sourceMesh.getIndices();
  64988. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64989. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64990. var position = options.position || BABYLON.Vector3.Zero();
  64991. var normal = options.normal || BABYLON.Vector3.Up();
  64992. var size = options.size || BABYLON.Vector3.One();
  64993. var angle = options.angle || 0;
  64994. // Getting correct rotation
  64995. if (!normal) {
  64996. var target = new BABYLON.Vector3(0, 0, 1);
  64997. var camera = sourceMesh.getScene().activeCamera;
  64998. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  64999. normal = camera.globalPosition.subtract(cameraWorldTarget);
  65000. }
  65001. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  65002. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  65003. var pitch = Math.atan2(normal.y, len);
  65004. // Matrix
  65005. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  65006. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  65007. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  65008. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  65009. var vertexData = new BABYLON.VertexData();
  65010. vertexData.indices = [];
  65011. vertexData.positions = [];
  65012. vertexData.normals = [];
  65013. vertexData.uvs = [];
  65014. var currentVertexDataIndex = 0;
  65015. var extractDecalVector3 = function (indexId) {
  65016. var result = new BABYLON.PositionNormalVertex();
  65017. if (!indices || !positions || !normals) {
  65018. return result;
  65019. }
  65020. var vertexId = indices[indexId];
  65021. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  65022. // Send vector to decal local world
  65023. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  65024. // Get normal
  65025. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  65026. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  65027. return result;
  65028. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  65029. var clip = function (vertices, axis) {
  65030. if (vertices.length === 0) {
  65031. return vertices;
  65032. }
  65033. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  65034. var clipVertices = function (v0, v1) {
  65035. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  65036. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  65037. };
  65038. var result = new Array();
  65039. for (var index = 0; index < vertices.length; index += 3) {
  65040. var v1Out;
  65041. var v2Out;
  65042. var v3Out;
  65043. var total = 0;
  65044. var nV1 = null;
  65045. var nV2 = null;
  65046. var nV3 = null;
  65047. var nV4 = null;
  65048. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  65049. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  65050. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  65051. v1Out = d1 > 0;
  65052. v2Out = d2 > 0;
  65053. v3Out = d3 > 0;
  65054. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  65055. switch (total) {
  65056. case 0:
  65057. result.push(vertices[index]);
  65058. result.push(vertices[index + 1]);
  65059. result.push(vertices[index + 2]);
  65060. break;
  65061. case 1:
  65062. if (v1Out) {
  65063. nV1 = vertices[index + 1];
  65064. nV2 = vertices[index + 2];
  65065. nV3 = clipVertices(vertices[index], nV1);
  65066. nV4 = clipVertices(vertices[index], nV2);
  65067. }
  65068. if (v2Out) {
  65069. nV1 = vertices[index];
  65070. nV2 = vertices[index + 2];
  65071. nV3 = clipVertices(vertices[index + 1], nV1);
  65072. nV4 = clipVertices(vertices[index + 1], nV2);
  65073. result.push(nV3);
  65074. result.push(nV2.clone());
  65075. result.push(nV1.clone());
  65076. result.push(nV2.clone());
  65077. result.push(nV3.clone());
  65078. result.push(nV4);
  65079. break;
  65080. }
  65081. if (v3Out) {
  65082. nV1 = vertices[index];
  65083. nV2 = vertices[index + 1];
  65084. nV3 = clipVertices(vertices[index + 2], nV1);
  65085. nV4 = clipVertices(vertices[index + 2], nV2);
  65086. }
  65087. if (nV1 && nV2 && nV3 && nV4) {
  65088. result.push(nV1.clone());
  65089. result.push(nV2.clone());
  65090. result.push(nV3);
  65091. result.push(nV4);
  65092. result.push(nV3.clone());
  65093. result.push(nV2.clone());
  65094. }
  65095. break;
  65096. case 2:
  65097. if (!v1Out) {
  65098. nV1 = vertices[index].clone();
  65099. nV2 = clipVertices(nV1, vertices[index + 1]);
  65100. nV3 = clipVertices(nV1, vertices[index + 2]);
  65101. result.push(nV1);
  65102. result.push(nV2);
  65103. result.push(nV3);
  65104. }
  65105. if (!v2Out) {
  65106. nV1 = vertices[index + 1].clone();
  65107. nV2 = clipVertices(nV1, vertices[index + 2]);
  65108. nV3 = clipVertices(nV1, vertices[index]);
  65109. result.push(nV1);
  65110. result.push(nV2);
  65111. result.push(nV3);
  65112. }
  65113. if (!v3Out) {
  65114. nV1 = vertices[index + 2].clone();
  65115. nV2 = clipVertices(nV1, vertices[index]);
  65116. nV3 = clipVertices(nV1, vertices[index + 1]);
  65117. result.push(nV1);
  65118. result.push(nV2);
  65119. result.push(nV3);
  65120. }
  65121. break;
  65122. case 3:
  65123. break;
  65124. }
  65125. }
  65126. return result;
  65127. };
  65128. for (var index = 0; index < indices.length; index += 3) {
  65129. var faceVertices = new Array();
  65130. faceVertices.push(extractDecalVector3(index));
  65131. faceVertices.push(extractDecalVector3(index + 1));
  65132. faceVertices.push(extractDecalVector3(index + 2));
  65133. // Clip
  65134. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  65135. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  65136. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  65137. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  65138. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  65139. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  65140. if (faceVertices.length === 0) {
  65141. continue;
  65142. }
  65143. // Add UVs and get back to world
  65144. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  65145. var vertex = faceVertices[vIndex];
  65146. //TODO check for Int32Array | Uint32Array | Uint16Array
  65147. vertexData.indices.push(currentVertexDataIndex);
  65148. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  65149. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  65150. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  65151. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  65152. currentVertexDataIndex++;
  65153. }
  65154. }
  65155. // Return mesh
  65156. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  65157. vertexData.applyToMesh(decal);
  65158. decal.position = position.clone();
  65159. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  65160. return decal;
  65161. };
  65162. // Privates
  65163. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  65164. // extrusion geometry
  65165. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  65166. var tangents = path3D.getTangents();
  65167. var normals = path3D.getNormals();
  65168. var binormals = path3D.getBinormals();
  65169. var distances = path3D.getDistances();
  65170. var angle = 0;
  65171. var returnScale = function () { return scale !== null ? scale : 1; };
  65172. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  65173. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  65174. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  65175. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  65176. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  65177. for (var i = 0; i < curve.length; i++) {
  65178. var shapePath = new Array();
  65179. var angleStep = rotate(i, distances[i]);
  65180. var scaleRatio = scl(i, distances[i]);
  65181. for (var p = 0; p < shape.length; p++) {
  65182. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  65183. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  65184. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  65185. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  65186. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  65187. shapePath[p] = rotated;
  65188. }
  65189. shapePaths[index] = shapePath;
  65190. angle += angleStep;
  65191. index++;
  65192. }
  65193. // cap
  65194. var capPath = function (shapePath) {
  65195. var pointCap = Array();
  65196. var barycenter = BABYLON.Vector3.Zero();
  65197. var i;
  65198. for (i = 0; i < shapePath.length; i++) {
  65199. barycenter.addInPlace(shapePath[i]);
  65200. }
  65201. barycenter.scaleInPlace(1.0 / shapePath.length);
  65202. for (i = 0; i < shapePath.length; i++) {
  65203. pointCap.push(barycenter);
  65204. }
  65205. return pointCap;
  65206. };
  65207. switch (cap) {
  65208. case BABYLON.Mesh.NO_CAP:
  65209. break;
  65210. case BABYLON.Mesh.CAP_START:
  65211. shapePaths[0] = capPath(shapePaths[2]);
  65212. shapePaths[1] = shapePaths[2];
  65213. break;
  65214. case BABYLON.Mesh.CAP_END:
  65215. shapePaths[index] = shapePaths[index - 1];
  65216. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  65217. break;
  65218. case BABYLON.Mesh.CAP_ALL:
  65219. shapePaths[0] = capPath(shapePaths[2]);
  65220. shapePaths[1] = shapePaths[2];
  65221. shapePaths[index] = shapePaths[index - 1];
  65222. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  65223. break;
  65224. default:
  65225. break;
  65226. }
  65227. return shapePaths;
  65228. };
  65229. var path3D;
  65230. var pathArray;
  65231. if (instance) { // instance update
  65232. path3D = (instance.path3D).update(curve);
  65233. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  65234. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  65235. return instance;
  65236. }
  65237. // extruded shape creation
  65238. path3D = new BABYLON.Path3D(curve);
  65239. var newShapePaths = new Array();
  65240. cap = (cap < 0 || cap > 3) ? 0 : cap;
  65241. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  65242. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  65243. extrudedGeneric.pathArray = pathArray;
  65244. extrudedGeneric.path3D = path3D;
  65245. extrudedGeneric.cap = cap;
  65246. return extrudedGeneric;
  65247. };
  65248. return MeshBuilder;
  65249. }());
  65250. BABYLON.MeshBuilder = MeshBuilder;
  65251. })(BABYLON || (BABYLON = {}));
  65252. //# sourceMappingURL=babylon.meshBuilder.js.map
  65253. var BABYLON;
  65254. (function (BABYLON) {
  65255. /**
  65256. * Draco compression (https://google.github.io/draco/)
  65257. *
  65258. * This class wraps the Draco module.
  65259. *
  65260. * **Encoder**
  65261. *
  65262. * The encoder is not currently implemented.
  65263. *
  65264. * **Decoder**
  65265. *
  65266. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  65267. *
  65268. * To update the configuration, use the following code:
  65269. * ```javascript
  65270. * BABYLON.DracoCompression.Configuration = {
  65271. * decoder: {
  65272. * wasmUrl: "<url to the WebAssembly library>",
  65273. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  65274. * fallbackUrl: "<url to the fallback JavaScript library>",
  65275. * }
  65276. * };
  65277. * ```
  65278. *
  65279. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  65280. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  65281. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  65282. *
  65283. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  65284. * ```javascript
  65285. * var dracoCompression = new BABYLON.DracoCompression();
  65286. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  65287. * [BABYLON.VertexBuffer.PositionKind]: 0
  65288. * });
  65289. * ```
  65290. *
  65291. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  65292. */
  65293. var DracoCompression = /** @class */ (function () {
  65294. /**
  65295. * Constructor
  65296. */
  65297. function DracoCompression() {
  65298. }
  65299. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  65300. /**
  65301. * Returns true if the decoder is available.
  65302. */
  65303. get: function () {
  65304. if (typeof DracoDecoderModule !== "undefined") {
  65305. return true;
  65306. }
  65307. var decoder = DracoCompression.Configuration.decoder;
  65308. if (decoder) {
  65309. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65310. return true;
  65311. }
  65312. if (decoder.fallbackUrl) {
  65313. return true;
  65314. }
  65315. }
  65316. return false;
  65317. },
  65318. enumerable: true,
  65319. configurable: true
  65320. });
  65321. /**
  65322. * Stop all async operations and release resources.
  65323. */
  65324. DracoCompression.prototype.dispose = function () {
  65325. };
  65326. /**
  65327. * Decode Draco compressed mesh data to vertex data.
  65328. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  65329. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  65330. * @returns A promise that resolves with the decoded vertex data
  65331. */
  65332. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  65333. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  65334. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  65335. var module = wrappedModule.module;
  65336. var vertexData = new BABYLON.VertexData();
  65337. var buffer = new module.DecoderBuffer();
  65338. buffer.Init(dataView, dataView.byteLength);
  65339. var decoder = new module.Decoder();
  65340. var geometry;
  65341. var status;
  65342. try {
  65343. var type = decoder.GetEncodedGeometryType(buffer);
  65344. switch (type) {
  65345. case module.TRIANGULAR_MESH:
  65346. geometry = new module.Mesh();
  65347. status = decoder.DecodeBufferToMesh(buffer, geometry);
  65348. break;
  65349. case module.POINT_CLOUD:
  65350. geometry = new module.PointCloud();
  65351. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  65352. break;
  65353. default:
  65354. throw new Error("Invalid geometry type " + type);
  65355. }
  65356. if (!status.ok() || !geometry.ptr) {
  65357. throw new Error(status.error_msg());
  65358. }
  65359. var numPoints = geometry.num_points();
  65360. if (type === module.TRIANGULAR_MESH) {
  65361. var numFaces = geometry.num_faces();
  65362. var faceIndices = new module.DracoInt32Array();
  65363. try {
  65364. var indices = new Uint32Array(numFaces * 3);
  65365. for (var i = 0; i < numFaces; i++) {
  65366. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  65367. var offset = i * 3;
  65368. indices[offset + 0] = faceIndices.GetValue(0);
  65369. indices[offset + 1] = faceIndices.GetValue(1);
  65370. indices[offset + 2] = faceIndices.GetValue(2);
  65371. }
  65372. vertexData.indices = indices;
  65373. }
  65374. finally {
  65375. module.destroy(faceIndices);
  65376. }
  65377. }
  65378. for (var kind in attributes) {
  65379. var uniqueId = attributes[kind];
  65380. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  65381. var dracoData = new module.DracoFloat32Array();
  65382. try {
  65383. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  65384. var babylonData = new Float32Array(numPoints * attribute.num_components());
  65385. for (var i = 0; i < babylonData.length; i++) {
  65386. babylonData[i] = dracoData.GetValue(i);
  65387. }
  65388. vertexData.set(babylonData, kind);
  65389. }
  65390. finally {
  65391. module.destroy(dracoData);
  65392. }
  65393. }
  65394. }
  65395. finally {
  65396. if (geometry) {
  65397. module.destroy(geometry);
  65398. }
  65399. module.destroy(decoder);
  65400. module.destroy(buffer);
  65401. }
  65402. return vertexData;
  65403. });
  65404. };
  65405. DracoCompression._GetDecoderModule = function () {
  65406. if (!DracoCompression._DecoderModulePromise) {
  65407. var promise = null;
  65408. var config_1 = {};
  65409. if (typeof DracoDecoderModule !== "undefined") {
  65410. promise = Promise.resolve();
  65411. }
  65412. else {
  65413. var decoder = DracoCompression.Configuration.decoder;
  65414. if (decoder) {
  65415. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65416. promise = Promise.all([
  65417. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  65418. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  65419. config_1.wasmBinary = data;
  65420. })
  65421. ]);
  65422. }
  65423. else if (decoder.fallbackUrl) {
  65424. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  65425. }
  65426. }
  65427. }
  65428. if (!promise) {
  65429. throw new Error("Draco decoder module is not available");
  65430. }
  65431. DracoCompression._DecoderModulePromise = promise.then(function () {
  65432. return new Promise(function (resolve) {
  65433. config_1.onModuleLoaded = function (decoderModule) {
  65434. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  65435. resolve({ module: decoderModule });
  65436. };
  65437. DracoDecoderModule(config_1);
  65438. });
  65439. });
  65440. }
  65441. return DracoCompression._DecoderModulePromise;
  65442. };
  65443. DracoCompression._LoadScriptAsync = function (url) {
  65444. return new Promise(function (resolve, reject) {
  65445. BABYLON.Tools.LoadScript(url, function () {
  65446. resolve();
  65447. }, function (message) {
  65448. reject(new Error(message));
  65449. });
  65450. });
  65451. };
  65452. DracoCompression._LoadFileAsync = function (url) {
  65453. return new Promise(function (resolve, reject) {
  65454. BABYLON.Tools.LoadFile(url, function (data) {
  65455. resolve(data);
  65456. }, undefined, undefined, true, function (request, exception) {
  65457. reject(exception);
  65458. });
  65459. });
  65460. };
  65461. /**
  65462. * The configuration. Defaults to the following urls:
  65463. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  65464. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  65465. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65466. */
  65467. DracoCompression.Configuration = {
  65468. decoder: {
  65469. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  65470. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  65471. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65472. }
  65473. };
  65474. return DracoCompression;
  65475. }());
  65476. BABYLON.DracoCompression = DracoCompression;
  65477. })(BABYLON || (BABYLON = {}));
  65478. //# sourceMappingURL=babylon.dracoCompression.js.map
  65479. var BABYLON;
  65480. (function (BABYLON) {
  65481. // Sets the default audio engine to Babylon JS.
  65482. BABYLON.Engine.AudioEngineFactory = function () { return new AudioEngine(); };
  65483. var AudioEngine = /** @class */ (function () {
  65484. function AudioEngine() {
  65485. this._audioContext = null;
  65486. this._audioContextInitialized = false;
  65487. this.canUseWebAudio = false;
  65488. this.WarnedWebAudioUnsupported = false;
  65489. this.unlocked = false;
  65490. this.isMP3supported = false;
  65491. this.isOGGsupported = false;
  65492. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  65493. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  65494. this.canUseWebAudio = true;
  65495. }
  65496. var audioElem = document.createElement('audio');
  65497. try {
  65498. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  65499. this.isMP3supported = true;
  65500. }
  65501. }
  65502. catch (e) {
  65503. // protect error during capability check.
  65504. }
  65505. try {
  65506. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  65507. this.isOGGsupported = true;
  65508. }
  65509. }
  65510. catch (e) {
  65511. // protect error during capability check.
  65512. }
  65513. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  65514. this._unlockiOSaudio();
  65515. }
  65516. else {
  65517. this.unlocked = true;
  65518. }
  65519. }
  65520. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  65521. get: function () {
  65522. if (!this._audioContextInitialized) {
  65523. this._initializeAudioContext();
  65524. }
  65525. return this._audioContext;
  65526. },
  65527. enumerable: true,
  65528. configurable: true
  65529. });
  65530. AudioEngine.prototype._unlockiOSaudio = function () {
  65531. var _this = this;
  65532. var unlockaudio = function () {
  65533. if (!_this.audioContext) {
  65534. return;
  65535. }
  65536. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  65537. var source = _this.audioContext.createBufferSource();
  65538. source.buffer = buffer;
  65539. source.connect(_this.audioContext.destination);
  65540. source.start(0);
  65541. setTimeout(function () {
  65542. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  65543. _this.unlocked = true;
  65544. window.removeEventListener('touchend', unlockaudio, false);
  65545. if (_this.onAudioUnlocked) {
  65546. _this.onAudioUnlocked();
  65547. }
  65548. }
  65549. }, 0);
  65550. };
  65551. window.addEventListener('touchend', unlockaudio, false);
  65552. };
  65553. AudioEngine.prototype._initializeAudioContext = function () {
  65554. try {
  65555. if (this.canUseWebAudio) {
  65556. this._audioContext = new AudioContext();
  65557. // create a global volume gain node
  65558. this.masterGain = this._audioContext.createGain();
  65559. this.masterGain.gain.value = 1;
  65560. this.masterGain.connect(this._audioContext.destination);
  65561. this._audioContextInitialized = true;
  65562. }
  65563. }
  65564. catch (e) {
  65565. this.canUseWebAudio = false;
  65566. BABYLON.Tools.Error("Web Audio: " + e.message);
  65567. }
  65568. };
  65569. AudioEngine.prototype.dispose = function () {
  65570. if (this.canUseWebAudio && this._audioContextInitialized) {
  65571. if (this._connectedAnalyser && this._audioContext) {
  65572. this._connectedAnalyser.stopDebugCanvas();
  65573. this._connectedAnalyser.dispose();
  65574. this.masterGain.disconnect();
  65575. this.masterGain.connect(this._audioContext.destination);
  65576. this._connectedAnalyser = null;
  65577. }
  65578. this.masterGain.gain.value = 1;
  65579. }
  65580. this.WarnedWebAudioUnsupported = false;
  65581. };
  65582. AudioEngine.prototype.getGlobalVolume = function () {
  65583. if (this.canUseWebAudio && this._audioContextInitialized) {
  65584. return this.masterGain.gain.value;
  65585. }
  65586. else {
  65587. return -1;
  65588. }
  65589. };
  65590. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  65591. if (this.canUseWebAudio && this._audioContextInitialized) {
  65592. this.masterGain.gain.value = newVolume;
  65593. }
  65594. };
  65595. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  65596. if (this._connectedAnalyser) {
  65597. this._connectedAnalyser.stopDebugCanvas();
  65598. }
  65599. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  65600. this._connectedAnalyser = analyser;
  65601. this.masterGain.disconnect();
  65602. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  65603. }
  65604. };
  65605. return AudioEngine;
  65606. }());
  65607. BABYLON.AudioEngine = AudioEngine;
  65608. })(BABYLON || (BABYLON = {}));
  65609. //# sourceMappingURL=babylon.audioEngine.js.map
  65610. var BABYLON;
  65611. (function (BABYLON) {
  65612. var Sound = /** @class */ (function () {
  65613. /**
  65614. * Create a sound and attach it to a scene
  65615. * @param name Name of your sound
  65616. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  65617. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  65618. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  65619. */
  65620. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  65621. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  65622. var _this = this;
  65623. this.autoplay = false;
  65624. this.loop = false;
  65625. this.useCustomAttenuation = false;
  65626. this.spatialSound = false;
  65627. this.refDistance = 1;
  65628. this.rolloffFactor = 1;
  65629. this.maxDistance = 100;
  65630. this.distanceModel = "linear";
  65631. this._panningModel = "equalpower";
  65632. /**
  65633. * Observable event when the current playing sound finishes.
  65634. */
  65635. this.onEndedObservable = new BABYLON.Observable();
  65636. this._playbackRate = 1;
  65637. this._streaming = false;
  65638. this._startTime = 0;
  65639. this._startOffset = 0;
  65640. this._position = BABYLON.Vector3.Zero();
  65641. /** @hidden */
  65642. this._positionInEmitterSpace = false;
  65643. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  65644. this._volume = 1;
  65645. this._isReadyToPlay = false;
  65646. this.isPlaying = false;
  65647. this.isPaused = false;
  65648. this._isDirectional = false;
  65649. // Used if you'd like to create a directional sound.
  65650. // If not set, the sound will be omnidirectional
  65651. this._coneInnerAngle = 360;
  65652. this._coneOuterAngle = 360;
  65653. this._coneOuterGain = 0;
  65654. this._isOutputConnected = false;
  65655. this._urlType = "Unknown";
  65656. this.name = name;
  65657. this._scene = scene;
  65658. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  65659. if (!compo) {
  65660. compo = new BABYLON.AudioSceneComponent(scene);
  65661. scene._addComponent(compo);
  65662. }
  65663. this._readyToPlayCallback = readyToPlayCallback;
  65664. // Default custom attenuation function is a linear attenuation
  65665. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  65666. if (currentDistance < maxDistance) {
  65667. return currentVolume * (1 - currentDistance / maxDistance);
  65668. }
  65669. else {
  65670. return 0;
  65671. }
  65672. };
  65673. if (options) {
  65674. this.autoplay = options.autoplay || false;
  65675. this.loop = options.loop || false;
  65676. // if volume === 0, we need another way to check this option
  65677. if (options.volume !== undefined) {
  65678. this._volume = options.volume;
  65679. }
  65680. this.spatialSound = options.spatialSound || false;
  65681. this.maxDistance = options.maxDistance || 100;
  65682. this.useCustomAttenuation = options.useCustomAttenuation || false;
  65683. this.rolloffFactor = options.rolloffFactor || 1;
  65684. this.refDistance = options.refDistance || 1;
  65685. this.distanceModel = options.distanceModel || "linear";
  65686. this._playbackRate = options.playbackRate || 1;
  65687. this._streaming = options.streaming || false;
  65688. }
  65689. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65690. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  65691. this._soundGain.gain.value = this._volume;
  65692. this._inputAudioNode = this._soundGain;
  65693. this._outputAudioNode = this._soundGain;
  65694. if (this.spatialSound) {
  65695. this._createSpatialParameters();
  65696. }
  65697. this._scene.mainSoundTrack.AddSound(this);
  65698. var validParameter = true;
  65699. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  65700. if (urlOrArrayBuffer) {
  65701. try {
  65702. if (typeof (urlOrArrayBuffer) === "string") {
  65703. this._urlType = "String";
  65704. }
  65705. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  65706. this._urlType = "ArrayBuffer";
  65707. }
  65708. else if (urlOrArrayBuffer instanceof MediaStream) {
  65709. this._urlType = "MediaStream";
  65710. }
  65711. else if (Array.isArray(urlOrArrayBuffer)) {
  65712. this._urlType = "Array";
  65713. }
  65714. var urls = [];
  65715. var codecSupportedFound = false;
  65716. switch (this._urlType) {
  65717. case "MediaStream":
  65718. this._streaming = true;
  65719. this._isReadyToPlay = true;
  65720. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  65721. if (this.autoplay) {
  65722. this.play();
  65723. }
  65724. if (this._readyToPlayCallback) {
  65725. this._readyToPlayCallback();
  65726. }
  65727. break;
  65728. case "ArrayBuffer":
  65729. if (urlOrArrayBuffer.byteLength > 0) {
  65730. codecSupportedFound = true;
  65731. this._soundLoaded(urlOrArrayBuffer);
  65732. }
  65733. break;
  65734. case "String":
  65735. urls.push(urlOrArrayBuffer);
  65736. case "Array":
  65737. if (urls.length === 0)
  65738. urls = urlOrArrayBuffer;
  65739. // If we found a supported format, we load it immediately and stop the loop
  65740. for (var i = 0; i < urls.length; i++) {
  65741. var url = urls[i];
  65742. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  65743. codecSupportedFound = true;
  65744. }
  65745. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  65746. codecSupportedFound = true;
  65747. }
  65748. if (url.indexOf(".wav", url.length - 4) !== -1) {
  65749. codecSupportedFound = true;
  65750. }
  65751. if (url.indexOf("blob:") !== -1) {
  65752. codecSupportedFound = true;
  65753. }
  65754. if (codecSupportedFound) {
  65755. // Loading sound using XHR2
  65756. if (!this._streaming) {
  65757. this._scene._loadFile(url, function (data) {
  65758. _this._soundLoaded(data);
  65759. }, undefined, true, true, function (exception) {
  65760. if (exception) {
  65761. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  65762. }
  65763. BABYLON.Tools.Error("Sound creation aborted.");
  65764. _this._scene.mainSoundTrack.RemoveSound(_this);
  65765. });
  65766. }
  65767. // Streaming sound using HTML5 Audio tag
  65768. else {
  65769. this._htmlAudioElement = new Audio(url);
  65770. this._htmlAudioElement.controls = false;
  65771. this._htmlAudioElement.loop = this.loop;
  65772. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  65773. this._htmlAudioElement.preload = "auto";
  65774. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  65775. _this._isReadyToPlay = true;
  65776. if (_this.autoplay) {
  65777. _this.play();
  65778. }
  65779. if (_this._readyToPlayCallback) {
  65780. _this._readyToPlayCallback();
  65781. }
  65782. });
  65783. document.body.appendChild(this._htmlAudioElement);
  65784. }
  65785. break;
  65786. }
  65787. }
  65788. break;
  65789. default:
  65790. validParameter = false;
  65791. break;
  65792. }
  65793. if (!validParameter) {
  65794. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  65795. }
  65796. else {
  65797. if (!codecSupportedFound) {
  65798. this._isReadyToPlay = true;
  65799. // Simulating a ready to play event to avoid breaking code path
  65800. if (this._readyToPlayCallback) {
  65801. window.setTimeout(function () {
  65802. if (_this._readyToPlayCallback) {
  65803. _this._readyToPlayCallback();
  65804. }
  65805. }, 1000);
  65806. }
  65807. }
  65808. }
  65809. }
  65810. catch (ex) {
  65811. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  65812. this._scene.mainSoundTrack.RemoveSound(this);
  65813. }
  65814. }
  65815. }
  65816. else {
  65817. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  65818. this._scene.mainSoundTrack.AddSound(this);
  65819. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  65820. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  65821. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  65822. }
  65823. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  65824. if (this._readyToPlayCallback) {
  65825. window.setTimeout(function () {
  65826. if (_this._readyToPlayCallback) {
  65827. _this._readyToPlayCallback();
  65828. }
  65829. }, 1000);
  65830. }
  65831. }
  65832. }
  65833. Sound.prototype.dispose = function () {
  65834. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65835. if (this.isPlaying) {
  65836. this.stop();
  65837. }
  65838. this._isReadyToPlay = false;
  65839. if (this.soundTrackId === -1) {
  65840. this._scene.mainSoundTrack.RemoveSound(this);
  65841. }
  65842. else if (this._scene.soundTracks) {
  65843. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  65844. }
  65845. if (this._soundGain) {
  65846. this._soundGain.disconnect();
  65847. this._soundGain = null;
  65848. }
  65849. if (this._soundPanner) {
  65850. this._soundPanner.disconnect();
  65851. this._soundPanner = null;
  65852. }
  65853. if (this._soundSource) {
  65854. this._soundSource.disconnect();
  65855. this._soundSource = null;
  65856. }
  65857. this._audioBuffer = null;
  65858. if (this._htmlAudioElement) {
  65859. this._htmlAudioElement.pause();
  65860. this._htmlAudioElement.src = "";
  65861. document.body.removeChild(this._htmlAudioElement);
  65862. }
  65863. if (this._streamingSource) {
  65864. this._streamingSource.disconnect();
  65865. }
  65866. if (this._connectedMesh && this._registerFunc) {
  65867. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65868. this._connectedMesh = null;
  65869. }
  65870. }
  65871. };
  65872. Sound.prototype.isReady = function () {
  65873. return this._isReadyToPlay;
  65874. };
  65875. Sound.prototype._soundLoaded = function (audioData) {
  65876. var _this = this;
  65877. if (!BABYLON.Engine.audioEngine.audioContext) {
  65878. return;
  65879. }
  65880. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  65881. _this._audioBuffer = buffer;
  65882. _this._isReadyToPlay = true;
  65883. if (_this.autoplay) {
  65884. _this.play();
  65885. }
  65886. if (_this._readyToPlayCallback) {
  65887. _this._readyToPlayCallback();
  65888. }
  65889. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  65890. };
  65891. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  65892. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65893. this._audioBuffer = audioBuffer;
  65894. this._isReadyToPlay = true;
  65895. }
  65896. };
  65897. Sound.prototype.updateOptions = function (options) {
  65898. if (options) {
  65899. this.loop = options.loop || this.loop;
  65900. this.maxDistance = options.maxDistance || this.maxDistance;
  65901. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  65902. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  65903. this.refDistance = options.refDistance || this.refDistance;
  65904. this.distanceModel = options.distanceModel || this.distanceModel;
  65905. this._playbackRate = options.playbackRate || this._playbackRate;
  65906. this._updateSpatialParameters();
  65907. if (this.isPlaying) {
  65908. if (this._streaming && this._htmlAudioElement) {
  65909. this._htmlAudioElement.playbackRate = this._playbackRate;
  65910. }
  65911. else {
  65912. if (this._soundSource) {
  65913. this._soundSource.playbackRate.value = this._playbackRate;
  65914. }
  65915. }
  65916. }
  65917. }
  65918. };
  65919. Sound.prototype._createSpatialParameters = function () {
  65920. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65921. if (this._scene.headphone) {
  65922. this._panningModel = "HRTF";
  65923. }
  65924. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  65925. this._updateSpatialParameters();
  65926. this._soundPanner.connect(this._outputAudioNode);
  65927. this._inputAudioNode = this._soundPanner;
  65928. }
  65929. };
  65930. Sound.prototype._updateSpatialParameters = function () {
  65931. if (this.spatialSound && this._soundPanner) {
  65932. if (this.useCustomAttenuation) {
  65933. // Tricks to disable in a way embedded Web Audio attenuation
  65934. this._soundPanner.distanceModel = "linear";
  65935. this._soundPanner.maxDistance = Number.MAX_VALUE;
  65936. this._soundPanner.refDistance = 1;
  65937. this._soundPanner.rolloffFactor = 1;
  65938. this._soundPanner.panningModel = this._panningModel;
  65939. }
  65940. else {
  65941. this._soundPanner.distanceModel = this.distanceModel;
  65942. this._soundPanner.maxDistance = this.maxDistance;
  65943. this._soundPanner.refDistance = this.refDistance;
  65944. this._soundPanner.rolloffFactor = this.rolloffFactor;
  65945. this._soundPanner.panningModel = this._panningModel;
  65946. }
  65947. }
  65948. };
  65949. Sound.prototype.switchPanningModelToHRTF = function () {
  65950. this._panningModel = "HRTF";
  65951. this._switchPanningModel();
  65952. };
  65953. Sound.prototype.switchPanningModelToEqualPower = function () {
  65954. this._panningModel = "equalpower";
  65955. this._switchPanningModel();
  65956. };
  65957. Sound.prototype._switchPanningModel = function () {
  65958. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65959. this._soundPanner.panningModel = this._panningModel;
  65960. }
  65961. };
  65962. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  65963. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65964. if (this._isOutputConnected) {
  65965. this._outputAudioNode.disconnect();
  65966. }
  65967. this._outputAudioNode.connect(soundTrackAudioNode);
  65968. this._isOutputConnected = true;
  65969. }
  65970. };
  65971. /**
  65972. * Transform this sound into a directional source
  65973. * @param coneInnerAngle Size of the inner cone in degree
  65974. * @param coneOuterAngle Size of the outer cone in degree
  65975. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  65976. */
  65977. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  65978. if (coneOuterAngle < coneInnerAngle) {
  65979. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  65980. return;
  65981. }
  65982. this._coneInnerAngle = coneInnerAngle;
  65983. this._coneOuterAngle = coneOuterAngle;
  65984. this._coneOuterGain = coneOuterGain;
  65985. this._isDirectional = true;
  65986. if (this.isPlaying && this.loop) {
  65987. this.stop();
  65988. this.play();
  65989. }
  65990. };
  65991. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  65992. /**
  65993. * Gets or sets the inner angle for the directional cone.
  65994. */
  65995. get: function () {
  65996. return this._coneInnerAngle;
  65997. },
  65998. /**
  65999. * Gets or sets the inner angle for the directional cone.
  66000. */
  66001. set: function (value) {
  66002. if (value != this._coneInnerAngle) {
  66003. if (this._coneOuterAngle < value) {
  66004. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66005. return;
  66006. }
  66007. this._coneInnerAngle = value;
  66008. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66009. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  66010. }
  66011. }
  66012. },
  66013. enumerable: true,
  66014. configurable: true
  66015. });
  66016. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  66017. /**
  66018. * Gets or sets the outer angle for the directional cone.
  66019. */
  66020. get: function () {
  66021. return this._coneOuterAngle;
  66022. },
  66023. /**
  66024. * Gets or sets the outer angle for the directional cone.
  66025. */
  66026. set: function (value) {
  66027. if (value != this._coneOuterAngle) {
  66028. if (value < this._coneInnerAngle) {
  66029. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66030. return;
  66031. }
  66032. this._coneOuterAngle = value;
  66033. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66034. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  66035. }
  66036. }
  66037. },
  66038. enumerable: true,
  66039. configurable: true
  66040. });
  66041. Sound.prototype.setPosition = function (newPosition) {
  66042. this._position = newPosition;
  66043. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  66044. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  66045. }
  66046. };
  66047. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  66048. this._localDirection = newLocalDirection;
  66049. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  66050. this._updateDirection();
  66051. }
  66052. };
  66053. Sound.prototype._updateDirection = function () {
  66054. if (!this._connectedMesh || !this._soundPanner) {
  66055. return;
  66056. }
  66057. var mat = this._connectedMesh.getWorldMatrix();
  66058. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  66059. direction.normalize();
  66060. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  66061. };
  66062. Sound.prototype.updateDistanceFromListener = function () {
  66063. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  66064. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  66065. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  66066. }
  66067. };
  66068. Sound.prototype.setAttenuationFunction = function (callback) {
  66069. this._customAttenuationFunction = callback;
  66070. };
  66071. /**
  66072. * Play the sound
  66073. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  66074. * @param offset (optional) Start the sound setting it at a specific time
  66075. */
  66076. Sound.prototype.play = function (time, offset) {
  66077. var _this = this;
  66078. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  66079. try {
  66080. if (this._startOffset < 0) {
  66081. time = -this._startOffset;
  66082. this._startOffset = 0;
  66083. }
  66084. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  66085. if (!this._soundSource || !this._streamingSource) {
  66086. if (this.spatialSound && this._soundPanner) {
  66087. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  66088. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  66089. }
  66090. if (this._isDirectional) {
  66091. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  66092. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  66093. this._soundPanner.coneOuterGain = this._coneOuterGain;
  66094. if (this._connectedMesh) {
  66095. this._updateDirection();
  66096. }
  66097. else {
  66098. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  66099. }
  66100. }
  66101. }
  66102. }
  66103. if (this._streaming) {
  66104. if (!this._streamingSource) {
  66105. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  66106. this._htmlAudioElement.onended = function () { _this._onended(); };
  66107. this._htmlAudioElement.playbackRate = this._playbackRate;
  66108. }
  66109. this._streamingSource.disconnect();
  66110. this._streamingSource.connect(this._inputAudioNode);
  66111. if (this._htmlAudioElement) {
  66112. this._htmlAudioElement.play();
  66113. }
  66114. }
  66115. else {
  66116. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  66117. this._soundSource.buffer = this._audioBuffer;
  66118. this._soundSource.connect(this._inputAudioNode);
  66119. this._soundSource.loop = this.loop;
  66120. this._soundSource.playbackRate.value = this._playbackRate;
  66121. this._soundSource.onended = function () { _this._onended(); };
  66122. if (this._soundSource.buffer) {
  66123. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  66124. }
  66125. }
  66126. this._startTime = startTime;
  66127. this.isPlaying = true;
  66128. this.isPaused = false;
  66129. }
  66130. catch (ex) {
  66131. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  66132. }
  66133. }
  66134. };
  66135. Sound.prototype._onended = function () {
  66136. this.isPlaying = false;
  66137. if (this.onended) {
  66138. this.onended();
  66139. }
  66140. this.onEndedObservable.notifyObservers(this);
  66141. };
  66142. /**
  66143. * Stop the sound
  66144. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  66145. */
  66146. Sound.prototype.stop = function (time) {
  66147. if (this.isPlaying) {
  66148. if (this._streaming) {
  66149. if (this._htmlAudioElement) {
  66150. this._htmlAudioElement.pause();
  66151. // Test needed for Firefox or it will generate an Invalid State Error
  66152. if (this._htmlAudioElement.currentTime > 0) {
  66153. this._htmlAudioElement.currentTime = 0;
  66154. }
  66155. }
  66156. else {
  66157. this._streamingSource.disconnect();
  66158. }
  66159. }
  66160. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  66161. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  66162. this._soundSource.stop(stopTime);
  66163. this._soundSource.onended = function () { };
  66164. if (!this.isPaused) {
  66165. this._startOffset = 0;
  66166. }
  66167. }
  66168. this.isPlaying = false;
  66169. }
  66170. };
  66171. Sound.prototype.pause = function () {
  66172. if (this.isPlaying) {
  66173. this.isPaused = true;
  66174. if (this._streaming) {
  66175. if (this._htmlAudioElement) {
  66176. this._htmlAudioElement.pause();
  66177. }
  66178. else {
  66179. this._streamingSource.disconnect();
  66180. }
  66181. }
  66182. else if (BABYLON.Engine.audioEngine.audioContext) {
  66183. this.stop(0);
  66184. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  66185. }
  66186. }
  66187. };
  66188. Sound.prototype.setVolume = function (newVolume, time) {
  66189. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  66190. if (time && BABYLON.Engine.audioEngine.audioContext) {
  66191. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  66192. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  66193. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  66194. }
  66195. else {
  66196. this._soundGain.gain.value = newVolume;
  66197. }
  66198. }
  66199. this._volume = newVolume;
  66200. };
  66201. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  66202. this._playbackRate = newPlaybackRate;
  66203. if (this.isPlaying) {
  66204. if (this._streaming && this._htmlAudioElement) {
  66205. this._htmlAudioElement.playbackRate = this._playbackRate;
  66206. }
  66207. else if (this._soundSource) {
  66208. this._soundSource.playbackRate.value = this._playbackRate;
  66209. }
  66210. }
  66211. };
  66212. Sound.prototype.getVolume = function () {
  66213. return this._volume;
  66214. };
  66215. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  66216. var _this = this;
  66217. if (this._connectedMesh && this._registerFunc) {
  66218. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66219. this._registerFunc = null;
  66220. }
  66221. this._connectedMesh = meshToConnectTo;
  66222. if (!this.spatialSound) {
  66223. this.spatialSound = true;
  66224. this._createSpatialParameters();
  66225. if (this.isPlaying && this.loop) {
  66226. this.stop();
  66227. this.play();
  66228. }
  66229. }
  66230. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  66231. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  66232. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  66233. };
  66234. Sound.prototype.detachFromMesh = function () {
  66235. if (this._connectedMesh && this._registerFunc) {
  66236. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66237. this._registerFunc = null;
  66238. this._connectedMesh = null;
  66239. }
  66240. };
  66241. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  66242. if (!node.getBoundingInfo) {
  66243. return;
  66244. }
  66245. var mesh = node;
  66246. if (this._positionInEmitterSpace) {
  66247. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  66248. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  66249. }
  66250. else {
  66251. var boundingInfo = mesh.getBoundingInfo();
  66252. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  66253. }
  66254. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  66255. this._updateDirection();
  66256. }
  66257. };
  66258. Sound.prototype.clone = function () {
  66259. var _this = this;
  66260. if (!this._streaming) {
  66261. var setBufferAndRun = function () {
  66262. if (_this._isReadyToPlay) {
  66263. clonedSound._audioBuffer = _this.getAudioBuffer();
  66264. clonedSound._isReadyToPlay = true;
  66265. if (clonedSound.autoplay) {
  66266. clonedSound.play();
  66267. }
  66268. }
  66269. else {
  66270. window.setTimeout(setBufferAndRun, 300);
  66271. }
  66272. };
  66273. var currentOptions = {
  66274. autoplay: this.autoplay, loop: this.loop,
  66275. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  66276. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  66277. refDistance: this.refDistance, distanceModel: this.distanceModel
  66278. };
  66279. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  66280. if (this.useCustomAttenuation) {
  66281. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  66282. }
  66283. clonedSound.setPosition(this._position);
  66284. clonedSound.setPlaybackRate(this._playbackRate);
  66285. setBufferAndRun();
  66286. return clonedSound;
  66287. }
  66288. // Can't clone a streaming sound
  66289. else {
  66290. return null;
  66291. }
  66292. };
  66293. Sound.prototype.getAudioBuffer = function () {
  66294. return this._audioBuffer;
  66295. };
  66296. Sound.prototype.serialize = function () {
  66297. var serializationObject = {
  66298. name: this.name,
  66299. url: this.name,
  66300. autoplay: this.autoplay,
  66301. loop: this.loop,
  66302. volume: this._volume,
  66303. spatialSound: this.spatialSound,
  66304. maxDistance: this.maxDistance,
  66305. rolloffFactor: this.rolloffFactor,
  66306. refDistance: this.refDistance,
  66307. distanceModel: this.distanceModel,
  66308. playbackRate: this._playbackRate,
  66309. panningModel: this._panningModel,
  66310. soundTrackId: this.soundTrackId
  66311. };
  66312. if (this.spatialSound) {
  66313. if (this._connectedMesh)
  66314. serializationObject.connectedMeshId = this._connectedMesh.id;
  66315. serializationObject.position = this._position.asArray();
  66316. serializationObject.refDistance = this.refDistance;
  66317. serializationObject.distanceModel = this.distanceModel;
  66318. serializationObject.isDirectional = this._isDirectional;
  66319. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  66320. serializationObject.coneInnerAngle = this._coneInnerAngle;
  66321. serializationObject.coneOuterAngle = this._coneOuterAngle;
  66322. serializationObject.coneOuterGain = this._coneOuterGain;
  66323. }
  66324. return serializationObject;
  66325. };
  66326. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  66327. var soundName = parsedSound.name;
  66328. var soundUrl;
  66329. if (parsedSound.url) {
  66330. soundUrl = rootUrl + parsedSound.url;
  66331. }
  66332. else {
  66333. soundUrl = rootUrl + soundName;
  66334. }
  66335. var options = {
  66336. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  66337. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  66338. rolloffFactor: parsedSound.rolloffFactor,
  66339. refDistance: parsedSound.refDistance,
  66340. distanceModel: parsedSound.distanceModel,
  66341. playbackRate: parsedSound.playbackRate
  66342. };
  66343. var newSound;
  66344. if (!sourceSound) {
  66345. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  66346. scene._addPendingData(newSound);
  66347. }
  66348. else {
  66349. var setBufferAndRun = function () {
  66350. if (sourceSound._isReadyToPlay) {
  66351. newSound._audioBuffer = sourceSound.getAudioBuffer();
  66352. newSound._isReadyToPlay = true;
  66353. if (newSound.autoplay) {
  66354. newSound.play();
  66355. }
  66356. }
  66357. else {
  66358. window.setTimeout(setBufferAndRun, 300);
  66359. }
  66360. };
  66361. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  66362. setBufferAndRun();
  66363. }
  66364. if (parsedSound.position) {
  66365. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  66366. newSound.setPosition(soundPosition);
  66367. }
  66368. if (parsedSound.isDirectional) {
  66369. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  66370. if (parsedSound.localDirectionToMesh) {
  66371. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  66372. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  66373. }
  66374. }
  66375. if (parsedSound.connectedMeshId) {
  66376. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  66377. if (connectedMesh) {
  66378. newSound.attachToMesh(connectedMesh);
  66379. }
  66380. }
  66381. return newSound;
  66382. };
  66383. return Sound;
  66384. }());
  66385. BABYLON.Sound = Sound;
  66386. })(BABYLON || (BABYLON = {}));
  66387. //# sourceMappingURL=babylon.sound.js.map
  66388. var BABYLON;
  66389. (function (BABYLON) {
  66390. var SoundTrack = /** @class */ (function () {
  66391. function SoundTrack(scene, options) {
  66392. this.id = -1;
  66393. this._isMainTrack = false;
  66394. this._isInitialized = false;
  66395. this._scene = scene;
  66396. this.soundCollection = new Array();
  66397. this._options = options;
  66398. if (!this._isMainTrack && this._scene.soundTracks) {
  66399. this._scene.soundTracks.push(this);
  66400. this.id = this._scene.soundTracks.length - 1;
  66401. }
  66402. }
  66403. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  66404. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  66405. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  66406. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  66407. if (this._options) {
  66408. if (this._options.volume) {
  66409. this._outputAudioNode.gain.value = this._options.volume;
  66410. }
  66411. if (this._options.mainTrack) {
  66412. this._isMainTrack = this._options.mainTrack;
  66413. }
  66414. }
  66415. this._isInitialized = true;
  66416. }
  66417. };
  66418. SoundTrack.prototype.dispose = function () {
  66419. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  66420. if (this._connectedAnalyser) {
  66421. this._connectedAnalyser.stopDebugCanvas();
  66422. }
  66423. while (this.soundCollection.length) {
  66424. this.soundCollection[0].dispose();
  66425. }
  66426. if (this._outputAudioNode) {
  66427. this._outputAudioNode.disconnect();
  66428. }
  66429. this._outputAudioNode = null;
  66430. }
  66431. };
  66432. SoundTrack.prototype.AddSound = function (sound) {
  66433. if (!this._isInitialized) {
  66434. this._initializeSoundTrackAudioGraph();
  66435. }
  66436. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66437. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  66438. }
  66439. if (sound.soundTrackId) {
  66440. if (sound.soundTrackId === -1) {
  66441. this._scene.mainSoundTrack.RemoveSound(sound);
  66442. }
  66443. else if (this._scene.soundTracks) {
  66444. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  66445. }
  66446. }
  66447. this.soundCollection.push(sound);
  66448. sound.soundTrackId = this.id;
  66449. };
  66450. SoundTrack.prototype.RemoveSound = function (sound) {
  66451. var index = this.soundCollection.indexOf(sound);
  66452. if (index !== -1) {
  66453. this.soundCollection.splice(index, 1);
  66454. }
  66455. };
  66456. SoundTrack.prototype.setVolume = function (newVolume) {
  66457. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66458. this._outputAudioNode.gain.value = newVolume;
  66459. }
  66460. };
  66461. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  66462. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66463. for (var i = 0; i < this.soundCollection.length; i++) {
  66464. this.soundCollection[i].switchPanningModelToHRTF();
  66465. }
  66466. }
  66467. };
  66468. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  66469. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66470. for (var i = 0; i < this.soundCollection.length; i++) {
  66471. this.soundCollection[i].switchPanningModelToEqualPower();
  66472. }
  66473. }
  66474. };
  66475. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  66476. if (this._connectedAnalyser) {
  66477. this._connectedAnalyser.stopDebugCanvas();
  66478. }
  66479. this._connectedAnalyser = analyser;
  66480. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66481. this._outputAudioNode.disconnect();
  66482. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  66483. }
  66484. };
  66485. return SoundTrack;
  66486. }());
  66487. BABYLON.SoundTrack = SoundTrack;
  66488. })(BABYLON || (BABYLON = {}));
  66489. //# sourceMappingURL=babylon.soundtrack.js.map
  66490. var BABYLON;
  66491. (function (BABYLON) {
  66492. /**
  66493. * Class used to work with sound analyzer using fast fourier transform (FFT)
  66494. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  66495. */
  66496. var Analyser = /** @class */ (function () {
  66497. /**
  66498. * Creates a new analyser
  66499. * @param scene defines hosting scene
  66500. */
  66501. function Analyser(scene) {
  66502. /**
  66503. * Gets or sets the smoothing
  66504. * @ignorenaming
  66505. */
  66506. this.SMOOTHING = 0.75;
  66507. /**
  66508. * Gets or sets the FFT table size
  66509. * @ignorenaming
  66510. */
  66511. this.FFT_SIZE = 512;
  66512. /**
  66513. * Gets or sets the bar graph amplitude
  66514. * @ignorenaming
  66515. */
  66516. this.BARGRAPHAMPLITUDE = 256;
  66517. /**
  66518. * Gets or sets the position of the debug canvas
  66519. * @ignorenaming
  66520. */
  66521. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  66522. /**
  66523. * Gets or sets the debug canvas size
  66524. * @ignorenaming
  66525. */
  66526. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  66527. this._scene = scene;
  66528. this._audioEngine = BABYLON.Engine.audioEngine;
  66529. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  66530. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  66531. this._webAudioAnalyser.minDecibels = -140;
  66532. this._webAudioAnalyser.maxDecibels = 0;
  66533. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66534. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66535. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  66536. }
  66537. }
  66538. /**
  66539. * Get the number of data values you will have to play with for the visualization
  66540. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  66541. * @returns a number
  66542. */
  66543. Analyser.prototype.getFrequencyBinCount = function () {
  66544. if (this._audioEngine.canUseWebAudio) {
  66545. return this._webAudioAnalyser.frequencyBinCount;
  66546. }
  66547. else {
  66548. return 0;
  66549. }
  66550. };
  66551. /**
  66552. * Gets the current frequency data as a byte array
  66553. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66554. * @returns a Uint8Array
  66555. */
  66556. Analyser.prototype.getByteFrequencyData = function () {
  66557. if (this._audioEngine.canUseWebAudio) {
  66558. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66559. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66560. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  66561. }
  66562. return this._byteFreqs;
  66563. };
  66564. /**
  66565. * Gets the current waveform as a byte array
  66566. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  66567. * @returns a Uint8Array
  66568. */
  66569. Analyser.prototype.getByteTimeDomainData = function () {
  66570. if (this._audioEngine.canUseWebAudio) {
  66571. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66572. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66573. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  66574. }
  66575. return this._byteTime;
  66576. };
  66577. /**
  66578. * Gets the current frequency data as a float array
  66579. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66580. * @returns a Float32Array
  66581. */
  66582. Analyser.prototype.getFloatFrequencyData = function () {
  66583. if (this._audioEngine.canUseWebAudio) {
  66584. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66585. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66586. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  66587. }
  66588. return this._floatFreqs;
  66589. };
  66590. /**
  66591. * Renders the debug canvas
  66592. */
  66593. Analyser.prototype.drawDebugCanvas = function () {
  66594. var _this = this;
  66595. if (this._audioEngine.canUseWebAudio) {
  66596. if (!this._debugCanvas) {
  66597. this._debugCanvas = document.createElement("canvas");
  66598. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  66599. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  66600. this._debugCanvas.style.position = "absolute";
  66601. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  66602. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  66603. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  66604. document.body.appendChild(this._debugCanvas);
  66605. this._registerFunc = function () {
  66606. _this.drawDebugCanvas();
  66607. };
  66608. this._scene.registerBeforeRender(this._registerFunc);
  66609. }
  66610. if (this._registerFunc && this._debugCanvasContext) {
  66611. var workingArray = this.getByteFrequencyData();
  66612. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  66613. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  66614. // Draw the frequency domain chart.
  66615. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  66616. var value = workingArray[i];
  66617. var percent = value / this.BARGRAPHAMPLITUDE;
  66618. var height = this.DEBUGCANVASSIZE.height * percent;
  66619. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  66620. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  66621. var hue = i / this.getFrequencyBinCount() * 360;
  66622. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  66623. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  66624. }
  66625. }
  66626. }
  66627. };
  66628. /**
  66629. * Stops rendering the debug canvas and removes it
  66630. */
  66631. Analyser.prototype.stopDebugCanvas = function () {
  66632. if (this._debugCanvas) {
  66633. if (this._registerFunc) {
  66634. this._scene.unregisterBeforeRender(this._registerFunc);
  66635. this._registerFunc = null;
  66636. }
  66637. document.body.removeChild(this._debugCanvas);
  66638. this._debugCanvas = null;
  66639. this._debugCanvasContext = null;
  66640. }
  66641. };
  66642. /**
  66643. * Connects two audio nodes
  66644. * @param inputAudioNode defines first node to connect
  66645. * @param outputAudioNode defines second node to connect
  66646. */
  66647. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  66648. if (this._audioEngine.canUseWebAudio) {
  66649. inputAudioNode.connect(this._webAudioAnalyser);
  66650. this._webAudioAnalyser.connect(outputAudioNode);
  66651. }
  66652. };
  66653. /**
  66654. * Releases all associated resources
  66655. */
  66656. Analyser.prototype.dispose = function () {
  66657. if (this._audioEngine.canUseWebAudio) {
  66658. this._webAudioAnalyser.disconnect();
  66659. }
  66660. };
  66661. return Analyser;
  66662. }());
  66663. BABYLON.Analyser = Analyser;
  66664. })(BABYLON || (BABYLON = {}));
  66665. //# sourceMappingURL=babylon.analyser.js.map
  66666. var BABYLON;
  66667. (function (BABYLON) {
  66668. /**
  66669. * Wraps one or more Sound objects and selects one with random weight for playback.
  66670. */
  66671. var WeightedSound = /** @class */ (function () {
  66672. /**
  66673. * Creates a new WeightedSound from the list of sounds given.
  66674. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  66675. * @param sounds Array of Sounds that will be selected from.
  66676. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  66677. */
  66678. function WeightedSound(loop, sounds, weights) {
  66679. var _this = this;
  66680. /** When true a Sound will be selected and played when the current playing Sound completes. */
  66681. this.loop = false;
  66682. this._coneInnerAngle = 360;
  66683. this._coneOuterAngle = 360;
  66684. this._volume = 1;
  66685. /** A Sound is currently playing. */
  66686. this.isPlaying = false;
  66687. /** A Sound is currently paused. */
  66688. this.isPaused = false;
  66689. this._sounds = [];
  66690. this._weights = [];
  66691. if (sounds.length !== weights.length) {
  66692. throw new Error('Sounds length does not equal weights length');
  66693. }
  66694. this.loop = loop;
  66695. this._weights = weights;
  66696. // Normalize the weights
  66697. var weightSum = 0;
  66698. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  66699. var weight = weights_1[_i];
  66700. weightSum += weight;
  66701. }
  66702. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  66703. for (var i = 0; i < this._weights.length; i++) {
  66704. this._weights[i] *= invWeightSum;
  66705. }
  66706. this._sounds = sounds;
  66707. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  66708. var sound = _b[_a];
  66709. sound.onEndedObservable.add(function () { _this._onended(); });
  66710. }
  66711. }
  66712. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  66713. /**
  66714. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  66715. */
  66716. get: function () {
  66717. return this._coneInnerAngle;
  66718. },
  66719. /**
  66720. * The size of cone in degress for a directional sound in which there will be no attenuation.
  66721. */
  66722. set: function (value) {
  66723. if (value !== this._coneInnerAngle) {
  66724. if (this._coneOuterAngle < value) {
  66725. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66726. return;
  66727. }
  66728. this._coneInnerAngle = value;
  66729. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66730. var sound = _a[_i];
  66731. sound.directionalConeInnerAngle = value;
  66732. }
  66733. }
  66734. },
  66735. enumerable: true,
  66736. configurable: true
  66737. });
  66738. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  66739. /**
  66740. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66741. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66742. */
  66743. get: function () {
  66744. return this._coneOuterAngle;
  66745. },
  66746. /**
  66747. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66748. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66749. */
  66750. set: function (value) {
  66751. if (value !== this._coneOuterAngle) {
  66752. if (value < this._coneInnerAngle) {
  66753. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66754. return;
  66755. }
  66756. this._coneOuterAngle = value;
  66757. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66758. var sound = _a[_i];
  66759. sound.directionalConeOuterAngle = value;
  66760. }
  66761. }
  66762. },
  66763. enumerable: true,
  66764. configurable: true
  66765. });
  66766. Object.defineProperty(WeightedSound.prototype, "volume", {
  66767. /**
  66768. * Playback volume.
  66769. */
  66770. get: function () {
  66771. return this._volume;
  66772. },
  66773. /**
  66774. * Playback volume.
  66775. */
  66776. set: function (value) {
  66777. if (value !== this._volume) {
  66778. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66779. var sound = _a[_i];
  66780. sound.setVolume(value);
  66781. }
  66782. }
  66783. },
  66784. enumerable: true,
  66785. configurable: true
  66786. });
  66787. WeightedSound.prototype._onended = function () {
  66788. if (this._currentIndex !== undefined) {
  66789. this._sounds[this._currentIndex].autoplay = false;
  66790. }
  66791. if (this.loop && this.isPlaying) {
  66792. this.play();
  66793. }
  66794. else {
  66795. this.isPlaying = false;
  66796. }
  66797. };
  66798. /**
  66799. * Suspend playback
  66800. */
  66801. WeightedSound.prototype.pause = function () {
  66802. this.isPaused = true;
  66803. if (this._currentIndex !== undefined) {
  66804. this._sounds[this._currentIndex].pause();
  66805. }
  66806. };
  66807. /**
  66808. * Stop playback
  66809. */
  66810. WeightedSound.prototype.stop = function () {
  66811. this.isPlaying = false;
  66812. if (this._currentIndex !== undefined) {
  66813. this._sounds[this._currentIndex].stop();
  66814. }
  66815. };
  66816. /**
  66817. * Start playback.
  66818. * @param startOffset Position the clip head at a specific time in seconds.
  66819. */
  66820. WeightedSound.prototype.play = function (startOffset) {
  66821. if (!this.isPaused) {
  66822. this.stop();
  66823. var randomValue = Math.random();
  66824. var total = 0;
  66825. for (var i = 0; i < this._weights.length; i++) {
  66826. total += this._weights[i];
  66827. if (randomValue <= total) {
  66828. this._currentIndex = i;
  66829. break;
  66830. }
  66831. }
  66832. }
  66833. var sound = this._sounds[this._currentIndex];
  66834. if (sound.isReady()) {
  66835. sound.play(0, this.isPaused ? undefined : startOffset);
  66836. }
  66837. else {
  66838. sound.autoplay = true;
  66839. }
  66840. this.isPlaying = true;
  66841. this.isPaused = false;
  66842. };
  66843. return WeightedSound;
  66844. }());
  66845. BABYLON.WeightedSound = WeightedSound;
  66846. })(BABYLON || (BABYLON = {}));
  66847. //# sourceMappingURL=babylon.weightedsound.js.map
  66848. var BABYLON;
  66849. (function (BABYLON) {
  66850. // Adds the parser to the scene parsers.
  66851. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  66852. // TODO: add sound
  66853. var loadedSounds = [];
  66854. var loadedSound;
  66855. container.sounds = container.sounds || [];
  66856. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  66857. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  66858. var parsedSound = parsedData.sounds[index];
  66859. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66860. if (!parsedSound.url)
  66861. parsedSound.url = parsedSound.name;
  66862. if (!loadedSounds[parsedSound.url]) {
  66863. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  66864. loadedSounds[parsedSound.url] = loadedSound;
  66865. container.sounds.push(loadedSound);
  66866. }
  66867. else {
  66868. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  66869. }
  66870. }
  66871. else {
  66872. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  66873. }
  66874. }
  66875. }
  66876. loadedSounds = [];
  66877. });
  66878. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  66879. get: function () {
  66880. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  66881. if (!compo) {
  66882. compo = new AudioSceneComponent(this);
  66883. this._addComponent(compo);
  66884. }
  66885. if (!this._mainSoundTrack) {
  66886. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  66887. }
  66888. return this._mainSoundTrack;
  66889. },
  66890. enumerable: true,
  66891. configurable: true
  66892. });
  66893. BABYLON.Scene.prototype.getSoundByName = function (name) {
  66894. var index;
  66895. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  66896. if (this.mainSoundTrack.soundCollection[index].name === name) {
  66897. return this.mainSoundTrack.soundCollection[index];
  66898. }
  66899. }
  66900. if (this.soundTracks) {
  66901. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  66902. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  66903. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  66904. return this.soundTracks[sdIndex].soundCollection[index];
  66905. }
  66906. }
  66907. }
  66908. }
  66909. return null;
  66910. };
  66911. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  66912. get: function () {
  66913. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  66914. if (!compo) {
  66915. compo = new AudioSceneComponent(this);
  66916. this._addComponent(compo);
  66917. }
  66918. return compo.audioEnabled;
  66919. },
  66920. set: function (value) {
  66921. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  66922. if (!compo) {
  66923. compo = new AudioSceneComponent(this);
  66924. this._addComponent(compo);
  66925. }
  66926. if (value) {
  66927. compo.enableAudio();
  66928. }
  66929. else {
  66930. compo.disableAudio();
  66931. }
  66932. },
  66933. enumerable: true,
  66934. configurable: true
  66935. });
  66936. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  66937. get: function () {
  66938. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  66939. if (!compo) {
  66940. compo = new AudioSceneComponent(this);
  66941. this._addComponent(compo);
  66942. }
  66943. return compo.headphone;
  66944. },
  66945. set: function (value) {
  66946. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  66947. if (!compo) {
  66948. compo = new AudioSceneComponent(this);
  66949. this._addComponent(compo);
  66950. }
  66951. if (value) {
  66952. compo.switchAudioModeForHeadphones();
  66953. }
  66954. else {
  66955. compo.switchAudioModeForNormalSpeakers();
  66956. }
  66957. },
  66958. enumerable: true,
  66959. configurable: true
  66960. });
  66961. /**
  66962. * Defines the sound scene component responsible to manage any sounds
  66963. * in a given scene.
  66964. */
  66965. var AudioSceneComponent = /** @class */ (function () {
  66966. /**
  66967. * Creates a new instance of the component for the given scene
  66968. * @param scene Defines the scene to register the component in
  66969. */
  66970. function AudioSceneComponent(scene) {
  66971. /**
  66972. * The component name helpfull to identify the component in the list of scene components.
  66973. */
  66974. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  66975. this._audioEnabled = true;
  66976. this._headphone = false;
  66977. this.scene = scene;
  66978. scene.soundTracks = new Array();
  66979. scene.sounds = new Array();
  66980. }
  66981. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  66982. /**
  66983. * Gets whether audio is enabled or not.
  66984. * Please use related enable/disable method to switch state.
  66985. */
  66986. get: function () {
  66987. return this._audioEnabled;
  66988. },
  66989. enumerable: true,
  66990. configurable: true
  66991. });
  66992. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  66993. /**
  66994. * Gets whether audio is outputing to headphone or not.
  66995. * Please use the according Switch methods to change output.
  66996. */
  66997. get: function () {
  66998. return this._headphone;
  66999. },
  67000. enumerable: true,
  67001. configurable: true
  67002. });
  67003. /**
  67004. * Registers the component in a given scene
  67005. */
  67006. AudioSceneComponent.prototype.register = function () {
  67007. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  67008. };
  67009. /**
  67010. * Rebuilds the elements related to this component in case of
  67011. * context lost for instance.
  67012. */
  67013. AudioSceneComponent.prototype.rebuild = function () {
  67014. // Nothing to do here. (Not rendering related)
  67015. };
  67016. /**
  67017. * Serializes the component data to the specified json object
  67018. * @param serializationObject The object to serialize to
  67019. */
  67020. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  67021. serializationObject.sounds = [];
  67022. if (this.scene.soundTracks) {
  67023. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  67024. var soundtrack = this.scene.soundTracks[index];
  67025. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  67026. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  67027. }
  67028. }
  67029. }
  67030. };
  67031. /**
  67032. * Adds all the element from the container to the scene
  67033. * @param container the container holding the elements
  67034. */
  67035. AudioSceneComponent.prototype.addFromContainer = function (container) {
  67036. var _this = this;
  67037. if (!container.sounds) {
  67038. return;
  67039. }
  67040. container.sounds.forEach(function (sound) {
  67041. sound.play();
  67042. sound.autoplay = true;
  67043. _this.scene.mainSoundTrack.AddSound(sound);
  67044. });
  67045. };
  67046. /**
  67047. * Removes all the elements in the container from the scene
  67048. * @param container contains the elements to remove
  67049. */
  67050. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  67051. var _this = this;
  67052. if (!container.sounds) {
  67053. return;
  67054. }
  67055. container.sounds.forEach(function (sound) {
  67056. sound.stop();
  67057. sound.autoplay = false;
  67058. _this.scene.mainSoundTrack.RemoveSound(sound);
  67059. });
  67060. };
  67061. /**
  67062. * Disposes the component and the associated ressources.
  67063. */
  67064. AudioSceneComponent.prototype.dispose = function () {
  67065. var scene = this.scene;
  67066. if (scene._mainSoundTrack) {
  67067. scene.mainSoundTrack.dispose();
  67068. }
  67069. if (scene.soundTracks) {
  67070. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  67071. scene.soundTracks[scIndex].dispose();
  67072. }
  67073. }
  67074. };
  67075. /**
  67076. * Disables audio in the associated scene.
  67077. */
  67078. AudioSceneComponent.prototype.disableAudio = function () {
  67079. var scene = this.scene;
  67080. this._audioEnabled = false;
  67081. var i;
  67082. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  67083. scene.mainSoundTrack.soundCollection[i].pause();
  67084. }
  67085. if (scene.soundTracks) {
  67086. for (i = 0; i < scene.soundTracks.length; i++) {
  67087. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  67088. scene.soundTracks[i].soundCollection[j].pause();
  67089. }
  67090. }
  67091. }
  67092. };
  67093. /**
  67094. * Enables audio in the associated scene.
  67095. */
  67096. AudioSceneComponent.prototype.enableAudio = function () {
  67097. var scene = this.scene;
  67098. this._audioEnabled = true;
  67099. var i;
  67100. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  67101. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  67102. scene.mainSoundTrack.soundCollection[i].play();
  67103. }
  67104. }
  67105. if (scene.soundTracks) {
  67106. for (i = 0; i < scene.soundTracks.length; i++) {
  67107. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  67108. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  67109. scene.soundTracks[i].soundCollection[j].play();
  67110. }
  67111. }
  67112. }
  67113. }
  67114. };
  67115. /**
  67116. * Switch audio to headphone output.
  67117. */
  67118. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  67119. var scene = this.scene;
  67120. this._headphone = true;
  67121. scene.mainSoundTrack.switchPanningModelToHRTF();
  67122. if (scene.soundTracks) {
  67123. for (var i = 0; i < scene.soundTracks.length; i++) {
  67124. scene.soundTracks[i].switchPanningModelToHRTF();
  67125. }
  67126. }
  67127. };
  67128. /**
  67129. * Switch audio to normal speakers.
  67130. */
  67131. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  67132. var scene = this.scene;
  67133. this._headphone = false;
  67134. scene.mainSoundTrack.switchPanningModelToEqualPower();
  67135. if (scene.soundTracks) {
  67136. for (var i = 0; i < scene.soundTracks.length; i++) {
  67137. scene.soundTracks[i].switchPanningModelToEqualPower();
  67138. }
  67139. }
  67140. };
  67141. AudioSceneComponent.prototype._afterRender = function () {
  67142. var scene = this.scene;
  67143. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  67144. return;
  67145. }
  67146. var listeningCamera;
  67147. var audioEngine = BABYLON.Engine.audioEngine;
  67148. if (scene.activeCameras.length > 0) {
  67149. listeningCamera = scene.activeCameras[0];
  67150. }
  67151. else {
  67152. listeningCamera = scene.activeCamera;
  67153. }
  67154. if (listeningCamera && audioEngine.audioContext) {
  67155. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  67156. // for VR cameras
  67157. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  67158. listeningCamera = listeningCamera.rigCameras[0];
  67159. }
  67160. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  67161. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  67162. cameraDirection.normalize();
  67163. // To avoid some errors on GearVR
  67164. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  67165. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  67166. }
  67167. var i;
  67168. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  67169. var sound = scene.mainSoundTrack.soundCollection[i];
  67170. if (sound.useCustomAttenuation) {
  67171. sound.updateDistanceFromListener();
  67172. }
  67173. }
  67174. if (scene.soundTracks) {
  67175. for (i = 0; i < scene.soundTracks.length; i++) {
  67176. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  67177. sound = scene.soundTracks[i].soundCollection[j];
  67178. if (sound.useCustomAttenuation) {
  67179. sound.updateDistanceFromListener();
  67180. }
  67181. }
  67182. }
  67183. }
  67184. }
  67185. };
  67186. return AudioSceneComponent;
  67187. }());
  67188. BABYLON.AudioSceneComponent = AudioSceneComponent;
  67189. })(BABYLON || (BABYLON = {}));
  67190. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  67191. var BABYLON;
  67192. (function (BABYLON) {
  67193. /**
  67194. * This defines an action helpful to play a defined sound on a triggered action.
  67195. */
  67196. var PlaySoundAction = /** @class */ (function (_super) {
  67197. __extends(PlaySoundAction, _super);
  67198. /**
  67199. * Instantiate the action
  67200. * @param triggerOptions defines the trigger options
  67201. * @param sound defines the sound to play
  67202. * @param condition defines the trigger related conditions
  67203. */
  67204. function PlaySoundAction(triggerOptions, sound, condition) {
  67205. var _this = _super.call(this, triggerOptions, condition) || this;
  67206. _this._sound = sound;
  67207. return _this;
  67208. }
  67209. /** @hidden */
  67210. PlaySoundAction.prototype._prepare = function () {
  67211. };
  67212. /**
  67213. * Execute the action and play the sound.
  67214. */
  67215. PlaySoundAction.prototype.execute = function () {
  67216. if (this._sound !== undefined)
  67217. this._sound.play();
  67218. };
  67219. /**
  67220. * Serializes the actions and its related information.
  67221. * @param parent defines the object to serialize in
  67222. * @returns the serialized object
  67223. */
  67224. PlaySoundAction.prototype.serialize = function (parent) {
  67225. return _super.prototype._serialize.call(this, {
  67226. name: "PlaySoundAction",
  67227. properties: [{ name: "sound", value: this._sound.name }]
  67228. }, parent);
  67229. };
  67230. return PlaySoundAction;
  67231. }(BABYLON.Action));
  67232. BABYLON.PlaySoundAction = PlaySoundAction;
  67233. /**
  67234. * This defines an action helpful to stop a defined sound on a triggered action.
  67235. */
  67236. var StopSoundAction = /** @class */ (function (_super) {
  67237. __extends(StopSoundAction, _super);
  67238. /**
  67239. * Instantiate the action
  67240. * @param triggerOptions defines the trigger options
  67241. * @param sound defines the sound to stop
  67242. * @param condition defines the trigger related conditions
  67243. */
  67244. function StopSoundAction(triggerOptions, sound, condition) {
  67245. var _this = _super.call(this, triggerOptions, condition) || this;
  67246. _this._sound = sound;
  67247. return _this;
  67248. }
  67249. /** @hidden */
  67250. StopSoundAction.prototype._prepare = function () {
  67251. };
  67252. /**
  67253. * Execute the action and stop the sound.
  67254. */
  67255. StopSoundAction.prototype.execute = function () {
  67256. if (this._sound !== undefined)
  67257. this._sound.stop();
  67258. };
  67259. /**
  67260. * Serializes the actions and its related information.
  67261. * @param parent defines the object to serialize in
  67262. * @returns the serialized object
  67263. */
  67264. StopSoundAction.prototype.serialize = function (parent) {
  67265. return _super.prototype._serialize.call(this, {
  67266. name: "StopSoundAction",
  67267. properties: [{ name: "sound", value: this._sound.name }]
  67268. }, parent);
  67269. };
  67270. return StopSoundAction;
  67271. }(BABYLON.Action));
  67272. BABYLON.StopSoundAction = StopSoundAction;
  67273. })(BABYLON || (BABYLON = {}));
  67274. //# sourceMappingURL=babylon.directAudioActions.js.map
  67275. var BABYLON;
  67276. (function (BABYLON) {
  67277. var CubeTexture = /** @class */ (function (_super) {
  67278. __extends(CubeTexture, _super);
  67279. /**
  67280. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  67281. * as prefiltered data.
  67282. * @param rootUrl defines the url of the texture or the root name of the six images
  67283. * @param scene defines the scene the texture is attached to
  67284. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  67285. * @param noMipmap defines if mipmaps should be created or not
  67286. * @param files defines the six files to load for the different faces
  67287. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  67288. * @param onError defines a callback triggered in case of error during load
  67289. * @param format defines the internal format to use for the texture once loaded
  67290. * @param prefiltered defines whether or not the texture is created from prefiltered data
  67291. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  67292. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  67293. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  67294. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  67295. * @return the cube texture
  67296. */
  67297. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  67298. if (extensions === void 0) { extensions = null; }
  67299. if (noMipmap === void 0) { noMipmap = false; }
  67300. if (files === void 0) { files = null; }
  67301. if (onLoad === void 0) { onLoad = null; }
  67302. if (onError === void 0) { onError = null; }
  67303. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67304. if (prefiltered === void 0) { prefiltered = false; }
  67305. if (forcedExtension === void 0) { forcedExtension = null; }
  67306. if (createPolynomials === void 0) { createPolynomials = false; }
  67307. if (lodScale === void 0) { lodScale = 0.8; }
  67308. if (lodOffset === void 0) { lodOffset = 0; }
  67309. var _this = _super.call(this, scene) || this;
  67310. /**
  67311. * Gets or sets the center of the bounding box associated with the cube texture
  67312. * It must define where the camera used to render the texture was set
  67313. */
  67314. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  67315. _this._rotationY = 0;
  67316. /** @hidden */
  67317. _this._prefiltered = false;
  67318. _this.name = rootUrl;
  67319. _this.url = rootUrl;
  67320. _this._noMipmap = noMipmap;
  67321. _this.hasAlpha = false;
  67322. _this._format = format;
  67323. _this.isCube = true;
  67324. _this._textureMatrix = BABYLON.Matrix.Identity();
  67325. _this._createPolynomials = createPolynomials;
  67326. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  67327. if (!rootUrl && !files) {
  67328. return _this;
  67329. }
  67330. var lastDot = rootUrl.lastIndexOf(".");
  67331. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  67332. var isDDS = (extension === ".dds");
  67333. var isEnv = (extension === ".env");
  67334. if (isEnv) {
  67335. _this.gammaSpace = false;
  67336. _this._prefiltered = false;
  67337. }
  67338. else {
  67339. _this._prefiltered = prefiltered;
  67340. if (prefiltered) {
  67341. _this.gammaSpace = false;
  67342. }
  67343. }
  67344. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  67345. if (!files) {
  67346. if (!isEnv && !isDDS && !extensions) {
  67347. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  67348. }
  67349. files = [];
  67350. if (extensions) {
  67351. for (var index = 0; index < extensions.length; index++) {
  67352. files.push(rootUrl + extensions[index]);
  67353. }
  67354. }
  67355. }
  67356. _this._files = files;
  67357. if (!_this._texture) {
  67358. if (!scene.useDelayedTextureLoading) {
  67359. if (prefiltered) {
  67360. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  67361. }
  67362. else {
  67363. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  67364. }
  67365. }
  67366. else {
  67367. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  67368. }
  67369. }
  67370. else if (onLoad) {
  67371. if (_this._texture.isReady) {
  67372. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  67373. }
  67374. else {
  67375. _this._texture.onLoadedObservable.add(onLoad);
  67376. }
  67377. }
  67378. return _this;
  67379. }
  67380. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  67381. get: function () {
  67382. return this._boundingBoxSize;
  67383. },
  67384. /**
  67385. * Gets or sets the size of the bounding box associated with the cube texture
  67386. * When defined, the cubemap will switch to local mode
  67387. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  67388. * @example https://www.babylonjs-playground.com/#RNASML
  67389. */
  67390. set: function (value) {
  67391. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  67392. return;
  67393. }
  67394. this._boundingBoxSize = value;
  67395. var scene = this.getScene();
  67396. if (scene) {
  67397. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  67398. }
  67399. },
  67400. enumerable: true,
  67401. configurable: true
  67402. });
  67403. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  67404. /**
  67405. * Gets texture matrix rotation angle around Y axis radians.
  67406. */
  67407. get: function () {
  67408. return this._rotationY;
  67409. },
  67410. /**
  67411. * Sets texture matrix rotation angle around Y axis in radians.
  67412. */
  67413. set: function (value) {
  67414. this._rotationY = value;
  67415. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  67416. },
  67417. enumerable: true,
  67418. configurable: true
  67419. });
  67420. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  67421. var rootUrlKey = "";
  67422. files.forEach(function (url) { return rootUrlKey += url; });
  67423. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  67424. };
  67425. /**
  67426. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  67427. * @param url defines the url of the prefiltered texture
  67428. * @param scene defines the scene the texture is attached to
  67429. * @param forcedExtension defines the extension of the file if different from the url
  67430. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  67431. * @return the prefiltered texture
  67432. */
  67433. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  67434. if (forcedExtension === void 0) { forcedExtension = null; }
  67435. if (createPolynomials === void 0) { createPolynomials = true; }
  67436. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  67437. };
  67438. // Methods
  67439. CubeTexture.prototype.delayLoad = function () {
  67440. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  67441. return;
  67442. }
  67443. var scene = this.getScene();
  67444. if (!scene) {
  67445. return;
  67446. }
  67447. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  67448. this._texture = this._getFromCache(this.url, this._noMipmap);
  67449. if (!this._texture) {
  67450. if (this._prefiltered) {
  67451. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  67452. }
  67453. else {
  67454. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  67455. }
  67456. }
  67457. };
  67458. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  67459. return this._textureMatrix;
  67460. };
  67461. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  67462. this._textureMatrix = value;
  67463. };
  67464. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  67465. var texture = BABYLON.SerializationHelper.Parse(function () {
  67466. var prefiltered = false;
  67467. if (parsedTexture.prefiltered) {
  67468. prefiltered = parsedTexture.prefiltered;
  67469. }
  67470. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  67471. }, parsedTexture, scene);
  67472. // Local Cubemaps
  67473. if (parsedTexture.boundingBoxPosition) {
  67474. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  67475. }
  67476. if (parsedTexture.boundingBoxSize) {
  67477. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  67478. }
  67479. // Animations
  67480. if (parsedTexture.animations) {
  67481. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  67482. var parsedAnimation = parsedTexture.animations[animationIndex];
  67483. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  67484. }
  67485. }
  67486. return texture;
  67487. };
  67488. CubeTexture.prototype.clone = function () {
  67489. var _this = this;
  67490. return BABYLON.SerializationHelper.Clone(function () {
  67491. var scene = _this.getScene();
  67492. if (!scene) {
  67493. return _this;
  67494. }
  67495. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  67496. }, this);
  67497. };
  67498. __decorate([
  67499. BABYLON.serialize("rotationY")
  67500. ], CubeTexture.prototype, "rotationY", null);
  67501. return CubeTexture;
  67502. }(BABYLON.BaseTexture));
  67503. BABYLON.CubeTexture = CubeTexture;
  67504. })(BABYLON || (BABYLON = {}));
  67505. //# sourceMappingURL=babylon.cubeTexture.js.map
  67506. var BABYLON;
  67507. (function (BABYLON) {
  67508. /**
  67509. * Raw cube texture where the raw buffers are passed in
  67510. */
  67511. var RawCubeTexture = /** @class */ (function (_super) {
  67512. __extends(RawCubeTexture, _super);
  67513. /**
  67514. * Creates a cube texture where the raw buffers are passed in.
  67515. * @param scene defines the scene the texture is attached to
  67516. * @param data defines the array of data to use to create each face
  67517. * @param size defines the size of the textures
  67518. * @param format defines the format of the data
  67519. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  67520. * @param generateMipMaps defines if the engine should generate the mip levels
  67521. * @param invertY defines if data must be stored with Y axis inverted
  67522. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  67523. * @param compression defines the compression used (null by default)
  67524. */
  67525. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  67526. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67527. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67528. if (generateMipMaps === void 0) { generateMipMaps = false; }
  67529. if (invertY === void 0) { invertY = false; }
  67530. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67531. if (compression === void 0) { compression = null; }
  67532. var _this = _super.call(this, "", scene) || this;
  67533. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  67534. return _this;
  67535. }
  67536. /**
  67537. * Updates the raw cube texture.
  67538. * @param data defines the data to store
  67539. * @param format defines the data format
  67540. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  67541. * @param invertY defines if data must be stored with Y axis inverted
  67542. * @param compression defines the compression used (null by default)
  67543. * @param level defines which level of the texture to update
  67544. */
  67545. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  67546. if (compression === void 0) { compression = null; }
  67547. if (level === void 0) { level = 0; }
  67548. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  67549. };
  67550. /**
  67551. * Updates a raw cube texture with RGBD encoded data.
  67552. * @param data defines the array of data [mipmap][face] to use to create each face
  67553. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  67554. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  67555. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  67556. * @returns a promsie that resolves when the operation is complete
  67557. */
  67558. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  67559. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  67560. if (lodScale === void 0) { lodScale = 0.8; }
  67561. if (lodOffset === void 0) { lodOffset = 0; }
  67562. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  67563. };
  67564. /**
  67565. * Clones the raw cube texture.
  67566. * @return a new cube texture
  67567. */
  67568. RawCubeTexture.prototype.clone = function () {
  67569. var _this = this;
  67570. return BABYLON.SerializationHelper.Clone(function () {
  67571. var scene = _this.getScene();
  67572. var internalTexture = _this._texture;
  67573. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  67574. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  67575. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  67576. }
  67577. return texture;
  67578. }, this);
  67579. };
  67580. /** @hidden */
  67581. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  67582. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  67583. internalTexture._bufferViewArrayArray = data;
  67584. internalTexture._lodGenerationScale = lodScale;
  67585. internalTexture._lodGenerationOffset = lodOffset;
  67586. internalTexture._sphericalPolynomial = sphericalPolynomial;
  67587. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  67588. internalTexture.isReady = true;
  67589. });
  67590. };
  67591. return RawCubeTexture;
  67592. }(BABYLON.CubeTexture));
  67593. BABYLON.RawCubeTexture = RawCubeTexture;
  67594. })(BABYLON || (BABYLON = {}));
  67595. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  67596. var BABYLON;
  67597. (function (BABYLON) {
  67598. var RenderTargetTexture = /** @class */ (function (_super) {
  67599. __extends(RenderTargetTexture, _super);
  67600. /**
  67601. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  67602. * or used a shadow, depth texture...
  67603. * @param name The friendly name of the texture
  67604. * @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)
  67605. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  67606. * @param generateMipMaps True if mip maps need to be generated after render.
  67607. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  67608. * @param type The type of the buffer in the RTT (int, half float, float...)
  67609. * @param isCube True if a cube texture needs to be created
  67610. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  67611. * @param generateDepthBuffer True to generate a depth buffer
  67612. * @param generateStencilBuffer True to generate a stencil buffer
  67613. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  67614. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  67615. */
  67616. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  67617. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  67618. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67619. if (isCube === void 0) { isCube = false; }
  67620. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67621. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  67622. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  67623. if (isMulti === void 0) { isMulti = false; }
  67624. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67625. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  67626. _this.isCube = isCube;
  67627. _this.renderParticles = true;
  67628. _this.renderSprites = false;
  67629. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  67630. _this.ignoreCameraViewport = false;
  67631. // Events
  67632. /**
  67633. * An event triggered when the texture is unbind.
  67634. */
  67635. _this.onBeforeBindObservable = new BABYLON.Observable();
  67636. /**
  67637. * An event triggered when the texture is unbind.
  67638. */
  67639. _this.onAfterUnbindObservable = new BABYLON.Observable();
  67640. /**
  67641. * An event triggered before rendering the texture
  67642. */
  67643. _this.onBeforeRenderObservable = new BABYLON.Observable();
  67644. /**
  67645. * An event triggered after rendering the texture
  67646. */
  67647. _this.onAfterRenderObservable = new BABYLON.Observable();
  67648. /**
  67649. * An event triggered after the texture clear
  67650. */
  67651. _this.onClearObservable = new BABYLON.Observable();
  67652. _this._currentRefreshId = -1;
  67653. _this._refreshRate = 1;
  67654. _this._samples = 1;
  67655. /**
  67656. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  67657. * It must define where the camera used to render the texture is set
  67658. */
  67659. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  67660. scene = _this.getScene();
  67661. if (!scene) {
  67662. return _this;
  67663. }
  67664. _this.renderList = new Array();
  67665. _this._engine = scene.getEngine();
  67666. _this.name = name;
  67667. _this.isRenderTarget = true;
  67668. _this._initialSizeParameter = size;
  67669. _this._processSizeParameter(size);
  67670. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  67671. });
  67672. _this._generateMipMaps = generateMipMaps ? true : false;
  67673. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  67674. // Rendering groups
  67675. _this._renderingManager = new BABYLON.RenderingManager(scene);
  67676. _this._renderingManager._useSceneAutoClearSetup = true;
  67677. if (isMulti) {
  67678. return _this;
  67679. }
  67680. _this._renderTargetOptions = {
  67681. generateMipMaps: generateMipMaps,
  67682. type: type,
  67683. format: format,
  67684. samplingMode: samplingMode,
  67685. generateDepthBuffer: generateDepthBuffer,
  67686. generateStencilBuffer: generateStencilBuffer
  67687. };
  67688. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  67689. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67690. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67691. }
  67692. if (isCube) {
  67693. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  67694. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  67695. _this._textureMatrix = BABYLON.Matrix.Identity();
  67696. }
  67697. else {
  67698. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  67699. }
  67700. return _this;
  67701. }
  67702. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  67703. get: function () {
  67704. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  67705. },
  67706. enumerable: true,
  67707. configurable: true
  67708. });
  67709. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  67710. get: function () {
  67711. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  67712. },
  67713. enumerable: true,
  67714. configurable: true
  67715. });
  67716. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  67717. get: function () {
  67718. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  67719. },
  67720. enumerable: true,
  67721. configurable: true
  67722. });
  67723. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  67724. /**
  67725. * Use this list to define the list of mesh you want to render.
  67726. */
  67727. get: function () {
  67728. return this._renderList;
  67729. },
  67730. set: function (value) {
  67731. this._renderList = value;
  67732. if (this._renderList) {
  67733. this._hookArray(this._renderList);
  67734. }
  67735. },
  67736. enumerable: true,
  67737. configurable: true
  67738. });
  67739. RenderTargetTexture.prototype._hookArray = function (array) {
  67740. var _this = this;
  67741. var oldPush = array.push;
  67742. array.push = function () {
  67743. var items = [];
  67744. for (var _i = 0; _i < arguments.length; _i++) {
  67745. items[_i] = arguments[_i];
  67746. }
  67747. var result = oldPush.apply(array, items);
  67748. _this.getScene().meshes.forEach(function (mesh) {
  67749. mesh._markSubMeshesAsLightDirty();
  67750. });
  67751. return result;
  67752. };
  67753. var oldSplice = array.splice;
  67754. array.splice = function (index, deleteCount) {
  67755. var deleted = oldSplice.apply(array, [index, deleteCount]);
  67756. _this.getScene().meshes.forEach(function (mesh) {
  67757. mesh._markSubMeshesAsLightDirty();
  67758. });
  67759. return deleted;
  67760. };
  67761. };
  67762. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  67763. set: function (callback) {
  67764. if (this._onAfterUnbindObserver) {
  67765. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  67766. }
  67767. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  67768. },
  67769. enumerable: true,
  67770. configurable: true
  67771. });
  67772. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  67773. set: function (callback) {
  67774. if (this._onBeforeRenderObserver) {
  67775. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67776. }
  67777. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67778. },
  67779. enumerable: true,
  67780. configurable: true
  67781. });
  67782. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  67783. set: function (callback) {
  67784. if (this._onAfterRenderObserver) {
  67785. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67786. }
  67787. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67788. },
  67789. enumerable: true,
  67790. configurable: true
  67791. });
  67792. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  67793. set: function (callback) {
  67794. if (this._onClearObserver) {
  67795. this.onClearObservable.remove(this._onClearObserver);
  67796. }
  67797. this._onClearObserver = this.onClearObservable.add(callback);
  67798. },
  67799. enumerable: true,
  67800. configurable: true
  67801. });
  67802. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  67803. get: function () {
  67804. return this._renderTargetOptions;
  67805. },
  67806. enumerable: true,
  67807. configurable: true
  67808. });
  67809. RenderTargetTexture.prototype._onRatioRescale = function () {
  67810. if (this._sizeRatio) {
  67811. this.resize(this._initialSizeParameter);
  67812. }
  67813. };
  67814. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  67815. get: function () {
  67816. return this._boundingBoxSize;
  67817. },
  67818. /**
  67819. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  67820. * When defined, the cubemap will switch to local mode
  67821. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  67822. * @example https://www.babylonjs-playground.com/#RNASML
  67823. */
  67824. set: function (value) {
  67825. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  67826. return;
  67827. }
  67828. this._boundingBoxSize = value;
  67829. var scene = this.getScene();
  67830. if (scene) {
  67831. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  67832. }
  67833. },
  67834. enumerable: true,
  67835. configurable: true
  67836. });
  67837. /**
  67838. * Creates a depth stencil texture.
  67839. * This is only available in WebGL 2 or with the depth texture extension available.
  67840. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  67841. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  67842. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  67843. */
  67844. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  67845. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  67846. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  67847. if (generateStencil === void 0) { generateStencil = false; }
  67848. if (!this.getScene()) {
  67849. return;
  67850. }
  67851. var engine = this.getScene().getEngine();
  67852. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  67853. bilinearFiltering: bilinearFiltering,
  67854. comparisonFunction: comparisonFunction,
  67855. generateStencil: generateStencil,
  67856. isCube: this.isCube
  67857. });
  67858. engine.setFrameBufferDepthStencilTexture(this);
  67859. };
  67860. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  67861. if (size.ratio) {
  67862. this._sizeRatio = size.ratio;
  67863. this._size = {
  67864. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  67865. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  67866. };
  67867. }
  67868. else {
  67869. this._size = size;
  67870. }
  67871. };
  67872. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  67873. get: function () {
  67874. return this._samples;
  67875. },
  67876. set: function (value) {
  67877. if (this._samples === value) {
  67878. return;
  67879. }
  67880. var scene = this.getScene();
  67881. if (!scene) {
  67882. return;
  67883. }
  67884. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  67885. },
  67886. enumerable: true,
  67887. configurable: true
  67888. });
  67889. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  67890. this._currentRefreshId = -1;
  67891. };
  67892. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  67893. get: function () {
  67894. return this._refreshRate;
  67895. },
  67896. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  67897. set: function (value) {
  67898. this._refreshRate = value;
  67899. this.resetRefreshCounter();
  67900. },
  67901. enumerable: true,
  67902. configurable: true
  67903. });
  67904. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  67905. if (!this._postProcessManager) {
  67906. var scene = this.getScene();
  67907. if (!scene) {
  67908. return;
  67909. }
  67910. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  67911. this._postProcesses = new Array();
  67912. }
  67913. this._postProcesses.push(postProcess);
  67914. this._postProcesses[0].autoClear = false;
  67915. };
  67916. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  67917. if (!this._postProcesses) {
  67918. return;
  67919. }
  67920. if (dispose) {
  67921. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  67922. var postProcess = _a[_i];
  67923. postProcess.dispose();
  67924. }
  67925. }
  67926. this._postProcesses = [];
  67927. };
  67928. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  67929. if (!this._postProcesses) {
  67930. return;
  67931. }
  67932. var index = this._postProcesses.indexOf(postProcess);
  67933. if (index === -1) {
  67934. return;
  67935. }
  67936. this._postProcesses.splice(index, 1);
  67937. if (this._postProcesses.length > 0) {
  67938. this._postProcesses[0].autoClear = false;
  67939. }
  67940. };
  67941. /** @hidden */
  67942. RenderTargetTexture.prototype._shouldRender = function () {
  67943. if (this._currentRefreshId === -1) { // At least render once
  67944. this._currentRefreshId = 1;
  67945. return true;
  67946. }
  67947. if (this.refreshRate === this._currentRefreshId) {
  67948. this._currentRefreshId = 1;
  67949. return true;
  67950. }
  67951. this._currentRefreshId++;
  67952. return false;
  67953. };
  67954. RenderTargetTexture.prototype.getRenderSize = function () {
  67955. if (this._size.width) {
  67956. return this._size.width;
  67957. }
  67958. return this._size;
  67959. };
  67960. RenderTargetTexture.prototype.getRenderWidth = function () {
  67961. if (this._size.width) {
  67962. return this._size.width;
  67963. }
  67964. return this._size;
  67965. };
  67966. RenderTargetTexture.prototype.getRenderHeight = function () {
  67967. if (this._size.width) {
  67968. return this._size.height;
  67969. }
  67970. return this._size;
  67971. };
  67972. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  67973. get: function () {
  67974. return true;
  67975. },
  67976. enumerable: true,
  67977. configurable: true
  67978. });
  67979. RenderTargetTexture.prototype.scale = function (ratio) {
  67980. var newSize = this.getRenderSize() * ratio;
  67981. this.resize(newSize);
  67982. };
  67983. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  67984. if (this.isCube) {
  67985. return this._textureMatrix;
  67986. }
  67987. return _super.prototype.getReflectionTextureMatrix.call(this);
  67988. };
  67989. RenderTargetTexture.prototype.resize = function (size) {
  67990. this.releaseInternalTexture();
  67991. var scene = this.getScene();
  67992. if (!scene) {
  67993. return;
  67994. }
  67995. this._processSizeParameter(size);
  67996. if (this.isCube) {
  67997. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  67998. }
  67999. else {
  68000. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  68001. }
  68002. };
  68003. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  68004. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  68005. if (dumpForDebug === void 0) { dumpForDebug = false; }
  68006. var scene = this.getScene();
  68007. if (!scene) {
  68008. return;
  68009. }
  68010. var engine = scene.getEngine();
  68011. if (this.useCameraPostProcesses !== undefined) {
  68012. useCameraPostProcess = this.useCameraPostProcesses;
  68013. }
  68014. if (this._waitingRenderList) {
  68015. this.renderList = [];
  68016. for (var index = 0; index < this._waitingRenderList.length; index++) {
  68017. var id = this._waitingRenderList[index];
  68018. var mesh_1 = scene.getMeshByID(id);
  68019. if (mesh_1) {
  68020. this.renderList.push(mesh_1);
  68021. }
  68022. }
  68023. delete this._waitingRenderList;
  68024. }
  68025. // Is predicate defined?
  68026. if (this.renderListPredicate) {
  68027. if (this.renderList) {
  68028. this.renderList.splice(0); // Clear previous renderList
  68029. }
  68030. else {
  68031. this.renderList = [];
  68032. }
  68033. var scene = this.getScene();
  68034. if (!scene) {
  68035. return;
  68036. }
  68037. var sceneMeshes = scene.meshes;
  68038. for (var index = 0; index < sceneMeshes.length; index++) {
  68039. var mesh = sceneMeshes[index];
  68040. if (this.renderListPredicate(mesh)) {
  68041. this.renderList.push(mesh);
  68042. }
  68043. }
  68044. }
  68045. this.onBeforeBindObservable.notifyObservers(this);
  68046. // Set custom projection.
  68047. // Needs to be before binding to prevent changing the aspect ratio.
  68048. var camera;
  68049. if (this.activeCamera) {
  68050. camera = this.activeCamera;
  68051. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  68052. if (this.activeCamera !== scene.activeCamera) {
  68053. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  68054. }
  68055. }
  68056. else {
  68057. camera = scene.activeCamera;
  68058. if (camera) {
  68059. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  68060. }
  68061. }
  68062. // Prepare renderingManager
  68063. this._renderingManager.reset();
  68064. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  68065. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  68066. var sceneRenderId = scene.getRenderId();
  68067. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  68068. var mesh = currentRenderList[meshIndex];
  68069. if (mesh) {
  68070. if (!mesh.isReady(this.refreshRate === 0)) {
  68071. this.resetRefreshCounter();
  68072. continue;
  68073. }
  68074. mesh._preActivateForIntermediateRendering(sceneRenderId);
  68075. var isMasked = void 0;
  68076. if (!this.renderList && camera) {
  68077. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  68078. }
  68079. else {
  68080. isMasked = false;
  68081. }
  68082. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  68083. mesh._activate(sceneRenderId);
  68084. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  68085. var subMesh = mesh.subMeshes[subIndex];
  68086. scene._activeIndices.addCount(subMesh.indexCount, false);
  68087. this._renderingManager.dispatch(subMesh, mesh);
  68088. }
  68089. }
  68090. }
  68091. }
  68092. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  68093. var particleSystem = scene.particleSystems[particleIndex];
  68094. var emitter = particleSystem.emitter;
  68095. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  68096. continue;
  68097. }
  68098. if (currentRenderList.indexOf(emitter) >= 0) {
  68099. this._renderingManager.dispatchParticles(particleSystem);
  68100. }
  68101. }
  68102. if (this.isCube) {
  68103. for (var face = 0; face < 6; face++) {
  68104. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  68105. scene.incrementRenderId();
  68106. scene.resetCachedMaterial();
  68107. }
  68108. }
  68109. else {
  68110. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  68111. }
  68112. this.onAfterUnbindObservable.notifyObservers(this);
  68113. if (scene.activeCamera) {
  68114. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  68115. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  68116. }
  68117. engine.setViewport(scene.activeCamera.viewport);
  68118. }
  68119. scene.resetCachedMaterial();
  68120. };
  68121. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  68122. var minimum = 128;
  68123. var x = renderDimension * scale;
  68124. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  68125. // Ensure we don't exceed the render dimension (while staying POT)
  68126. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  68127. };
  68128. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  68129. var _this = this;
  68130. if (!this._texture) {
  68131. return;
  68132. }
  68133. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  68134. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  68135. });
  68136. };
  68137. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  68138. var scene = this.getScene();
  68139. if (!scene) {
  68140. return;
  68141. }
  68142. var engine = scene.getEngine();
  68143. if (!this._texture) {
  68144. return;
  68145. }
  68146. // Bind
  68147. if (this._postProcessManager) {
  68148. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  68149. }
  68150. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  68151. if (this._texture) {
  68152. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  68153. }
  68154. }
  68155. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  68156. // Clear
  68157. if (this.onClearObservable.hasObservers()) {
  68158. this.onClearObservable.notifyObservers(engine);
  68159. }
  68160. else {
  68161. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  68162. }
  68163. if (!this._doNotChangeAspectRatio) {
  68164. scene.updateTransformMatrix(true);
  68165. }
  68166. // Render
  68167. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  68168. if (this._postProcessManager) {
  68169. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  68170. }
  68171. else if (useCameraPostProcess) {
  68172. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  68173. }
  68174. if (!this._doNotChangeAspectRatio) {
  68175. scene.updateTransformMatrix(true);
  68176. }
  68177. // Dump ?
  68178. if (dumpForDebug) {
  68179. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  68180. }
  68181. // Unbind
  68182. if (!this.isCube || faceIndex === 5) {
  68183. if (this.isCube) {
  68184. if (faceIndex === 5) {
  68185. engine.generateMipMapsForCubemap(this._texture);
  68186. }
  68187. }
  68188. this.unbindFrameBuffer(engine, faceIndex);
  68189. }
  68190. else {
  68191. this.onAfterRenderObservable.notifyObservers(faceIndex);
  68192. }
  68193. };
  68194. /**
  68195. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  68196. * This allowed control for front to back rendering or reversly depending of the special needs.
  68197. *
  68198. * @param renderingGroupId The rendering group id corresponding to its index
  68199. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  68200. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  68201. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  68202. */
  68203. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  68204. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  68205. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  68206. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  68207. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  68208. };
  68209. /**
  68210. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  68211. *
  68212. * @param renderingGroupId The rendering group id corresponding to its index
  68213. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  68214. */
  68215. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  68216. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  68217. this._renderingManager._useSceneAutoClearSetup = false;
  68218. };
  68219. RenderTargetTexture.prototype.clone = function () {
  68220. var textureSize = this.getSize();
  68221. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  68222. // Base texture
  68223. newTexture.hasAlpha = this.hasAlpha;
  68224. newTexture.level = this.level;
  68225. // RenderTarget Texture
  68226. newTexture.coordinatesMode = this.coordinatesMode;
  68227. if (this.renderList) {
  68228. newTexture.renderList = this.renderList.slice(0);
  68229. }
  68230. return newTexture;
  68231. };
  68232. RenderTargetTexture.prototype.serialize = function () {
  68233. if (!this.name) {
  68234. return null;
  68235. }
  68236. var serializationObject = _super.prototype.serialize.call(this);
  68237. serializationObject.renderTargetSize = this.getRenderSize();
  68238. serializationObject.renderList = [];
  68239. if (this.renderList) {
  68240. for (var index = 0; index < this.renderList.length; index++) {
  68241. serializationObject.renderList.push(this.renderList[index].id);
  68242. }
  68243. }
  68244. return serializationObject;
  68245. };
  68246. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  68247. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  68248. var objBuffer = this.getInternalTexture();
  68249. var scene = this.getScene();
  68250. if (objBuffer && scene) {
  68251. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  68252. }
  68253. };
  68254. RenderTargetTexture.prototype.dispose = function () {
  68255. if (this._postProcessManager) {
  68256. this._postProcessManager.dispose();
  68257. this._postProcessManager = null;
  68258. }
  68259. this.clearPostProcesses(true);
  68260. if (this._resizeObserver) {
  68261. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  68262. this._resizeObserver = null;
  68263. }
  68264. this.renderList = null;
  68265. // Remove from custom render targets
  68266. var scene = this.getScene();
  68267. if (!scene) {
  68268. return;
  68269. }
  68270. var index = scene.customRenderTargets.indexOf(this);
  68271. if (index >= 0) {
  68272. scene.customRenderTargets.splice(index, 1);
  68273. }
  68274. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  68275. var camera = _a[_i];
  68276. index = camera.customRenderTargets.indexOf(this);
  68277. if (index >= 0) {
  68278. camera.customRenderTargets.splice(index, 1);
  68279. }
  68280. }
  68281. _super.prototype.dispose.call(this);
  68282. };
  68283. /** @hidden */
  68284. RenderTargetTexture.prototype._rebuild = function () {
  68285. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  68286. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  68287. }
  68288. if (this._postProcessManager) {
  68289. this._postProcessManager._rebuild();
  68290. }
  68291. };
  68292. /**
  68293. * Clear the info related to rendering groups preventing retention point in material dispose.
  68294. */
  68295. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  68296. if (this._renderingManager) {
  68297. this._renderingManager.freeRenderingGroups();
  68298. }
  68299. };
  68300. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  68301. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  68302. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  68303. return RenderTargetTexture;
  68304. }(BABYLON.Texture));
  68305. BABYLON.RenderTargetTexture = RenderTargetTexture;
  68306. })(BABYLON || (BABYLON = {}));
  68307. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  68308. var BABYLON;
  68309. (function (BABYLON) {
  68310. ;
  68311. var MultiRenderTarget = /** @class */ (function (_super) {
  68312. __extends(MultiRenderTarget, _super);
  68313. function MultiRenderTarget(name, size, count, scene, options) {
  68314. var _this = this;
  68315. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  68316. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  68317. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  68318. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  68319. _this._engine = scene.getEngine();
  68320. if (!_this.isSupported) {
  68321. _this.dispose();
  68322. return;
  68323. }
  68324. var types = [];
  68325. var samplingModes = [];
  68326. for (var i = 0; i < count; i++) {
  68327. if (options && options.types && options.types[i] !== undefined) {
  68328. types.push(options.types[i]);
  68329. }
  68330. else {
  68331. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68332. }
  68333. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  68334. samplingModes.push(options.samplingModes[i]);
  68335. }
  68336. else {
  68337. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68338. }
  68339. }
  68340. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  68341. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  68342. _this._size = size;
  68343. _this._multiRenderTargetOptions = {
  68344. samplingModes: samplingModes,
  68345. generateMipMaps: generateMipMaps,
  68346. generateDepthBuffer: generateDepthBuffer,
  68347. generateStencilBuffer: generateStencilBuffer,
  68348. generateDepthTexture: generateDepthTexture,
  68349. types: types,
  68350. textureCount: count
  68351. };
  68352. _this._createInternalTextures();
  68353. _this._createTextures();
  68354. return _this;
  68355. }
  68356. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  68357. get: function () {
  68358. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  68359. },
  68360. enumerable: true,
  68361. configurable: true
  68362. });
  68363. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  68364. get: function () {
  68365. return this._textures;
  68366. },
  68367. enumerable: true,
  68368. configurable: true
  68369. });
  68370. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  68371. get: function () {
  68372. return this._textures[this._textures.length - 1];
  68373. },
  68374. enumerable: true,
  68375. configurable: true
  68376. });
  68377. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  68378. set: function (wrap) {
  68379. if (this._textures) {
  68380. for (var i = 0; i < this._textures.length; i++) {
  68381. this._textures[i].wrapU = wrap;
  68382. }
  68383. }
  68384. },
  68385. enumerable: true,
  68386. configurable: true
  68387. });
  68388. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  68389. set: function (wrap) {
  68390. if (this._textures) {
  68391. for (var i = 0; i < this._textures.length; i++) {
  68392. this._textures[i].wrapV = wrap;
  68393. }
  68394. }
  68395. },
  68396. enumerable: true,
  68397. configurable: true
  68398. });
  68399. /** @hidden */
  68400. MultiRenderTarget.prototype._rebuild = function () {
  68401. this.releaseInternalTextures();
  68402. this._createInternalTextures();
  68403. for (var i = 0; i < this._internalTextures.length; i++) {
  68404. var texture = this._textures[i];
  68405. texture._texture = this._internalTextures[i];
  68406. }
  68407. // Keeps references to frame buffer and stencil/depth buffer
  68408. this._texture = this._internalTextures[0];
  68409. };
  68410. MultiRenderTarget.prototype._createInternalTextures = function () {
  68411. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  68412. };
  68413. MultiRenderTarget.prototype._createTextures = function () {
  68414. this._textures = [];
  68415. for (var i = 0; i < this._internalTextures.length; i++) {
  68416. var texture = new BABYLON.Texture(null, this.getScene());
  68417. texture._texture = this._internalTextures[i];
  68418. this._textures.push(texture);
  68419. }
  68420. // Keeps references to frame buffer and stencil/depth buffer
  68421. this._texture = this._internalTextures[0];
  68422. };
  68423. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  68424. get: function () {
  68425. return this._samples;
  68426. },
  68427. set: function (value) {
  68428. if (this._samples === value) {
  68429. return;
  68430. }
  68431. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  68432. },
  68433. enumerable: true,
  68434. configurable: true
  68435. });
  68436. MultiRenderTarget.prototype.resize = function (size) {
  68437. this.releaseInternalTextures();
  68438. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  68439. this._createInternalTextures();
  68440. };
  68441. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  68442. var _this = this;
  68443. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  68444. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  68445. });
  68446. };
  68447. MultiRenderTarget.prototype.dispose = function () {
  68448. this.releaseInternalTextures();
  68449. _super.prototype.dispose.call(this);
  68450. };
  68451. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  68452. if (!this._internalTextures) {
  68453. return;
  68454. }
  68455. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  68456. if (this._internalTextures[i] !== undefined) {
  68457. this._internalTextures[i].dispose();
  68458. this._internalTextures.splice(i, 1);
  68459. }
  68460. }
  68461. };
  68462. return MultiRenderTarget;
  68463. }(BABYLON.RenderTargetTexture));
  68464. BABYLON.MultiRenderTarget = MultiRenderTarget;
  68465. })(BABYLON || (BABYLON = {}));
  68466. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  68467. var BABYLON;
  68468. (function (BABYLON) {
  68469. var MirrorTexture = /** @class */ (function (_super) {
  68470. __extends(MirrorTexture, _super);
  68471. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  68472. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68473. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68474. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  68475. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  68476. _this.scene = scene;
  68477. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  68478. _this._transformMatrix = BABYLON.Matrix.Zero();
  68479. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  68480. _this._adaptiveBlurKernel = 0;
  68481. _this._blurKernelX = 0;
  68482. _this._blurKernelY = 0;
  68483. _this._blurRatio = 1.0;
  68484. _this.ignoreCameraViewport = true;
  68485. _this._updateGammaSpace();
  68486. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  68487. _this._updateGammaSpace;
  68488. });
  68489. _this.onBeforeRenderObservable.add(function () {
  68490. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  68491. _this._savedViewMatrix = scene.getViewMatrix();
  68492. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  68493. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  68494. scene.clipPlane = _this.mirrorPlane;
  68495. scene.getEngine().cullBackFaces = false;
  68496. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  68497. });
  68498. _this.onAfterRenderObservable.add(function () {
  68499. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  68500. scene.getEngine().cullBackFaces = true;
  68501. scene._mirroredCameraPosition = null;
  68502. delete scene.clipPlane;
  68503. });
  68504. return _this;
  68505. }
  68506. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  68507. get: function () {
  68508. return this._blurRatio;
  68509. },
  68510. set: function (value) {
  68511. if (this._blurRatio === value) {
  68512. return;
  68513. }
  68514. this._blurRatio = value;
  68515. this._preparePostProcesses();
  68516. },
  68517. enumerable: true,
  68518. configurable: true
  68519. });
  68520. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  68521. set: function (value) {
  68522. this._adaptiveBlurKernel = value;
  68523. this._autoComputeBlurKernel();
  68524. },
  68525. enumerable: true,
  68526. configurable: true
  68527. });
  68528. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  68529. set: function (value) {
  68530. this.blurKernelX = value;
  68531. this.blurKernelY = value;
  68532. },
  68533. enumerable: true,
  68534. configurable: true
  68535. });
  68536. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  68537. get: function () {
  68538. return this._blurKernelX;
  68539. },
  68540. set: function (value) {
  68541. if (this._blurKernelX === value) {
  68542. return;
  68543. }
  68544. this._blurKernelX = value;
  68545. this._preparePostProcesses();
  68546. },
  68547. enumerable: true,
  68548. configurable: true
  68549. });
  68550. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  68551. get: function () {
  68552. return this._blurKernelY;
  68553. },
  68554. set: function (value) {
  68555. if (this._blurKernelY === value) {
  68556. return;
  68557. }
  68558. this._blurKernelY = value;
  68559. this._preparePostProcesses();
  68560. },
  68561. enumerable: true,
  68562. configurable: true
  68563. });
  68564. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  68565. var engine = this.getScene().getEngine();
  68566. var dw = this.getRenderWidth() / engine.getRenderWidth();
  68567. var dh = this.getRenderHeight() / engine.getRenderHeight();
  68568. this.blurKernelX = this._adaptiveBlurKernel * dw;
  68569. this.blurKernelY = this._adaptiveBlurKernel * dh;
  68570. };
  68571. MirrorTexture.prototype._onRatioRescale = function () {
  68572. if (this._sizeRatio) {
  68573. this.resize(this._initialSizeParameter);
  68574. if (!this._adaptiveBlurKernel) {
  68575. this._preparePostProcesses();
  68576. }
  68577. }
  68578. if (this._adaptiveBlurKernel) {
  68579. this._autoComputeBlurKernel();
  68580. }
  68581. };
  68582. MirrorTexture.prototype._updateGammaSpace = function () {
  68583. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  68584. };
  68585. MirrorTexture.prototype._preparePostProcesses = function () {
  68586. this.clearPostProcesses(true);
  68587. if (this._blurKernelX && this._blurKernelY) {
  68588. var engine = this.getScene().getEngine();
  68589. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68590. 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);
  68591. this._blurX.autoClear = false;
  68592. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  68593. this._blurX.inputTexture = this._texture;
  68594. }
  68595. else {
  68596. this._blurX.alwaysForcePOT = true;
  68597. }
  68598. 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);
  68599. this._blurY.autoClear = false;
  68600. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  68601. this.addPostProcess(this._blurX);
  68602. this.addPostProcess(this._blurY);
  68603. }
  68604. else {
  68605. if (this._blurY) {
  68606. this.removePostProcess(this._blurY);
  68607. this._blurY.dispose();
  68608. this._blurY = null;
  68609. }
  68610. if (this._blurX) {
  68611. this.removePostProcess(this._blurX);
  68612. this._blurX.dispose();
  68613. this._blurX = null;
  68614. }
  68615. }
  68616. };
  68617. MirrorTexture.prototype.clone = function () {
  68618. var scene = this.getScene();
  68619. if (!scene) {
  68620. return this;
  68621. }
  68622. var textureSize = this.getSize();
  68623. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  68624. // Base texture
  68625. newTexture.hasAlpha = this.hasAlpha;
  68626. newTexture.level = this.level;
  68627. // Mirror Texture
  68628. newTexture.mirrorPlane = this.mirrorPlane.clone();
  68629. if (this.renderList) {
  68630. newTexture.renderList = this.renderList.slice(0);
  68631. }
  68632. return newTexture;
  68633. };
  68634. MirrorTexture.prototype.serialize = function () {
  68635. if (!this.name) {
  68636. return null;
  68637. }
  68638. var serializationObject = _super.prototype.serialize.call(this);
  68639. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  68640. return serializationObject;
  68641. };
  68642. MirrorTexture.prototype.dispose = function () {
  68643. _super.prototype.dispose.call(this);
  68644. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  68645. };
  68646. return MirrorTexture;
  68647. }(BABYLON.RenderTargetTexture));
  68648. BABYLON.MirrorTexture = MirrorTexture;
  68649. })(BABYLON || (BABYLON = {}));
  68650. //# sourceMappingURL=babylon.mirrorTexture.js.map
  68651. var BABYLON;
  68652. (function (BABYLON) {
  68653. /**
  68654. * Creates a refraction texture used by refraction channel of the standard material.
  68655. * @param name the texture name
  68656. * @param size size of the underlying texture
  68657. * @param scene root scene
  68658. */
  68659. var RefractionTexture = /** @class */ (function (_super) {
  68660. __extends(RefractionTexture, _super);
  68661. function RefractionTexture(name, size, scene, generateMipMaps) {
  68662. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  68663. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  68664. _this.depth = 2.0;
  68665. _this.onBeforeRenderObservable.add(function () {
  68666. scene.clipPlane = _this.refractionPlane;
  68667. });
  68668. _this.onAfterRenderObservable.add(function () {
  68669. delete scene.clipPlane;
  68670. });
  68671. return _this;
  68672. }
  68673. RefractionTexture.prototype.clone = function () {
  68674. var scene = this.getScene();
  68675. if (!scene) {
  68676. return this;
  68677. }
  68678. var textureSize = this.getSize();
  68679. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  68680. // Base texture
  68681. newTexture.hasAlpha = this.hasAlpha;
  68682. newTexture.level = this.level;
  68683. // Refraction Texture
  68684. newTexture.refractionPlane = this.refractionPlane.clone();
  68685. if (this.renderList) {
  68686. newTexture.renderList = this.renderList.slice(0);
  68687. }
  68688. newTexture.depth = this.depth;
  68689. return newTexture;
  68690. };
  68691. RefractionTexture.prototype.serialize = function () {
  68692. if (!this.name) {
  68693. return null;
  68694. }
  68695. var serializationObject = _super.prototype.serialize.call(this);
  68696. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  68697. serializationObject.depth = this.depth;
  68698. return serializationObject;
  68699. };
  68700. return RefractionTexture;
  68701. }(BABYLON.RenderTargetTexture));
  68702. BABYLON.RefractionTexture = RefractionTexture;
  68703. })(BABYLON || (BABYLON = {}));
  68704. //# sourceMappingURL=babylon.refractionTexture.js.map
  68705. var BABYLON;
  68706. (function (BABYLON) {
  68707. /**
  68708. * A class extending {BABYLON.Texture} allowing drawing on a texture
  68709. * @see http://doc.babylonjs.com/how_to/dynamictexture
  68710. */
  68711. var DynamicTexture = /** @class */ (function (_super) {
  68712. __extends(DynamicTexture, _super);
  68713. /**
  68714. * Creates a {BABYLON.DynamicTexture}
  68715. * @param name defines the name of the texture
  68716. * @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
  68717. * @param scene defines the scene where you want the texture
  68718. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  68719. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  68720. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  68721. */
  68722. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  68723. if (scene === void 0) { scene = null; }
  68724. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68725. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  68726. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  68727. _this.name = name;
  68728. _this._engine = _this.getScene().getEngine();
  68729. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68730. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68731. _this._generateMipMaps = generateMipMaps;
  68732. if (options.getContext) {
  68733. _this._canvas = options;
  68734. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  68735. }
  68736. else {
  68737. _this._canvas = document.createElement("canvas");
  68738. if (options.width || options.width === 0) {
  68739. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  68740. }
  68741. else {
  68742. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  68743. }
  68744. }
  68745. var textureSize = _this.getSize();
  68746. _this._canvas.width = textureSize.width;
  68747. _this._canvas.height = textureSize.height;
  68748. _this._context = _this._canvas.getContext("2d");
  68749. return _this;
  68750. }
  68751. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  68752. /**
  68753. * Gets the current state of canRescale
  68754. */
  68755. get: function () {
  68756. return true;
  68757. },
  68758. enumerable: true,
  68759. configurable: true
  68760. });
  68761. DynamicTexture.prototype._recreate = function (textureSize) {
  68762. this._canvas.width = textureSize.width;
  68763. this._canvas.height = textureSize.height;
  68764. this.releaseInternalTexture();
  68765. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  68766. };
  68767. /**
  68768. * Scales the texture
  68769. * @param ratio the scale factor to apply to both width and height
  68770. */
  68771. DynamicTexture.prototype.scale = function (ratio) {
  68772. var textureSize = this.getSize();
  68773. textureSize.width *= ratio;
  68774. textureSize.height *= ratio;
  68775. this._recreate(textureSize);
  68776. };
  68777. /**
  68778. * Resizes the texture
  68779. * @param width the new width
  68780. * @param height the new height
  68781. */
  68782. DynamicTexture.prototype.scaleTo = function (width, height) {
  68783. var textureSize = this.getSize();
  68784. textureSize.width = width;
  68785. textureSize.height = height;
  68786. this._recreate(textureSize);
  68787. };
  68788. /**
  68789. * Gets the context of the canvas used by the texture
  68790. * @returns the canvas context of the dynamic texture
  68791. */
  68792. DynamicTexture.prototype.getContext = function () {
  68793. return this._context;
  68794. };
  68795. /**
  68796. * Clears the texture
  68797. */
  68798. DynamicTexture.prototype.clear = function () {
  68799. var size = this.getSize();
  68800. this._context.fillRect(0, 0, size.width, size.height);
  68801. };
  68802. /**
  68803. * Updates the texture
  68804. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  68805. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  68806. */
  68807. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  68808. if (premulAlpha === void 0) { premulAlpha = false; }
  68809. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  68810. };
  68811. /**
  68812. * Draws text onto the texture
  68813. * @param text defines the text to be drawn
  68814. * @param x defines the placement of the text from the left
  68815. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  68816. * @param font defines the font to be used with font-style, font-size, font-name
  68817. * @param color defines the color used for the text
  68818. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  68819. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  68820. * @param update defines whether texture is immediately update (default is true)
  68821. */
  68822. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  68823. if (update === void 0) { update = true; }
  68824. var size = this.getSize();
  68825. if (clearColor) {
  68826. this._context.fillStyle = clearColor;
  68827. this._context.fillRect(0, 0, size.width, size.height);
  68828. }
  68829. this._context.font = font;
  68830. if (x === null || x === undefined) {
  68831. var textSize = this._context.measureText(text);
  68832. x = (size.width - textSize.width) / 2;
  68833. }
  68834. if (y === null || y === undefined) {
  68835. var fontSize = parseInt((font.replace(/\D/g, '')));
  68836. y = (size.height / 2) + (fontSize / 3.65);
  68837. }
  68838. this._context.fillStyle = color;
  68839. this._context.fillText(text, x, y);
  68840. if (update) {
  68841. this.update(invertY);
  68842. }
  68843. };
  68844. /**
  68845. * Clones the texture
  68846. * @returns the clone of the texture.
  68847. */
  68848. DynamicTexture.prototype.clone = function () {
  68849. var scene = this.getScene();
  68850. if (!scene) {
  68851. return this;
  68852. }
  68853. var textureSize = this.getSize();
  68854. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  68855. // Base texture
  68856. newTexture.hasAlpha = this.hasAlpha;
  68857. newTexture.level = this.level;
  68858. // Dynamic Texture
  68859. newTexture.wrapU = this.wrapU;
  68860. newTexture.wrapV = this.wrapV;
  68861. return newTexture;
  68862. };
  68863. /**
  68864. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  68865. * @returns a serialized dynamic texture object
  68866. */
  68867. DynamicTexture.prototype.serialize = function () {
  68868. var scene = this.getScene();
  68869. if (scene && !scene.isReady()) {
  68870. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  68871. }
  68872. var serializationObject = _super.prototype.serialize.call(this);
  68873. serializationObject.base64String = this._canvas.toDataURL();
  68874. serializationObject.invertY = this._invertY;
  68875. serializationObject.samplingMode = this.samplingMode;
  68876. return serializationObject;
  68877. };
  68878. /** @hidden */
  68879. DynamicTexture.prototype._rebuild = function () {
  68880. this.update();
  68881. };
  68882. return DynamicTexture;
  68883. }(BABYLON.Texture));
  68884. BABYLON.DynamicTexture = DynamicTexture;
  68885. })(BABYLON || (BABYLON = {}));
  68886. //# sourceMappingURL=babylon.dynamicTexture.js.map
  68887. var BABYLON;
  68888. (function (BABYLON) {
  68889. var VideoTexture = /** @class */ (function (_super) {
  68890. __extends(VideoTexture, _super);
  68891. /**
  68892. * Creates a video texture.
  68893. * Sample : https://doc.babylonjs.com/how_to/video_texture
  68894. * @param {string | null} name optional name, will detect from video source, if not defined
  68895. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  68896. * @param {BABYLON.Scene} scene is obviously the current scene.
  68897. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  68898. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  68899. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  68900. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  68901. */
  68902. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  68903. if (generateMipMaps === void 0) { generateMipMaps = false; }
  68904. if (invertY === void 0) { invertY = false; }
  68905. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68906. if (settings === void 0) { settings = {
  68907. autoPlay: true,
  68908. loop: true,
  68909. autoUpdateTexture: true,
  68910. }; }
  68911. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68912. _this._onUserActionRequestedObservable = null;
  68913. _this._stillImageCaptured = false;
  68914. _this._poster = false;
  68915. _this._createInternalTexture = function () {
  68916. if (_this._texture != null) {
  68917. if (_this._poster) {
  68918. _this._texture.dispose();
  68919. _this._poster = false;
  68920. }
  68921. else {
  68922. return;
  68923. }
  68924. }
  68925. if (!_this._engine.needPOTTextures ||
  68926. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  68927. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68928. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68929. }
  68930. else {
  68931. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68932. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68933. _this._generateMipMaps = false;
  68934. }
  68935. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  68936. if (!_this.video.autoplay) {
  68937. var oldHandler_1 = _this.video.onplaying;
  68938. var error_1 = false;
  68939. _this.video.onplaying = function () {
  68940. _this.video.onplaying = oldHandler_1;
  68941. _this._texture.isReady = true;
  68942. _this._updateInternalTexture();
  68943. if (!error_1) {
  68944. _this.video.pause();
  68945. }
  68946. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68947. _this.onLoadObservable.notifyObservers(_this);
  68948. }
  68949. };
  68950. var playing = _this.video.play();
  68951. if (playing) {
  68952. playing.then(function () {
  68953. // Everything is good.
  68954. })
  68955. .catch(function () {
  68956. error_1 = true;
  68957. // On Chrome for instance, new policies might prevent playing without user interaction.
  68958. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  68959. _this._onUserActionRequestedObservable.notifyObservers(_this);
  68960. }
  68961. });
  68962. }
  68963. else {
  68964. _this.video.onplaying = oldHandler_1;
  68965. _this._texture.isReady = true;
  68966. _this._updateInternalTexture();
  68967. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68968. _this.onLoadObservable.notifyObservers(_this);
  68969. }
  68970. }
  68971. }
  68972. else {
  68973. _this._texture.isReady = true;
  68974. _this._updateInternalTexture();
  68975. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68976. _this.onLoadObservable.notifyObservers(_this);
  68977. }
  68978. }
  68979. };
  68980. _this.reset = function () {
  68981. if (_this._texture == null) {
  68982. return;
  68983. }
  68984. if (!_this._poster) {
  68985. _this._texture.dispose();
  68986. _this._texture = null;
  68987. }
  68988. };
  68989. _this._updateInternalTexture = function (e) {
  68990. if (_this._texture == null || !_this._texture.isReady) {
  68991. return;
  68992. }
  68993. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  68994. return;
  68995. }
  68996. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  68997. };
  68998. _this._engine = _this.getScene().getEngine();
  68999. _this._generateMipMaps = generateMipMaps;
  69000. _this._samplingMode = samplingMode;
  69001. _this.autoUpdateTexture = settings.autoUpdateTexture;
  69002. _this.name = name || _this._getName(src);
  69003. _this.video = _this._getVideo(src);
  69004. if (settings.poster) {
  69005. _this.video.poster = settings.poster;
  69006. }
  69007. if (settings.autoPlay !== undefined) {
  69008. _this.video.autoplay = settings.autoPlay;
  69009. }
  69010. if (settings.loop !== undefined) {
  69011. _this.video.loop = settings.loop;
  69012. }
  69013. _this.video.setAttribute("playsinline", "");
  69014. _this.video.addEventListener("canplay", _this._createInternalTexture);
  69015. _this.video.addEventListener("paused", _this._updateInternalTexture);
  69016. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  69017. _this.video.addEventListener("emptied", _this.reset);
  69018. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  69019. _this._createInternalTexture();
  69020. }
  69021. if (settings.poster) {
  69022. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  69023. _this._poster = true;
  69024. }
  69025. return _this;
  69026. }
  69027. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  69028. get: function () {
  69029. if (!this._onUserActionRequestedObservable) {
  69030. this._onUserActionRequestedObservable = new BABYLON.Observable();
  69031. }
  69032. return this._onUserActionRequestedObservable;
  69033. },
  69034. enumerable: true,
  69035. configurable: true
  69036. });
  69037. VideoTexture.prototype._getName = function (src) {
  69038. if (src instanceof HTMLVideoElement) {
  69039. return src.currentSrc;
  69040. }
  69041. if (typeof src === "object") {
  69042. return src.toString();
  69043. }
  69044. return src;
  69045. };
  69046. ;
  69047. VideoTexture.prototype._getVideo = function (src) {
  69048. if (src instanceof HTMLVideoElement) {
  69049. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  69050. return src;
  69051. }
  69052. var video = document.createElement("video");
  69053. if (typeof src === "string") {
  69054. BABYLON.Tools.SetCorsBehavior(src, video);
  69055. video.src = src;
  69056. }
  69057. else {
  69058. BABYLON.Tools.SetCorsBehavior(src[0], video);
  69059. src.forEach(function (url) {
  69060. var source = document.createElement("source");
  69061. source.src = url;
  69062. video.appendChild(source);
  69063. });
  69064. }
  69065. return video;
  69066. };
  69067. ;
  69068. /**
  69069. * @hidden Internal method to initiate `update`.
  69070. */
  69071. VideoTexture.prototype._rebuild = function () {
  69072. this.update();
  69073. };
  69074. /**
  69075. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  69076. */
  69077. VideoTexture.prototype.update = function () {
  69078. if (!this.autoUpdateTexture) {
  69079. // Expecting user to call `updateTexture` manually
  69080. return;
  69081. }
  69082. this.updateTexture(true);
  69083. };
  69084. /**
  69085. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  69086. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  69087. */
  69088. VideoTexture.prototype.updateTexture = function (isVisible) {
  69089. if (!isVisible) {
  69090. return;
  69091. }
  69092. if (this.video.paused && this._stillImageCaptured) {
  69093. return;
  69094. }
  69095. this._stillImageCaptured = true;
  69096. this._updateInternalTexture();
  69097. };
  69098. /**
  69099. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  69100. * @param url New url.
  69101. */
  69102. VideoTexture.prototype.updateURL = function (url) {
  69103. this.video.src = url;
  69104. };
  69105. VideoTexture.prototype.dispose = function () {
  69106. _super.prototype.dispose.call(this);
  69107. if (this._onUserActionRequestedObservable) {
  69108. this._onUserActionRequestedObservable.clear();
  69109. this._onUserActionRequestedObservable = null;
  69110. }
  69111. this.video.removeEventListener("canplay", this._createInternalTexture);
  69112. this.video.removeEventListener("paused", this._updateInternalTexture);
  69113. this.video.removeEventListener("seeked", this._updateInternalTexture);
  69114. this.video.removeEventListener("emptied", this.reset);
  69115. this.video.pause();
  69116. };
  69117. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  69118. var video = document.createElement("video");
  69119. video.setAttribute('autoplay', '');
  69120. video.setAttribute('muted', '');
  69121. video.setAttribute('playsinline', '');
  69122. var constraintsDeviceId;
  69123. if (constraints && constraints.deviceId) {
  69124. constraintsDeviceId = {
  69125. exact: constraints.deviceId,
  69126. };
  69127. }
  69128. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  69129. if (navigator.mediaDevices) {
  69130. navigator.mediaDevices.getUserMedia({ video: constraints })
  69131. .then(function (stream) {
  69132. if (video.mozSrcObject !== undefined) {
  69133. // hack for Firefox < 19
  69134. video.mozSrcObject = stream;
  69135. }
  69136. else {
  69137. video.srcObject = stream;
  69138. }
  69139. var onPlaying = function () {
  69140. if (onReady) {
  69141. onReady(new VideoTexture("video", video, scene, true, true));
  69142. }
  69143. video.removeEventListener("playing", onPlaying);
  69144. };
  69145. video.addEventListener("playing", onPlaying);
  69146. video.play();
  69147. })
  69148. .catch(function (err) {
  69149. BABYLON.Tools.Error(err.name);
  69150. });
  69151. }
  69152. else {
  69153. navigator.getUserMedia =
  69154. navigator.getUserMedia ||
  69155. navigator.webkitGetUserMedia ||
  69156. navigator.mozGetUserMedia ||
  69157. navigator.msGetUserMedia;
  69158. if (navigator.getUserMedia) {
  69159. navigator.getUserMedia({
  69160. video: {
  69161. deviceId: constraintsDeviceId,
  69162. width: {
  69163. min: (constraints && constraints.minWidth) || 256,
  69164. max: (constraints && constraints.maxWidth) || 640,
  69165. },
  69166. height: {
  69167. min: (constraints && constraints.minHeight) || 256,
  69168. max: (constraints && constraints.maxHeight) || 480,
  69169. },
  69170. },
  69171. }, function (stream) {
  69172. if (video.mozSrcObject !== undefined) {
  69173. // hack for Firefox < 19
  69174. video.mozSrcObject = stream;
  69175. }
  69176. else {
  69177. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  69178. }
  69179. video.play();
  69180. if (onReady) {
  69181. onReady(new VideoTexture("video", video, scene, true, true));
  69182. }
  69183. }, function (e) {
  69184. BABYLON.Tools.Error(e.name);
  69185. });
  69186. }
  69187. }
  69188. };
  69189. return VideoTexture;
  69190. }(BABYLON.Texture));
  69191. BABYLON.VideoTexture = VideoTexture;
  69192. })(BABYLON || (BABYLON = {}));
  69193. //# sourceMappingURL=babylon.videoTexture.js.map
  69194. var BABYLON;
  69195. (function (BABYLON) {
  69196. var RawTexture = /** @class */ (function (_super) {
  69197. __extends(RawTexture, _super);
  69198. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  69199. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69200. if (invertY === void 0) { invertY = false; }
  69201. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69202. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69203. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  69204. _this.format = format;
  69205. _this._engine = scene.getEngine();
  69206. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  69207. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69208. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69209. return _this;
  69210. }
  69211. RawTexture.prototype.update = function (data) {
  69212. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  69213. };
  69214. // Statics
  69215. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  69216. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69217. if (invertY === void 0) { invertY = false; }
  69218. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69219. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  69220. };
  69221. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  69222. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69223. if (invertY === void 0) { invertY = false; }
  69224. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69225. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  69226. };
  69227. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  69228. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69229. if (invertY === void 0) { invertY = false; }
  69230. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69231. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  69232. };
  69233. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  69234. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69235. if (invertY === void 0) { invertY = false; }
  69236. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69237. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69238. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  69239. };
  69240. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  69241. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69242. if (invertY === void 0) { invertY = false; }
  69243. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69244. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69245. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  69246. };
  69247. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  69248. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69249. if (invertY === void 0) { invertY = false; }
  69250. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69251. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  69252. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  69253. };
  69254. return RawTexture;
  69255. }(BABYLON.Texture));
  69256. BABYLON.RawTexture = RawTexture;
  69257. })(BABYLON || (BABYLON = {}));
  69258. //# sourceMappingURL=babylon.rawTexture.js.map
  69259. var BABYLON;
  69260. (function (BABYLON) {
  69261. /**
  69262. * Class used to store 3D textures containing user data
  69263. */
  69264. var RawTexture3D = /** @class */ (function (_super) {
  69265. __extends(RawTexture3D, _super);
  69266. /**
  69267. * Create a new RawTexture3D
  69268. * @param data defines the data of the texture
  69269. * @param width defines the width of the texture
  69270. * @param height defines the height of the texture
  69271. * @param depth defines the depth of the texture
  69272. * @param format defines the texture format to use
  69273. * @param scene defines the hosting scene
  69274. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  69275. * @param invertY defines if texture must be stored with Y axis inverted
  69276. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  69277. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  69278. */
  69279. function RawTexture3D(data, width, height, depth,
  69280. /** Gets or sets the texture format to use */
  69281. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  69282. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69283. if (invertY === void 0) { invertY = false; }
  69284. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69285. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69286. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  69287. _this.format = format;
  69288. _this._engine = scene.getEngine();
  69289. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  69290. _this.is3D = true;
  69291. return _this;
  69292. }
  69293. /**
  69294. * Update the texture with new data
  69295. * @param data defines the data to store in the texture
  69296. */
  69297. RawTexture3D.prototype.update = function (data) {
  69298. if (!this._texture) {
  69299. return;
  69300. }
  69301. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  69302. };
  69303. return RawTexture3D;
  69304. }(BABYLON.Texture));
  69305. BABYLON.RawTexture3D = RawTexture3D;
  69306. })(BABYLON || (BABYLON = {}));
  69307. //# sourceMappingURL=babylon.rawTexture3D.js.map
  69308. var BABYLON;
  69309. (function (BABYLON) {
  69310. /**
  69311. * PostProcessManager is used to manage one or more post processes or post process pipelines
  69312. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  69313. */
  69314. var PostProcessManager = /** @class */ (function () {
  69315. /**
  69316. * Creates a new instance PostProcess
  69317. * @param scene The scene that the post process is associated with.
  69318. */
  69319. function PostProcessManager(scene) {
  69320. this._vertexBuffers = {};
  69321. this._scene = scene;
  69322. }
  69323. PostProcessManager.prototype._prepareBuffers = function () {
  69324. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  69325. return;
  69326. }
  69327. // VBO
  69328. var vertices = [];
  69329. vertices.push(1, 1);
  69330. vertices.push(-1, 1);
  69331. vertices.push(-1, -1);
  69332. vertices.push(1, -1);
  69333. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69334. this._buildIndexBuffer();
  69335. };
  69336. PostProcessManager.prototype._buildIndexBuffer = function () {
  69337. // Indices
  69338. var indices = [];
  69339. indices.push(0);
  69340. indices.push(1);
  69341. indices.push(2);
  69342. indices.push(0);
  69343. indices.push(2);
  69344. indices.push(3);
  69345. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  69346. };
  69347. /**
  69348. * Rebuilds the vertex buffers of the manager.
  69349. * @hidden
  69350. */
  69351. PostProcessManager.prototype._rebuild = function () {
  69352. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69353. if (!vb) {
  69354. return;
  69355. }
  69356. vb._rebuild();
  69357. this._buildIndexBuffer();
  69358. };
  69359. // Methods
  69360. /**
  69361. * Prepares a frame to be run through a post process.
  69362. * @param sourceTexture The input texture to the post procesess. (default: null)
  69363. * @param postProcesses An array of post processes to be run. (default: null)
  69364. * @returns True if the post processes were able to be run.
  69365. * @hidden
  69366. */
  69367. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  69368. if (sourceTexture === void 0) { sourceTexture = null; }
  69369. if (postProcesses === void 0) { postProcesses = null; }
  69370. var camera = this._scene.activeCamera;
  69371. if (!camera) {
  69372. return false;
  69373. }
  69374. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  69375. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  69376. return false;
  69377. }
  69378. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  69379. return true;
  69380. };
  69381. /**
  69382. * Manually render a set of post processes to a texture.
  69383. * @param postProcesses An array of post processes to be run.
  69384. * @param targetTexture The target texture to render to.
  69385. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  69386. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  69387. * @param lodLevel defines which lod of the texture to render to
  69388. */
  69389. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  69390. if (targetTexture === void 0) { targetTexture = null; }
  69391. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  69392. if (faceIndex === void 0) { faceIndex = 0; }
  69393. if (lodLevel === void 0) { lodLevel = 0; }
  69394. var engine = this._scene.getEngine();
  69395. for (var index = 0; index < postProcesses.length; index++) {
  69396. if (index < postProcesses.length - 1) {
  69397. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  69398. }
  69399. else {
  69400. if (targetTexture) {
  69401. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  69402. }
  69403. else {
  69404. engine.restoreDefaultFramebuffer();
  69405. }
  69406. }
  69407. var pp = postProcesses[index];
  69408. var effect = pp.apply();
  69409. if (effect) {
  69410. pp.onBeforeRenderObservable.notifyObservers(effect);
  69411. // VBOs
  69412. this._prepareBuffers();
  69413. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  69414. // Draw order
  69415. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69416. pp.onAfterRenderObservable.notifyObservers(effect);
  69417. }
  69418. }
  69419. // Restore depth buffer
  69420. engine.setDepthBuffer(true);
  69421. engine.setDepthWrite(true);
  69422. };
  69423. /**
  69424. * Finalize the result of the output of the postprocesses.
  69425. * @param doNotPresent If true the result will not be displayed to the screen.
  69426. * @param targetTexture The target texture to render to.
  69427. * @param faceIndex The index of the face to bind the target texture to.
  69428. * @param postProcesses The array of post processes to render.
  69429. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  69430. * @hidden
  69431. */
  69432. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  69433. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  69434. var camera = this._scene.activeCamera;
  69435. if (!camera) {
  69436. return;
  69437. }
  69438. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  69439. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  69440. return;
  69441. }
  69442. var engine = this._scene.getEngine();
  69443. for (var index = 0, len = postProcesses.length; index < len; index++) {
  69444. var pp = postProcesses[index];
  69445. if (index < len - 1) {
  69446. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  69447. }
  69448. else {
  69449. if (targetTexture) {
  69450. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  69451. pp._outputTexture = targetTexture;
  69452. }
  69453. else {
  69454. engine.restoreDefaultFramebuffer();
  69455. pp._outputTexture = null;
  69456. }
  69457. }
  69458. if (doNotPresent) {
  69459. break;
  69460. }
  69461. var effect = pp.apply();
  69462. if (effect) {
  69463. pp.onBeforeRenderObservable.notifyObservers(effect);
  69464. // VBOs
  69465. this._prepareBuffers();
  69466. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  69467. // Draw order
  69468. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69469. pp.onAfterRenderObservable.notifyObservers(effect);
  69470. }
  69471. }
  69472. // Restore states
  69473. engine.setDepthBuffer(true);
  69474. engine.setDepthWrite(true);
  69475. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69476. };
  69477. /**
  69478. * Disposes of the post process manager.
  69479. */
  69480. PostProcessManager.prototype.dispose = function () {
  69481. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69482. if (buffer) {
  69483. buffer.dispose();
  69484. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69485. }
  69486. if (this._indexBuffer) {
  69487. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69488. this._indexBuffer = null;
  69489. }
  69490. };
  69491. return PostProcessManager;
  69492. }());
  69493. BABYLON.PostProcessManager = PostProcessManager;
  69494. })(BABYLON || (BABYLON = {}));
  69495. //# sourceMappingURL=babylon.postProcessManager.js.map
  69496. var BABYLON;
  69497. (function (BABYLON) {
  69498. /**
  69499. * PostProcess can be used to apply a shader to a texture after it has been rendered
  69500. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  69501. */
  69502. var PostProcess = /** @class */ (function () {
  69503. /**
  69504. * Creates a new instance PostProcess
  69505. * @param name The name of the PostProcess.
  69506. * @param fragmentUrl The url of the fragment shader to be used.
  69507. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  69508. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  69509. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69510. * @param camera The camera to apply the render pass to.
  69511. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69512. * @param engine The engine which the post process will be applied. (default: current engine)
  69513. * @param reusable If the post process can be reused on the same frame. (default: false)
  69514. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  69515. * @param textureType Type of textures used when performing the post process. (default: 0)
  69516. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  69517. * @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
  69518. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  69519. */
  69520. function PostProcess(
  69521. /** Name of the PostProcess. */
  69522. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  69523. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  69524. if (defines === void 0) { defines = null; }
  69525. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69526. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  69527. if (blockCompilation === void 0) { blockCompilation = false; }
  69528. this.name = name;
  69529. /**
  69530. * Width of the texture to apply the post process on
  69531. */
  69532. this.width = -1;
  69533. /**
  69534. * Height of the texture to apply the post process on
  69535. */
  69536. this.height = -1;
  69537. /**
  69538. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  69539. * @hidden
  69540. */
  69541. this._outputTexture = null;
  69542. /**
  69543. * If the buffer needs to be cleared before applying the post process. (default: true)
  69544. * Should be set to false if shader will overwrite all previous pixels.
  69545. */
  69546. this.autoClear = true;
  69547. /**
  69548. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  69549. */
  69550. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  69551. /**
  69552. * Animations to be used for the post processing
  69553. */
  69554. this.animations = new Array();
  69555. /**
  69556. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  69557. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  69558. */
  69559. this.enablePixelPerfectMode = false;
  69560. /**
  69561. * Force the postprocess to be applied without taking in account viewport
  69562. */
  69563. this.forceFullscreenViewport = true;
  69564. /**
  69565. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  69566. *
  69567. * | Value | Type | Description |
  69568. * | ----- | ----------------------------------- | ----------- |
  69569. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  69570. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  69571. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  69572. *
  69573. */
  69574. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  69575. /**
  69576. * Force textures to be a power of two (default: false)
  69577. */
  69578. this.alwaysForcePOT = false;
  69579. this._samples = 1;
  69580. /**
  69581. * Modify the scale of the post process to be the same as the viewport (default: false)
  69582. */
  69583. this.adaptScaleToCurrentViewport = false;
  69584. this._reusable = false;
  69585. /**
  69586. * Smart array of input and output textures for the post process.
  69587. * @hidden
  69588. */
  69589. this._textures = new BABYLON.SmartArray(2);
  69590. /**
  69591. * The index in _textures that corresponds to the output texture.
  69592. * @hidden
  69593. */
  69594. this._currentRenderTextureInd = 0;
  69595. this._scaleRatio = new BABYLON.Vector2(1, 1);
  69596. this._texelSize = BABYLON.Vector2.Zero();
  69597. // Events
  69598. /**
  69599. * An event triggered when the postprocess is activated.
  69600. */
  69601. this.onActivateObservable = new BABYLON.Observable();
  69602. /**
  69603. * An event triggered when the postprocess changes its size.
  69604. */
  69605. this.onSizeChangedObservable = new BABYLON.Observable();
  69606. /**
  69607. * An event triggered when the postprocess applies its effect.
  69608. */
  69609. this.onApplyObservable = new BABYLON.Observable();
  69610. /**
  69611. * An event triggered before rendering the postprocess
  69612. */
  69613. this.onBeforeRenderObservable = new BABYLON.Observable();
  69614. /**
  69615. * An event triggered after rendering the postprocess
  69616. */
  69617. this.onAfterRenderObservable = new BABYLON.Observable();
  69618. if (camera != null) {
  69619. this._camera = camera;
  69620. this._scene = camera.getScene();
  69621. camera.attachPostProcess(this);
  69622. this._engine = this._scene.getEngine();
  69623. this._scene.postProcesses.push(this);
  69624. }
  69625. else if (engine) {
  69626. this._engine = engine;
  69627. this._engine.postProcesses.push(this);
  69628. }
  69629. this._options = options;
  69630. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  69631. this._reusable = reusable || false;
  69632. this._textureType = textureType;
  69633. this._samplers = samplers || [];
  69634. this._samplers.push("textureSampler");
  69635. this._fragmentUrl = fragmentUrl;
  69636. this._vertexUrl = vertexUrl;
  69637. this._parameters = parameters || [];
  69638. this._parameters.push("scale");
  69639. this._indexParameters = indexParameters;
  69640. if (!blockCompilation) {
  69641. this.updateEffect(defines);
  69642. }
  69643. }
  69644. Object.defineProperty(PostProcess.prototype, "samples", {
  69645. /**
  69646. * Number of sample textures (default: 1)
  69647. */
  69648. get: function () {
  69649. return this._samples;
  69650. },
  69651. set: function (n) {
  69652. var _this = this;
  69653. this._samples = n;
  69654. this._textures.forEach(function (texture) {
  69655. if (texture.samples !== _this._samples) {
  69656. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  69657. }
  69658. });
  69659. },
  69660. enumerable: true,
  69661. configurable: true
  69662. });
  69663. Object.defineProperty(PostProcess.prototype, "onActivate", {
  69664. /**
  69665. * A function that is added to the onActivateObservable
  69666. */
  69667. set: function (callback) {
  69668. if (this._onActivateObserver) {
  69669. this.onActivateObservable.remove(this._onActivateObserver);
  69670. }
  69671. if (callback) {
  69672. this._onActivateObserver = this.onActivateObservable.add(callback);
  69673. }
  69674. },
  69675. enumerable: true,
  69676. configurable: true
  69677. });
  69678. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  69679. /**
  69680. * A function that is added to the onSizeChangedObservable
  69681. */
  69682. set: function (callback) {
  69683. if (this._onSizeChangedObserver) {
  69684. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  69685. }
  69686. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  69687. },
  69688. enumerable: true,
  69689. configurable: true
  69690. });
  69691. Object.defineProperty(PostProcess.prototype, "onApply", {
  69692. /**
  69693. * A function that is added to the onApplyObservable
  69694. */
  69695. set: function (callback) {
  69696. if (this._onApplyObserver) {
  69697. this.onApplyObservable.remove(this._onApplyObserver);
  69698. }
  69699. this._onApplyObserver = this.onApplyObservable.add(callback);
  69700. },
  69701. enumerable: true,
  69702. configurable: true
  69703. });
  69704. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  69705. /**
  69706. * A function that is added to the onBeforeRenderObservable
  69707. */
  69708. set: function (callback) {
  69709. if (this._onBeforeRenderObserver) {
  69710. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69711. }
  69712. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69713. },
  69714. enumerable: true,
  69715. configurable: true
  69716. });
  69717. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  69718. /**
  69719. * A function that is added to the onAfterRenderObservable
  69720. */
  69721. set: function (callback) {
  69722. if (this._onAfterRenderObserver) {
  69723. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69724. }
  69725. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69726. },
  69727. enumerable: true,
  69728. configurable: true
  69729. });
  69730. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  69731. /**
  69732. * 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
  69733. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  69734. */
  69735. get: function () {
  69736. return this._textures.data[this._currentRenderTextureInd];
  69737. },
  69738. set: function (value) {
  69739. this._forcedOutputTexture = value;
  69740. },
  69741. enumerable: true,
  69742. configurable: true
  69743. });
  69744. /**
  69745. * Gets the camera which post process is applied to.
  69746. * @returns The camera the post process is applied to.
  69747. */
  69748. PostProcess.prototype.getCamera = function () {
  69749. return this._camera;
  69750. };
  69751. Object.defineProperty(PostProcess.prototype, "texelSize", {
  69752. /**
  69753. * Gets the texel size of the postprocess.
  69754. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  69755. */
  69756. get: function () {
  69757. if (this._shareOutputWithPostProcess) {
  69758. return this._shareOutputWithPostProcess.texelSize;
  69759. }
  69760. if (this._forcedOutputTexture) {
  69761. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  69762. }
  69763. return this._texelSize;
  69764. },
  69765. enumerable: true,
  69766. configurable: true
  69767. });
  69768. /**
  69769. * Gets the engine which this post process belongs to.
  69770. * @returns The engine the post process was enabled with.
  69771. */
  69772. PostProcess.prototype.getEngine = function () {
  69773. return this._engine;
  69774. };
  69775. /**
  69776. * The effect that is created when initializing the post process.
  69777. * @returns The created effect corrisponding the the postprocess.
  69778. */
  69779. PostProcess.prototype.getEffect = function () {
  69780. return this._effect;
  69781. };
  69782. /**
  69783. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  69784. * @param postProcess The post process to share the output with.
  69785. * @returns This post process.
  69786. */
  69787. PostProcess.prototype.shareOutputWith = function (postProcess) {
  69788. this._disposeTextures();
  69789. this._shareOutputWithPostProcess = postProcess;
  69790. return this;
  69791. };
  69792. /**
  69793. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  69794. * This should be called if the post process that shares output with this post process is disabled/disposed.
  69795. */
  69796. PostProcess.prototype.useOwnOutput = function () {
  69797. if (this._textures.length == 0) {
  69798. this._textures = new BABYLON.SmartArray(2);
  69799. }
  69800. this._shareOutputWithPostProcess = null;
  69801. };
  69802. /**
  69803. * Updates the effect with the current post process compile time values and recompiles the shader.
  69804. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69805. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69806. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69807. * @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
  69808. * @param onCompiled Called when the shader has been compiled.
  69809. * @param onError Called if there is an error when compiling a shader.
  69810. */
  69811. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69812. if (defines === void 0) { defines = null; }
  69813. if (uniforms === void 0) { uniforms = null; }
  69814. if (samplers === void 0) { samplers = null; }
  69815. 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);
  69816. };
  69817. /**
  69818. * The post process is reusable if it can be used multiple times within one frame.
  69819. * @returns If the post process is reusable
  69820. */
  69821. PostProcess.prototype.isReusable = function () {
  69822. return this._reusable;
  69823. };
  69824. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  69825. PostProcess.prototype.markTextureDirty = function () {
  69826. this.width = -1;
  69827. };
  69828. /**
  69829. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  69830. * 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.
  69831. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  69832. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  69833. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  69834. * @returns The target texture that was bound to be written to.
  69835. */
  69836. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  69837. var _this = this;
  69838. if (sourceTexture === void 0) { sourceTexture = null; }
  69839. camera = camera || this._camera;
  69840. var scene = camera.getScene();
  69841. var engine = scene.getEngine();
  69842. var maxSize = engine.getCaps().maxTextureSize;
  69843. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  69844. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  69845. // 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
  69846. var webVRCamera = camera.parent;
  69847. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  69848. requiredWidth /= 2;
  69849. }
  69850. var desiredWidth = (this._options.width || requiredWidth);
  69851. var desiredHeight = this._options.height || requiredHeight;
  69852. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  69853. if (this.adaptScaleToCurrentViewport) {
  69854. var currentViewport = engine.currentViewport;
  69855. if (currentViewport) {
  69856. desiredWidth *= currentViewport.width;
  69857. desiredHeight *= currentViewport.height;
  69858. }
  69859. }
  69860. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  69861. if (!this._options.width) {
  69862. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  69863. }
  69864. if (!this._options.height) {
  69865. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  69866. }
  69867. }
  69868. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  69869. if (this._textures.length > 0) {
  69870. for (var i = 0; i < this._textures.length; i++) {
  69871. this._engine._releaseTexture(this._textures.data[i]);
  69872. }
  69873. this._textures.reset();
  69874. }
  69875. this.width = desiredWidth;
  69876. this.height = desiredHeight;
  69877. var textureSize = { width: this.width, height: this.height };
  69878. var textureOptions = {
  69879. generateMipMaps: false,
  69880. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  69881. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  69882. samplingMode: this.renderTargetSamplingMode,
  69883. type: this._textureType
  69884. };
  69885. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  69886. if (this._reusable) {
  69887. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  69888. }
  69889. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  69890. this.onSizeChangedObservable.notifyObservers(this);
  69891. }
  69892. this._textures.forEach(function (texture) {
  69893. if (texture.samples !== _this.samples) {
  69894. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  69895. }
  69896. });
  69897. }
  69898. var target;
  69899. if (this._shareOutputWithPostProcess) {
  69900. target = this._shareOutputWithPostProcess.inputTexture;
  69901. }
  69902. else if (this._forcedOutputTexture) {
  69903. target = this._forcedOutputTexture;
  69904. this.width = this._forcedOutputTexture.width;
  69905. this.height = this._forcedOutputTexture.height;
  69906. }
  69907. else {
  69908. target = this.inputTexture;
  69909. }
  69910. // Bind the input of this post process to be used as the output of the previous post process.
  69911. if (this.enablePixelPerfectMode) {
  69912. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  69913. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  69914. }
  69915. else {
  69916. this._scaleRatio.copyFromFloats(1, 1);
  69917. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  69918. }
  69919. this.onActivateObservable.notifyObservers(camera);
  69920. // Clear
  69921. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  69922. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  69923. }
  69924. if (this._reusable) {
  69925. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  69926. }
  69927. return target;
  69928. };
  69929. Object.defineProperty(PostProcess.prototype, "isSupported", {
  69930. /**
  69931. * If the post process is supported.
  69932. */
  69933. get: function () {
  69934. return this._effect.isSupported;
  69935. },
  69936. enumerable: true,
  69937. configurable: true
  69938. });
  69939. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  69940. /**
  69941. * The aspect ratio of the output texture.
  69942. */
  69943. get: function () {
  69944. if (this._shareOutputWithPostProcess) {
  69945. return this._shareOutputWithPostProcess.aspectRatio;
  69946. }
  69947. if (this._forcedOutputTexture) {
  69948. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  69949. }
  69950. return this.width / this.height;
  69951. },
  69952. enumerable: true,
  69953. configurable: true
  69954. });
  69955. /**
  69956. * Get a value indicating if the post-process is ready to be used
  69957. * @returns true if the post-process is ready (shader is compiled)
  69958. */
  69959. PostProcess.prototype.isReady = function () {
  69960. return this._effect && this._effect.isReady();
  69961. };
  69962. /**
  69963. * Binds all textures and uniforms to the shader, this will be run on every pass.
  69964. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  69965. */
  69966. PostProcess.prototype.apply = function () {
  69967. // Check
  69968. if (!this._effect || !this._effect.isReady())
  69969. return null;
  69970. // States
  69971. this._engine.enableEffect(this._effect);
  69972. this._engine.setState(false);
  69973. this._engine.setDepthBuffer(false);
  69974. this._engine.setDepthWrite(false);
  69975. // Alpha
  69976. this._engine.setAlphaMode(this.alphaMode);
  69977. if (this.alphaConstants) {
  69978. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  69979. }
  69980. // Bind the output texture of the preivous post process as the input to this post process.
  69981. var source;
  69982. if (this._shareOutputWithPostProcess) {
  69983. source = this._shareOutputWithPostProcess.inputTexture;
  69984. }
  69985. else if (this._forcedOutputTexture) {
  69986. source = this._forcedOutputTexture;
  69987. }
  69988. else {
  69989. source = this.inputTexture;
  69990. }
  69991. this._effect._bindTexture("textureSampler", source);
  69992. // Parameters
  69993. this._effect.setVector2("scale", this._scaleRatio);
  69994. this.onApplyObservable.notifyObservers(this._effect);
  69995. return this._effect;
  69996. };
  69997. PostProcess.prototype._disposeTextures = function () {
  69998. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  69999. return;
  70000. }
  70001. if (this._textures.length > 0) {
  70002. for (var i = 0; i < this._textures.length; i++) {
  70003. this._engine._releaseTexture(this._textures.data[i]);
  70004. }
  70005. }
  70006. this._textures.dispose();
  70007. };
  70008. /**
  70009. * Disposes the post process.
  70010. * @param camera The camera to dispose the post process on.
  70011. */
  70012. PostProcess.prototype.dispose = function (camera) {
  70013. camera = camera || this._camera;
  70014. this._disposeTextures();
  70015. if (this._scene) {
  70016. var index_1 = this._scene.postProcesses.indexOf(this);
  70017. if (index_1 !== -1) {
  70018. this._scene.postProcesses.splice(index_1, 1);
  70019. }
  70020. }
  70021. else {
  70022. var index_2 = this._engine.postProcesses.indexOf(this);
  70023. if (index_2 !== -1) {
  70024. this._engine.postProcesses.splice(index_2, 1);
  70025. }
  70026. }
  70027. if (!camera) {
  70028. return;
  70029. }
  70030. camera.detachPostProcess(this);
  70031. var index = camera._postProcesses.indexOf(this);
  70032. if (index === 0 && camera._postProcesses.length > 0) {
  70033. var firstPostProcess = this._camera._getFirstPostProcess();
  70034. if (firstPostProcess) {
  70035. firstPostProcess.markTextureDirty();
  70036. }
  70037. }
  70038. this.onActivateObservable.clear();
  70039. this.onAfterRenderObservable.clear();
  70040. this.onApplyObservable.clear();
  70041. this.onBeforeRenderObservable.clear();
  70042. this.onSizeChangedObservable.clear();
  70043. };
  70044. return PostProcess;
  70045. }());
  70046. BABYLON.PostProcess = PostProcess;
  70047. })(BABYLON || (BABYLON = {}));
  70048. //# sourceMappingURL=babylon.postProcess.js.map
  70049. var BABYLON;
  70050. (function (BABYLON) {
  70051. var PassPostProcess = /** @class */ (function (_super) {
  70052. __extends(PassPostProcess, _super);
  70053. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70054. if (camera === void 0) { camera = null; }
  70055. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70056. if (blockCompilation === void 0) { blockCompilation = false; }
  70057. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  70058. }
  70059. return PassPostProcess;
  70060. }(BABYLON.PostProcess));
  70061. BABYLON.PassPostProcess = PassPostProcess;
  70062. })(BABYLON || (BABYLON = {}));
  70063. //# sourceMappingURL=babylon.passPostProcess.js.map
  70064. var __assign = (this && this.__assign) || function () {
  70065. __assign = Object.assign || function(t) {
  70066. for (var s, i = 1, n = arguments.length; i < n; i++) {
  70067. s = arguments[i];
  70068. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  70069. t[p] = s[p];
  70070. }
  70071. return t;
  70072. };
  70073. return __assign.apply(this, arguments);
  70074. };
  70075. var BABYLON;
  70076. (function (BABYLON) {
  70077. /**
  70078. * Default implementation IShadowGenerator.
  70079. * This is the main object responsible of generating shadows in the framework.
  70080. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  70081. */
  70082. var ShadowGenerator = /** @class */ (function () {
  70083. /**
  70084. * Creates a ShadowGenerator object.
  70085. * A ShadowGenerator is the required tool to use the shadows.
  70086. * Each light casting shadows needs to use its own ShadowGenerator.
  70087. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  70088. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  70089. * @param light The light object generating the shadows.
  70090. * @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.
  70091. */
  70092. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  70093. this._bias = 0.00005;
  70094. this._normalBias = 0;
  70095. this._blurBoxOffset = 1;
  70096. this._blurScale = 2;
  70097. this._blurKernel = 1;
  70098. this._useKernelBlur = false;
  70099. this._filter = ShadowGenerator.FILTER_NONE;
  70100. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  70101. this._contactHardeningLightSizeUVRatio = 0.1;
  70102. this._darkness = 0;
  70103. this._transparencyShadow = false;
  70104. /**
  70105. * Controls the extent to which the shadows fade out at the edge of the frustum
  70106. * Used only by directionals and spots
  70107. */
  70108. this.frustumEdgeFalloff = 0;
  70109. /**
  70110. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  70111. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  70112. * It might on the other hand introduce peter panning.
  70113. */
  70114. this.forceBackFacesOnly = false;
  70115. this._lightDirection = BABYLON.Vector3.Zero();
  70116. this._viewMatrix = BABYLON.Matrix.Zero();
  70117. this._projectionMatrix = BABYLON.Matrix.Zero();
  70118. this._transformMatrix = BABYLON.Matrix.Zero();
  70119. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  70120. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  70121. this._currentFaceIndex = 0;
  70122. this._currentFaceIndexCache = 0;
  70123. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  70124. this._mapSize = mapSize;
  70125. this._light = light;
  70126. this._scene = light.getScene();
  70127. light._shadowGenerator = this;
  70128. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  70129. if (!component) {
  70130. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  70131. this._scene._addComponent(component);
  70132. }
  70133. // Texture type fallback from float to int if not supported.
  70134. var caps = this._scene.getEngine().getCaps();
  70135. if (!useFullFloatFirst) {
  70136. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  70137. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70138. }
  70139. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  70140. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70141. }
  70142. else {
  70143. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70144. }
  70145. }
  70146. else {
  70147. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  70148. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70149. }
  70150. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  70151. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70152. }
  70153. else {
  70154. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70155. }
  70156. }
  70157. this._initializeGenerator();
  70158. this._applyFilterValues();
  70159. }
  70160. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  70161. /**
  70162. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  70163. */
  70164. get: function () {
  70165. return this._bias;
  70166. },
  70167. /**
  70168. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  70169. */
  70170. set: function (bias) {
  70171. this._bias = bias;
  70172. },
  70173. enumerable: true,
  70174. configurable: true
  70175. });
  70176. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  70177. /**
  70178. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  70179. */
  70180. get: function () {
  70181. return this._normalBias;
  70182. },
  70183. /**
  70184. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  70185. */
  70186. set: function (normalBias) {
  70187. this._normalBias = normalBias;
  70188. },
  70189. enumerable: true,
  70190. configurable: true
  70191. });
  70192. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  70193. /**
  70194. * Gets the blur box offset: offset applied during the blur pass.
  70195. * Only usefull if useKernelBlur = false
  70196. */
  70197. get: function () {
  70198. return this._blurBoxOffset;
  70199. },
  70200. /**
  70201. * Sets the blur box offset: offset applied during the blur pass.
  70202. * Only usefull if useKernelBlur = false
  70203. */
  70204. set: function (value) {
  70205. if (this._blurBoxOffset === value) {
  70206. return;
  70207. }
  70208. this._blurBoxOffset = value;
  70209. this._disposeBlurPostProcesses();
  70210. },
  70211. enumerable: true,
  70212. configurable: true
  70213. });
  70214. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  70215. /**
  70216. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  70217. * 2 means half of the size.
  70218. */
  70219. get: function () {
  70220. return this._blurScale;
  70221. },
  70222. /**
  70223. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  70224. * 2 means half of the size.
  70225. */
  70226. set: function (value) {
  70227. if (this._blurScale === value) {
  70228. return;
  70229. }
  70230. this._blurScale = value;
  70231. this._disposeBlurPostProcesses();
  70232. },
  70233. enumerable: true,
  70234. configurable: true
  70235. });
  70236. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  70237. /**
  70238. * Gets the blur kernel: kernel size of the blur pass.
  70239. * Only usefull if useKernelBlur = true
  70240. */
  70241. get: function () {
  70242. return this._blurKernel;
  70243. },
  70244. /**
  70245. * Sets the blur kernel: kernel size of the blur pass.
  70246. * Only usefull if useKernelBlur = true
  70247. */
  70248. set: function (value) {
  70249. if (this._blurKernel === value) {
  70250. return;
  70251. }
  70252. this._blurKernel = value;
  70253. this._disposeBlurPostProcesses();
  70254. },
  70255. enumerable: true,
  70256. configurable: true
  70257. });
  70258. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  70259. /**
  70260. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  70261. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  70262. */
  70263. get: function () {
  70264. return this._useKernelBlur;
  70265. },
  70266. /**
  70267. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  70268. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  70269. */
  70270. set: function (value) {
  70271. if (this._useKernelBlur === value) {
  70272. return;
  70273. }
  70274. this._useKernelBlur = value;
  70275. this._disposeBlurPostProcesses();
  70276. },
  70277. enumerable: true,
  70278. configurable: true
  70279. });
  70280. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  70281. /**
  70282. * Gets the depth scale used in ESM mode.
  70283. */
  70284. get: function () {
  70285. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  70286. },
  70287. /**
  70288. * Sets the depth scale used in ESM mode.
  70289. * This can override the scale stored on the light.
  70290. */
  70291. set: function (value) {
  70292. this._depthScale = value;
  70293. },
  70294. enumerable: true,
  70295. configurable: true
  70296. });
  70297. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  70298. /**
  70299. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  70300. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  70301. */
  70302. get: function () {
  70303. return this._filter;
  70304. },
  70305. /**
  70306. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  70307. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  70308. */
  70309. set: function (value) {
  70310. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  70311. if (this._light.needCube()) {
  70312. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  70313. this.useExponentialShadowMap = true;
  70314. return;
  70315. }
  70316. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  70317. this.useCloseExponentialShadowMap = true;
  70318. return;
  70319. }
  70320. // PCF on cubemap would also be expensive
  70321. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  70322. this.usePoissonSampling = true;
  70323. return;
  70324. }
  70325. }
  70326. // Weblg1 fallback for PCF.
  70327. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  70328. if (this._scene.getEngine().webGLVersion === 1) {
  70329. this.usePoissonSampling = true;
  70330. return;
  70331. }
  70332. }
  70333. if (this._filter === value) {
  70334. return;
  70335. }
  70336. this._filter = value;
  70337. this._disposeBlurPostProcesses();
  70338. this._applyFilterValues();
  70339. this._light._markMeshesAsLightDirty();
  70340. },
  70341. enumerable: true,
  70342. configurable: true
  70343. });
  70344. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  70345. /**
  70346. * Gets if the current filter is set to Poisson Sampling.
  70347. */
  70348. get: function () {
  70349. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  70350. },
  70351. /**
  70352. * Sets the current filter to Poisson Sampling.
  70353. */
  70354. set: function (value) {
  70355. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  70356. return;
  70357. }
  70358. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  70359. },
  70360. enumerable: true,
  70361. configurable: true
  70362. });
  70363. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  70364. /**
  70365. * Gets if the current filter is set to VSM.
  70366. * DEPRECATED. Should use useExponentialShadowMap instead.
  70367. */
  70368. get: function () {
  70369. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  70370. return this.useExponentialShadowMap;
  70371. },
  70372. /**
  70373. * Sets the current filter is to VSM.
  70374. * DEPRECATED. Should use useExponentialShadowMap instead.
  70375. */
  70376. set: function (value) {
  70377. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  70378. this.useExponentialShadowMap = value;
  70379. },
  70380. enumerable: true,
  70381. configurable: true
  70382. });
  70383. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  70384. /**
  70385. * Gets if the current filter is set to blurred VSM.
  70386. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  70387. */
  70388. get: function () {
  70389. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  70390. return this.useBlurExponentialShadowMap;
  70391. },
  70392. /**
  70393. * Sets the current filter is to blurred VSM.
  70394. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  70395. */
  70396. set: function (value) {
  70397. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  70398. this.useBlurExponentialShadowMap = value;
  70399. },
  70400. enumerable: true,
  70401. configurable: true
  70402. });
  70403. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  70404. /**
  70405. * Gets if the current filter is set to ESM.
  70406. */
  70407. get: function () {
  70408. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  70409. },
  70410. /**
  70411. * Sets the current filter is to ESM.
  70412. */
  70413. set: function (value) {
  70414. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  70415. return;
  70416. }
  70417. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70418. },
  70419. enumerable: true,
  70420. configurable: true
  70421. });
  70422. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  70423. /**
  70424. * Gets if the current filter is set to filtered ESM.
  70425. */
  70426. get: function () {
  70427. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  70428. },
  70429. /**
  70430. * Gets if the current filter is set to filtered ESM.
  70431. */
  70432. set: function (value) {
  70433. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  70434. return;
  70435. }
  70436. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70437. },
  70438. enumerable: true,
  70439. configurable: true
  70440. });
  70441. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  70442. /**
  70443. * Gets if the current filter is set to "close ESM" (using the inverse of the
  70444. * exponential to prevent steep falloff artifacts).
  70445. */
  70446. get: function () {
  70447. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  70448. },
  70449. /**
  70450. * Sets the current filter to "close ESM" (using the inverse of the
  70451. * exponential to prevent steep falloff artifacts).
  70452. */
  70453. set: function (value) {
  70454. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  70455. return;
  70456. }
  70457. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70458. },
  70459. enumerable: true,
  70460. configurable: true
  70461. });
  70462. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  70463. /**
  70464. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  70465. * exponential to prevent steep falloff artifacts).
  70466. */
  70467. get: function () {
  70468. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  70469. },
  70470. /**
  70471. * Sets the current filter to filtered "close ESM" (using the inverse of the
  70472. * exponential to prevent steep falloff artifacts).
  70473. */
  70474. set: function (value) {
  70475. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  70476. return;
  70477. }
  70478. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70479. },
  70480. enumerable: true,
  70481. configurable: true
  70482. });
  70483. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  70484. /**
  70485. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  70486. */
  70487. get: function () {
  70488. return this.filter === ShadowGenerator.FILTER_PCF;
  70489. },
  70490. /**
  70491. * Sets the current filter to "PCF" (percentage closer filtering).
  70492. */
  70493. set: function (value) {
  70494. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  70495. return;
  70496. }
  70497. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  70498. },
  70499. enumerable: true,
  70500. configurable: true
  70501. });
  70502. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  70503. /**
  70504. * Gets the PCF or PCSS Quality.
  70505. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  70506. */
  70507. get: function () {
  70508. return this._filteringQuality;
  70509. },
  70510. /**
  70511. * Sets the PCF or PCSS Quality.
  70512. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  70513. */
  70514. set: function (filteringQuality) {
  70515. this._filteringQuality = filteringQuality;
  70516. },
  70517. enumerable: true,
  70518. configurable: true
  70519. });
  70520. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  70521. /**
  70522. * Gets if the current filter is set to "PCSS" (contact hardening).
  70523. */
  70524. get: function () {
  70525. return this.filter === ShadowGenerator.FILTER_PCSS;
  70526. },
  70527. /**
  70528. * Sets the current filter to "PCSS" (contact hardening).
  70529. */
  70530. set: function (value) {
  70531. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  70532. return;
  70533. }
  70534. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  70535. },
  70536. enumerable: true,
  70537. configurable: true
  70538. });
  70539. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  70540. /**
  70541. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  70542. * Using a ratio helps keeping shape stability independently of the map size.
  70543. *
  70544. * It does not account for the light projection as it was having too much
  70545. * instability during the light setup or during light position changes.
  70546. *
  70547. * Only valid if useContactHardeningShadow is true.
  70548. */
  70549. get: function () {
  70550. return this._contactHardeningLightSizeUVRatio;
  70551. },
  70552. /**
  70553. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  70554. * Using a ratio helps keeping shape stability independently of the map size.
  70555. *
  70556. * It does not account for the light projection as it was having too much
  70557. * instability during the light setup or during light position changes.
  70558. *
  70559. * Only valid if useContactHardeningShadow is true.
  70560. */
  70561. set: function (contactHardeningLightSizeUVRatio) {
  70562. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  70563. },
  70564. enumerable: true,
  70565. configurable: true
  70566. });
  70567. /**
  70568. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  70569. * 0 means strongest and 1 would means no shadow.
  70570. * @returns the darkness.
  70571. */
  70572. ShadowGenerator.prototype.getDarkness = function () {
  70573. return this._darkness;
  70574. };
  70575. /**
  70576. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  70577. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  70578. * @returns the shadow generator allowing fluent coding.
  70579. */
  70580. ShadowGenerator.prototype.setDarkness = function (darkness) {
  70581. if (darkness >= 1.0)
  70582. this._darkness = 1.0;
  70583. else if (darkness <= 0.0)
  70584. this._darkness = 0.0;
  70585. else
  70586. this._darkness = darkness;
  70587. return this;
  70588. };
  70589. /**
  70590. * Sets the ability to have transparent shadow (boolean).
  70591. * @param transparent True if transparent else False
  70592. * @returns the shadow generator allowing fluent coding
  70593. */
  70594. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  70595. this._transparencyShadow = transparent;
  70596. return this;
  70597. };
  70598. /**
  70599. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  70600. * @returns The render target texture if present otherwise, null
  70601. */
  70602. ShadowGenerator.prototype.getShadowMap = function () {
  70603. return this._shadowMap;
  70604. };
  70605. /**
  70606. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  70607. * @returns The render target texture if the shadow map is present otherwise, null
  70608. */
  70609. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  70610. if (this._shadowMap2) {
  70611. return this._shadowMap2;
  70612. }
  70613. return this._shadowMap;
  70614. };
  70615. /**
  70616. * Helper function to add a mesh and its descendants to the list of shadow casters.
  70617. * @param mesh Mesh to add
  70618. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  70619. * @returns the Shadow Generator itself
  70620. */
  70621. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  70622. if (includeDescendants === void 0) { includeDescendants = true; }
  70623. var _a;
  70624. if (!this._shadowMap) {
  70625. return this;
  70626. }
  70627. if (!this._shadowMap.renderList) {
  70628. this._shadowMap.renderList = [];
  70629. }
  70630. this._shadowMap.renderList.push(mesh);
  70631. if (includeDescendants) {
  70632. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  70633. }
  70634. return this;
  70635. };
  70636. /**
  70637. * Helper function to remove a mesh and its descendants from the list of shadow casters
  70638. * @param mesh Mesh to remove
  70639. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  70640. * @returns the Shadow Generator itself
  70641. */
  70642. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  70643. if (includeDescendants === void 0) { includeDescendants = true; }
  70644. if (!this._shadowMap || !this._shadowMap.renderList) {
  70645. return this;
  70646. }
  70647. var index = this._shadowMap.renderList.indexOf(mesh);
  70648. if (index !== -1) {
  70649. this._shadowMap.renderList.splice(index, 1);
  70650. }
  70651. if (includeDescendants) {
  70652. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  70653. var child = _a[_i];
  70654. this.removeShadowCaster(child);
  70655. }
  70656. }
  70657. return this;
  70658. };
  70659. /**
  70660. * Returns the associated light object.
  70661. * @returns the light generating the shadow
  70662. */
  70663. ShadowGenerator.prototype.getLight = function () {
  70664. return this._light;
  70665. };
  70666. ShadowGenerator.prototype._initializeGenerator = function () {
  70667. this._light._markMeshesAsLightDirty();
  70668. this._initializeShadowMap();
  70669. };
  70670. ShadowGenerator.prototype._initializeShadowMap = function () {
  70671. var _this = this;
  70672. // Render target
  70673. var engine = this._scene.getEngine();
  70674. if (engine.webGLVersion > 1) {
  70675. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  70676. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  70677. }
  70678. else {
  70679. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  70680. }
  70681. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70682. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70683. this._shadowMap.anisotropicFilteringLevel = 1;
  70684. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70685. this._shadowMap.renderParticles = false;
  70686. this._shadowMap.ignoreCameraViewport = true;
  70687. // Record Face Index before render.
  70688. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  70689. _this._currentFaceIndex = faceIndex;
  70690. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70691. engine.setColorWrite(false);
  70692. }
  70693. });
  70694. // Custom render function.
  70695. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  70696. // Blur if required afer render.
  70697. this._shadowMap.onAfterUnbindObservable.add(function () {
  70698. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70699. engine.setColorWrite(true);
  70700. }
  70701. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  70702. return;
  70703. }
  70704. var shadowMap = _this.getShadowMapForRendering();
  70705. if (shadowMap) {
  70706. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  70707. }
  70708. });
  70709. // Clear according to the chosen filter.
  70710. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  70711. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  70712. this._shadowMap.onClearObservable.add(function (engine) {
  70713. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70714. engine.clear(clearOne, false, true, false);
  70715. }
  70716. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  70717. engine.clear(clearZero, true, true, false);
  70718. }
  70719. else {
  70720. engine.clear(clearOne, true, true, false);
  70721. }
  70722. });
  70723. };
  70724. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  70725. var _this = this;
  70726. var engine = this._scene.getEngine();
  70727. var targetSize = this._mapSize / this.blurScale;
  70728. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  70729. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  70730. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70731. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70732. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70733. }
  70734. if (this.useKernelBlur) {
  70735. 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);
  70736. this._kernelBlurXPostprocess.width = targetSize;
  70737. this._kernelBlurXPostprocess.height = targetSize;
  70738. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  70739. effect.setTexture("textureSampler", _this._shadowMap);
  70740. });
  70741. 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);
  70742. this._kernelBlurXPostprocess.autoClear = false;
  70743. this._kernelBlurYPostprocess.autoClear = false;
  70744. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70745. this._kernelBlurXPostprocess.packedFloat = true;
  70746. this._kernelBlurYPostprocess.packedFloat = true;
  70747. }
  70748. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  70749. }
  70750. else {
  70751. 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);
  70752. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  70753. effect.setFloat2("screenSize", targetSize, targetSize);
  70754. effect.setTexture("textureSampler", _this._shadowMap);
  70755. });
  70756. this._boxBlurPostprocess.autoClear = false;
  70757. this._blurPostProcesses = [this._boxBlurPostprocess];
  70758. }
  70759. };
  70760. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70761. var index;
  70762. var engine = this._scene.getEngine();
  70763. if (depthOnlySubMeshes.length) {
  70764. engine.setColorWrite(false);
  70765. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70766. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  70767. }
  70768. engine.setColorWrite(true);
  70769. }
  70770. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70771. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  70772. }
  70773. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70774. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  70775. }
  70776. if (this._transparencyShadow) {
  70777. for (index = 0; index < transparentSubMeshes.length; index++) {
  70778. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  70779. }
  70780. }
  70781. };
  70782. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  70783. var _this = this;
  70784. var mesh = subMesh.getRenderingMesh();
  70785. var scene = this._scene;
  70786. var engine = scene.getEngine();
  70787. var material = subMesh.getMaterial();
  70788. if (!material) {
  70789. return;
  70790. }
  70791. // Culling
  70792. engine.setState(material.backFaceCulling);
  70793. // Managing instances
  70794. var batch = mesh._getInstancesRenderList(subMesh._id);
  70795. if (batch.mustReturn) {
  70796. return;
  70797. }
  70798. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  70799. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  70800. engine.enableEffect(this._effect);
  70801. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  70802. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  70803. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  70804. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  70805. this._effect.setVector3("lightData", this._cachedDirection);
  70806. }
  70807. else {
  70808. this._effect.setVector3("lightData", this._cachedPosition);
  70809. }
  70810. if (scene.activeCamera) {
  70811. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  70812. }
  70813. // Alpha test
  70814. if (material && material.needAlphaTesting()) {
  70815. var alphaTexture = material.getAlphaTestTexture();
  70816. if (alphaTexture) {
  70817. this._effect.setTexture("diffuseSampler", alphaTexture);
  70818. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  70819. }
  70820. }
  70821. // Bones
  70822. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70823. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  70824. }
  70825. // Morph targets
  70826. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  70827. if (this.forceBackFacesOnly) {
  70828. engine.setState(true, 0, false, true);
  70829. }
  70830. // Draw
  70831. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70832. if (this.forceBackFacesOnly) {
  70833. engine.setState(true, 0, false, false);
  70834. }
  70835. }
  70836. else {
  70837. // Need to reset refresh rate of the shadowMap
  70838. if (this._shadowMap) {
  70839. this._shadowMap.resetRefreshCounter();
  70840. }
  70841. }
  70842. };
  70843. ShadowGenerator.prototype._applyFilterValues = function () {
  70844. if (!this._shadowMap) {
  70845. return;
  70846. }
  70847. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  70848. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  70849. }
  70850. else {
  70851. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70852. }
  70853. };
  70854. /**
  70855. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  70856. * @param onCompiled Callback triggered at the and of the effects compilation
  70857. * @param options Sets of optional options forcing the compilation with different modes
  70858. */
  70859. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  70860. var _this = this;
  70861. var localOptions = __assign({ useInstances: false }, options);
  70862. var shadowMap = this.getShadowMap();
  70863. if (!shadowMap) {
  70864. if (onCompiled) {
  70865. onCompiled(this);
  70866. }
  70867. return;
  70868. }
  70869. var renderList = shadowMap.renderList;
  70870. if (!renderList) {
  70871. if (onCompiled) {
  70872. onCompiled(this);
  70873. }
  70874. return;
  70875. }
  70876. var subMeshes = new Array();
  70877. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  70878. var mesh = renderList_1[_i];
  70879. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  70880. }
  70881. if (subMeshes.length === 0) {
  70882. if (onCompiled) {
  70883. onCompiled(this);
  70884. }
  70885. return;
  70886. }
  70887. var currentIndex = 0;
  70888. var checkReady = function () {
  70889. if (!_this._scene || !_this._scene.getEngine()) {
  70890. return;
  70891. }
  70892. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  70893. currentIndex++;
  70894. if (currentIndex >= subMeshes.length) {
  70895. if (onCompiled) {
  70896. onCompiled(_this);
  70897. }
  70898. return;
  70899. }
  70900. }
  70901. setTimeout(checkReady, 16);
  70902. };
  70903. checkReady();
  70904. };
  70905. /**
  70906. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  70907. * @param options Sets of optional options forcing the compilation with different modes
  70908. * @returns A promise that resolves when the compilation completes
  70909. */
  70910. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  70911. var _this = this;
  70912. return new Promise(function (resolve) {
  70913. _this.forceCompilation(function () {
  70914. resolve();
  70915. }, options);
  70916. });
  70917. };
  70918. /**
  70919. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  70920. * @param subMesh The submesh we want to render in the shadow map
  70921. * @param useInstances Defines wether will draw in the map using instances
  70922. * @returns true if ready otherwise, false
  70923. */
  70924. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  70925. var defines = [];
  70926. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70927. defines.push("#define FLOAT");
  70928. }
  70929. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  70930. defines.push("#define ESM");
  70931. }
  70932. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  70933. defines.push("#define DEPTHTEXTURE");
  70934. }
  70935. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70936. var mesh = subMesh.getMesh();
  70937. var material = subMesh.getMaterial();
  70938. // Normal bias.
  70939. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  70940. attribs.push(BABYLON.VertexBuffer.NormalKind);
  70941. defines.push("#define NORMAL");
  70942. if (mesh.nonUniformScaling) {
  70943. defines.push("#define NONUNIFORMSCALING");
  70944. }
  70945. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  70946. defines.push("#define DIRECTIONINLIGHTDATA");
  70947. }
  70948. }
  70949. // Alpha test
  70950. if (material && material.needAlphaTesting()) {
  70951. var alphaTexture = material.getAlphaTestTexture();
  70952. if (alphaTexture) {
  70953. defines.push("#define ALPHATEST");
  70954. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70955. attribs.push(BABYLON.VertexBuffer.UVKind);
  70956. defines.push("#define UV1");
  70957. }
  70958. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70959. if (alphaTexture.coordinatesIndex === 1) {
  70960. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70961. defines.push("#define UV2");
  70962. }
  70963. }
  70964. }
  70965. }
  70966. // Bones
  70967. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70968. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70969. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70970. if (mesh.numBoneInfluencers > 4) {
  70971. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70972. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70973. }
  70974. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70975. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  70976. }
  70977. else {
  70978. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70979. }
  70980. // Morph targets
  70981. var manager = mesh.morphTargetManager;
  70982. var morphInfluencers = 0;
  70983. if (manager) {
  70984. if (manager.numInfluencers > 0) {
  70985. defines.push("#define MORPHTARGETS");
  70986. morphInfluencers = manager.numInfluencers;
  70987. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  70988. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  70989. }
  70990. }
  70991. // Instances
  70992. if (useInstances) {
  70993. defines.push("#define INSTANCES");
  70994. attribs.push("world0");
  70995. attribs.push("world1");
  70996. attribs.push("world2");
  70997. attribs.push("world3");
  70998. }
  70999. // Get correct effect
  71000. var join = defines.join("\n");
  71001. if (this._cachedDefines !== join) {
  71002. this._cachedDefines = join;
  71003. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  71004. }
  71005. if (!this._effect.isReady()) {
  71006. return false;
  71007. }
  71008. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  71009. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  71010. this._initializeBlurRTTAndPostProcesses();
  71011. }
  71012. }
  71013. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  71014. return false;
  71015. }
  71016. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  71017. return false;
  71018. }
  71019. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  71020. return false;
  71021. }
  71022. return true;
  71023. };
  71024. /**
  71025. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  71026. * @param defines Defines of the material we want to update
  71027. * @param lightIndex Index of the light in the enabled light list of the material
  71028. */
  71029. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  71030. var scene = this._scene;
  71031. var light = this._light;
  71032. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  71033. return;
  71034. }
  71035. defines["SHADOW" + lightIndex] = true;
  71036. if (this.useContactHardeningShadow) {
  71037. defines["SHADOWPCSS" + lightIndex] = true;
  71038. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  71039. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  71040. }
  71041. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  71042. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  71043. }
  71044. // else default to high.
  71045. }
  71046. if (this.usePercentageCloserFiltering) {
  71047. defines["SHADOWPCF" + lightIndex] = true;
  71048. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  71049. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  71050. }
  71051. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  71052. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  71053. }
  71054. // else default to high.
  71055. }
  71056. else if (this.usePoissonSampling) {
  71057. defines["SHADOWPOISSON" + lightIndex] = true;
  71058. }
  71059. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  71060. defines["SHADOWESM" + lightIndex] = true;
  71061. }
  71062. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  71063. defines["SHADOWCLOSEESM" + lightIndex] = true;
  71064. }
  71065. if (light.needCube()) {
  71066. defines["SHADOWCUBE" + lightIndex] = true;
  71067. }
  71068. };
  71069. /**
  71070. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  71071. * defined in the generator but impacting the effect).
  71072. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  71073. * @param effect The effect we are binfing the information for
  71074. */
  71075. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  71076. var light = this._light;
  71077. var scene = this._scene;
  71078. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  71079. return;
  71080. }
  71081. var camera = scene.activeCamera;
  71082. if (!camera) {
  71083. return;
  71084. }
  71085. var shadowMap = this.getShadowMap();
  71086. if (!shadowMap) {
  71087. return;
  71088. }
  71089. if (!light.needCube()) {
  71090. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  71091. }
  71092. // Only PCF uses depth stencil texture.
  71093. if (this._filter === ShadowGenerator.FILTER_PCF) {
  71094. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  71095. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  71096. }
  71097. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  71098. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  71099. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  71100. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  71101. }
  71102. else {
  71103. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  71104. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  71105. }
  71106. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  71107. };
  71108. /**
  71109. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  71110. * (eq to shadow prjection matrix * light transform matrix)
  71111. * @returns The transform matrix used to create the shadow map
  71112. */
  71113. ShadowGenerator.prototype.getTransformMatrix = function () {
  71114. var scene = this._scene;
  71115. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  71116. return this._transformMatrix;
  71117. }
  71118. this._currentRenderID = scene.getRenderId();
  71119. this._currentFaceIndexCache = this._currentFaceIndex;
  71120. var lightPosition = this._light.position;
  71121. if (this._light.computeTransformedInformation()) {
  71122. lightPosition = this._light.transformedPosition;
  71123. }
  71124. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  71125. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  71126. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  71127. }
  71128. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  71129. this._cachedPosition.copyFrom(lightPosition);
  71130. this._cachedDirection.copyFrom(this._lightDirection);
  71131. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  71132. var shadowMap = this.getShadowMap();
  71133. if (shadowMap) {
  71134. var renderList = shadowMap.renderList;
  71135. if (renderList) {
  71136. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  71137. }
  71138. }
  71139. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  71140. }
  71141. return this._transformMatrix;
  71142. };
  71143. /**
  71144. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  71145. * Cube and 2D textures for instance.
  71146. */
  71147. ShadowGenerator.prototype.recreateShadowMap = function () {
  71148. var shadowMap = this._shadowMap;
  71149. if (!shadowMap) {
  71150. return;
  71151. }
  71152. // Track render list.
  71153. var renderList = shadowMap.renderList;
  71154. // Clean up existing data.
  71155. this._disposeRTTandPostProcesses();
  71156. // Reinitializes.
  71157. this._initializeGenerator();
  71158. // Reaffect the filter to ensure a correct fallback if necessary.
  71159. this.filter = this.filter;
  71160. // Reaffect the filter.
  71161. this._applyFilterValues();
  71162. // Reaffect Render List.
  71163. this._shadowMap.renderList = renderList;
  71164. };
  71165. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  71166. if (this._shadowMap2) {
  71167. this._shadowMap2.dispose();
  71168. this._shadowMap2 = null;
  71169. }
  71170. if (this._boxBlurPostprocess) {
  71171. this._boxBlurPostprocess.dispose();
  71172. this._boxBlurPostprocess = null;
  71173. }
  71174. if (this._kernelBlurXPostprocess) {
  71175. this._kernelBlurXPostprocess.dispose();
  71176. this._kernelBlurXPostprocess = null;
  71177. }
  71178. if (this._kernelBlurYPostprocess) {
  71179. this._kernelBlurYPostprocess.dispose();
  71180. this._kernelBlurYPostprocess = null;
  71181. }
  71182. this._blurPostProcesses = [];
  71183. };
  71184. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  71185. if (this._shadowMap) {
  71186. this._shadowMap.dispose();
  71187. this._shadowMap = null;
  71188. }
  71189. this._disposeBlurPostProcesses();
  71190. };
  71191. /**
  71192. * Disposes the ShadowGenerator.
  71193. * Returns nothing.
  71194. */
  71195. ShadowGenerator.prototype.dispose = function () {
  71196. this._disposeRTTandPostProcesses();
  71197. if (this._light) {
  71198. this._light._shadowGenerator = null;
  71199. this._light._markMeshesAsLightDirty();
  71200. }
  71201. };
  71202. /**
  71203. * Serializes the shadow generator setup to a json object.
  71204. * @returns The serialized JSON object
  71205. */
  71206. ShadowGenerator.prototype.serialize = function () {
  71207. var serializationObject = {};
  71208. var shadowMap = this.getShadowMap();
  71209. if (!shadowMap) {
  71210. return serializationObject;
  71211. }
  71212. serializationObject.lightId = this._light.id;
  71213. serializationObject.mapSize = shadowMap.getRenderSize();
  71214. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  71215. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  71216. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  71217. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  71218. serializationObject.usePoissonSampling = this.usePoissonSampling;
  71219. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  71220. serializationObject.depthScale = this.depthScale;
  71221. serializationObject.darkness = this.getDarkness();
  71222. serializationObject.blurBoxOffset = this.blurBoxOffset;
  71223. serializationObject.blurKernel = this.blurKernel;
  71224. serializationObject.blurScale = this.blurScale;
  71225. serializationObject.useKernelBlur = this.useKernelBlur;
  71226. serializationObject.transparencyShadow = this._transparencyShadow;
  71227. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  71228. serializationObject.bias = this.bias;
  71229. serializationObject.normalBias = this.normalBias;
  71230. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  71231. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  71232. serializationObject.filteringQuality = this.filteringQuality;
  71233. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  71234. serializationObject.renderList = [];
  71235. if (shadowMap.renderList) {
  71236. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  71237. var mesh = shadowMap.renderList[meshIndex];
  71238. serializationObject.renderList.push(mesh.id);
  71239. }
  71240. }
  71241. return serializationObject;
  71242. };
  71243. /**
  71244. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  71245. * @param parsedShadowGenerator The JSON object to parse
  71246. * @param scene The scene to create the shadow map for
  71247. * @returns The parsed shadow generator
  71248. */
  71249. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  71250. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  71251. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  71252. var shadowMap = shadowGenerator.getShadowMap();
  71253. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  71254. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  71255. meshes.forEach(function (mesh) {
  71256. if (!shadowMap) {
  71257. return;
  71258. }
  71259. if (!shadowMap.renderList) {
  71260. shadowMap.renderList = [];
  71261. }
  71262. shadowMap.renderList.push(mesh);
  71263. });
  71264. }
  71265. if (parsedShadowGenerator.usePoissonSampling) {
  71266. shadowGenerator.usePoissonSampling = true;
  71267. }
  71268. else if (parsedShadowGenerator.useExponentialShadowMap) {
  71269. shadowGenerator.useExponentialShadowMap = true;
  71270. }
  71271. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  71272. shadowGenerator.useBlurExponentialShadowMap = true;
  71273. }
  71274. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  71275. shadowGenerator.useCloseExponentialShadowMap = true;
  71276. }
  71277. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  71278. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  71279. }
  71280. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  71281. shadowGenerator.usePercentageCloserFiltering = true;
  71282. }
  71283. else if (parsedShadowGenerator.useContactHardeningShadow) {
  71284. shadowGenerator.useContactHardeningShadow = true;
  71285. }
  71286. if (parsedShadowGenerator.filteringQuality) {
  71287. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  71288. }
  71289. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  71290. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  71291. }
  71292. // Backward compat
  71293. else if (parsedShadowGenerator.useVarianceShadowMap) {
  71294. shadowGenerator.useExponentialShadowMap = true;
  71295. }
  71296. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  71297. shadowGenerator.useBlurExponentialShadowMap = true;
  71298. }
  71299. if (parsedShadowGenerator.depthScale) {
  71300. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  71301. }
  71302. if (parsedShadowGenerator.blurScale) {
  71303. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  71304. }
  71305. if (parsedShadowGenerator.blurBoxOffset) {
  71306. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  71307. }
  71308. if (parsedShadowGenerator.useKernelBlur) {
  71309. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  71310. }
  71311. if (parsedShadowGenerator.blurKernel) {
  71312. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  71313. }
  71314. if (parsedShadowGenerator.bias !== undefined) {
  71315. shadowGenerator.bias = parsedShadowGenerator.bias;
  71316. }
  71317. if (parsedShadowGenerator.normalBias !== undefined) {
  71318. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  71319. }
  71320. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  71321. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  71322. }
  71323. if (parsedShadowGenerator.darkness) {
  71324. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  71325. }
  71326. if (parsedShadowGenerator.transparencyShadow) {
  71327. shadowGenerator.setTransparencyShadow(true);
  71328. }
  71329. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  71330. return shadowGenerator;
  71331. };
  71332. /**
  71333. * Shadow generator mode None: no filtering applied.
  71334. */
  71335. ShadowGenerator.FILTER_NONE = 0;
  71336. /**
  71337. * Shadow generator mode ESM: Exponential Shadow Mapping.
  71338. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71339. */
  71340. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  71341. /**
  71342. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  71343. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  71344. */
  71345. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  71346. /**
  71347. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  71348. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71349. */
  71350. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  71351. /**
  71352. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  71353. * edge artifacts on steep falloff.
  71354. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71355. */
  71356. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  71357. /**
  71358. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  71359. * edge artifacts on steep falloff.
  71360. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71361. */
  71362. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  71363. /**
  71364. * Shadow generator mode PCF: Percentage Closer Filtering
  71365. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  71366. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  71367. */
  71368. ShadowGenerator.FILTER_PCF = 6;
  71369. /**
  71370. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  71371. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  71372. * Contact Hardening
  71373. */
  71374. ShadowGenerator.FILTER_PCSS = 7;
  71375. /**
  71376. * Reserved for PCF and PCSS
  71377. * Highest Quality.
  71378. *
  71379. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  71380. *
  71381. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  71382. */
  71383. ShadowGenerator.QUALITY_HIGH = 0;
  71384. /**
  71385. * Reserved for PCF and PCSS
  71386. * Good tradeoff for quality/perf cross devices
  71387. *
  71388. * Execute PCF on a 3*3 kernel.
  71389. *
  71390. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  71391. */
  71392. ShadowGenerator.QUALITY_MEDIUM = 1;
  71393. /**
  71394. * Reserved for PCF and PCSS
  71395. * The lowest quality but the fastest.
  71396. *
  71397. * Execute PCF on a 1*1 kernel.
  71398. *
  71399. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  71400. */
  71401. ShadowGenerator.QUALITY_LOW = 2;
  71402. return ShadowGenerator;
  71403. }());
  71404. BABYLON.ShadowGenerator = ShadowGenerator;
  71405. })(BABYLON || (BABYLON = {}));
  71406. //# sourceMappingURL=babylon.shadowGenerator.js.map
  71407. var BABYLON;
  71408. (function (BABYLON) {
  71409. // Adds the parser to the scene parsers.
  71410. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  71411. // Shadows
  71412. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  71413. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  71414. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  71415. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  71416. // SG would be available on their associated lights
  71417. }
  71418. }
  71419. });
  71420. /**
  71421. * Defines the shadow generator component responsible to manage any shadow generators
  71422. * in a given scene.
  71423. */
  71424. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  71425. /**
  71426. * Creates a new instance of the component for the given scene
  71427. * @param scene Defines the scene to register the component in
  71428. */
  71429. function ShadowGeneratorSceneComponent(scene) {
  71430. /**
  71431. * The component name helpfull to identify the component in the list of scene components.
  71432. */
  71433. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  71434. this.scene = scene;
  71435. }
  71436. /**
  71437. * Registers the component in a given scene
  71438. */
  71439. ShadowGeneratorSceneComponent.prototype.register = function () {
  71440. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  71441. };
  71442. /**
  71443. * Rebuilds the elements related to this component in case of
  71444. * context lost for instance.
  71445. */
  71446. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  71447. // Nothing To Do Here.
  71448. };
  71449. /**
  71450. * Serializes the component data to the specified json object
  71451. * @param serializationObject The object to serialize to
  71452. */
  71453. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  71454. // Shadows
  71455. serializationObject.shadowGenerators = [];
  71456. var lights = this.scene.lights;
  71457. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  71458. var light = lights_1[_i];
  71459. var shadowGenerator = light.getShadowGenerator();
  71460. if (shadowGenerator) {
  71461. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  71462. }
  71463. }
  71464. };
  71465. /**
  71466. * Adds all the element from the container to the scene
  71467. * @param container the container holding the elements
  71468. */
  71469. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  71470. // Nothing To Do Here. (directly attached to a light)
  71471. };
  71472. /**
  71473. * Removes all the elements in the container from the scene
  71474. * @param container contains the elements to remove
  71475. */
  71476. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  71477. // Nothing To Do Here. (directly attached to a light)
  71478. };
  71479. /**
  71480. * Rebuilds the elements related to this component in case of
  71481. * context lost for instance.
  71482. */
  71483. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  71484. // Nothing To Do Here.
  71485. };
  71486. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  71487. // Shadows
  71488. var scene = this.scene;
  71489. if (this.scene.shadowsEnabled) {
  71490. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  71491. var light = scene.lights[lightIndex];
  71492. var shadowGenerator = light.getShadowGenerator();
  71493. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  71494. var shadowMap = (shadowGenerator.getShadowMap());
  71495. if (scene.textures.indexOf(shadowMap) !== -1) {
  71496. renderTargets.push(shadowMap);
  71497. }
  71498. }
  71499. }
  71500. }
  71501. };
  71502. return ShadowGeneratorSceneComponent;
  71503. }());
  71504. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  71505. })(BABYLON || (BABYLON = {}));
  71506. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  71507. var BABYLON;
  71508. (function (BABYLON) {
  71509. var DefaultLoadingScreen = /** @class */ (function () {
  71510. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  71511. if (_loadingText === void 0) { _loadingText = ""; }
  71512. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  71513. var _this = this;
  71514. this._renderingCanvas = _renderingCanvas;
  71515. this._loadingText = _loadingText;
  71516. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  71517. // Resize
  71518. this._resizeLoadingUI = function () {
  71519. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  71520. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  71521. if (!_this._loadingDiv) {
  71522. return;
  71523. }
  71524. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  71525. _this._loadingDiv.style.left = canvasRect.left + "px";
  71526. _this._loadingDiv.style.top = canvasRect.top + "px";
  71527. _this._loadingDiv.style.width = canvasRect.width + "px";
  71528. _this._loadingDiv.style.height = canvasRect.height + "px";
  71529. };
  71530. }
  71531. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  71532. if (this._loadingDiv) {
  71533. // Do not add a loading screen if there is already one
  71534. return;
  71535. }
  71536. this._loadingDiv = document.createElement("div");
  71537. this._loadingDiv.id = "babylonjsLoadingDiv";
  71538. this._loadingDiv.style.opacity = "0";
  71539. this._loadingDiv.style.transition = "opacity 1.5s ease";
  71540. this._loadingDiv.style.pointerEvents = "none";
  71541. // Loading text
  71542. this._loadingTextDiv = document.createElement("div");
  71543. this._loadingTextDiv.style.position = "absolute";
  71544. this._loadingTextDiv.style.left = "0";
  71545. this._loadingTextDiv.style.top = "50%";
  71546. this._loadingTextDiv.style.marginTop = "80px";
  71547. this._loadingTextDiv.style.width = "100%";
  71548. this._loadingTextDiv.style.height = "20px";
  71549. this._loadingTextDiv.style.fontFamily = "Arial";
  71550. this._loadingTextDiv.style.fontSize = "14px";
  71551. this._loadingTextDiv.style.color = "white";
  71552. this._loadingTextDiv.style.textAlign = "center";
  71553. this._loadingTextDiv.innerHTML = "Loading";
  71554. this._loadingDiv.appendChild(this._loadingTextDiv);
  71555. //set the predefined text
  71556. this._loadingTextDiv.innerHTML = this._loadingText;
  71557. // Generating keyframes
  71558. var style = document.createElement('style');
  71559. style.type = 'text/css';
  71560. 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 }";
  71561. style.innerHTML = keyFrames;
  71562. document.getElementsByTagName('head')[0].appendChild(style);
  71563. // Loading img
  71564. var imgBack = new Image();
  71565. 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";
  71566. imgBack.style.position = "absolute";
  71567. imgBack.style.left = "50%";
  71568. imgBack.style.top = "50%";
  71569. imgBack.style.marginLeft = "-60px";
  71570. imgBack.style.marginTop = "-60px";
  71571. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  71572. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  71573. imgBack.style.transformOrigin = "50% 50%";
  71574. imgBack.style.webkitTransformOrigin = "50% 50%";
  71575. this._loadingDiv.appendChild(imgBack);
  71576. this._resizeLoadingUI();
  71577. window.addEventListener("resize", this._resizeLoadingUI);
  71578. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  71579. document.body.appendChild(this._loadingDiv);
  71580. this._loadingDiv.style.opacity = "1";
  71581. };
  71582. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  71583. var _this = this;
  71584. if (!this._loadingDiv) {
  71585. return;
  71586. }
  71587. var onTransitionEnd = function () {
  71588. if (!_this._loadingDiv) {
  71589. return;
  71590. }
  71591. document.body.removeChild(_this._loadingDiv);
  71592. window.removeEventListener("resize", _this._resizeLoadingUI);
  71593. _this._loadingDiv = null;
  71594. };
  71595. this._loadingDiv.style.opacity = "0";
  71596. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  71597. };
  71598. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  71599. set: function (text) {
  71600. this._loadingText = text;
  71601. if (this._loadingTextDiv) {
  71602. this._loadingTextDiv.innerHTML = this._loadingText;
  71603. }
  71604. },
  71605. enumerable: true,
  71606. configurable: true
  71607. });
  71608. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  71609. get: function () {
  71610. return this._loadingDivBackgroundColor;
  71611. },
  71612. set: function (color) {
  71613. this._loadingDivBackgroundColor = color;
  71614. if (!this._loadingDiv) {
  71615. return;
  71616. }
  71617. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  71618. },
  71619. enumerable: true,
  71620. configurable: true
  71621. });
  71622. return DefaultLoadingScreen;
  71623. }());
  71624. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  71625. })(BABYLON || (BABYLON = {}));
  71626. //# sourceMappingURL=babylon.loadingScreen.js.map
  71627. var BABYLON;
  71628. (function (BABYLON) {
  71629. var SceneLoaderProgressEvent = /** @class */ (function () {
  71630. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  71631. this.lengthComputable = lengthComputable;
  71632. this.loaded = loaded;
  71633. this.total = total;
  71634. }
  71635. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  71636. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  71637. };
  71638. return SceneLoaderProgressEvent;
  71639. }());
  71640. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  71641. var SceneLoader = /** @class */ (function () {
  71642. function SceneLoader() {
  71643. }
  71644. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  71645. get: function () {
  71646. return 0;
  71647. },
  71648. enumerable: true,
  71649. configurable: true
  71650. });
  71651. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  71652. get: function () {
  71653. return 1;
  71654. },
  71655. enumerable: true,
  71656. configurable: true
  71657. });
  71658. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  71659. get: function () {
  71660. return 2;
  71661. },
  71662. enumerable: true,
  71663. configurable: true
  71664. });
  71665. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  71666. get: function () {
  71667. return 3;
  71668. },
  71669. enumerable: true,
  71670. configurable: true
  71671. });
  71672. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  71673. get: function () {
  71674. return SceneLoader._ForceFullSceneLoadingForIncremental;
  71675. },
  71676. set: function (value) {
  71677. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  71678. },
  71679. enumerable: true,
  71680. configurable: true
  71681. });
  71682. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  71683. get: function () {
  71684. return SceneLoader._ShowLoadingScreen;
  71685. },
  71686. set: function (value) {
  71687. SceneLoader._ShowLoadingScreen = value;
  71688. },
  71689. enumerable: true,
  71690. configurable: true
  71691. });
  71692. Object.defineProperty(SceneLoader, "loggingLevel", {
  71693. get: function () {
  71694. return SceneLoader._loggingLevel;
  71695. },
  71696. set: function (value) {
  71697. SceneLoader._loggingLevel = value;
  71698. },
  71699. enumerable: true,
  71700. configurable: true
  71701. });
  71702. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  71703. get: function () {
  71704. return SceneLoader._CleanBoneMatrixWeights;
  71705. },
  71706. set: function (value) {
  71707. SceneLoader._CleanBoneMatrixWeights = value;
  71708. },
  71709. enumerable: true,
  71710. configurable: true
  71711. });
  71712. SceneLoader._getDefaultPlugin = function () {
  71713. return SceneLoader._registeredPlugins[".babylon"];
  71714. };
  71715. SceneLoader._getPluginForExtension = function (extension) {
  71716. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  71717. if (registeredPlugin) {
  71718. return registeredPlugin;
  71719. }
  71720. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  71721. return SceneLoader._getDefaultPlugin();
  71722. };
  71723. SceneLoader._getPluginForDirectLoad = function (data) {
  71724. for (var extension in SceneLoader._registeredPlugins) {
  71725. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  71726. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  71727. return SceneLoader._registeredPlugins[extension];
  71728. }
  71729. }
  71730. return SceneLoader._getDefaultPlugin();
  71731. };
  71732. SceneLoader._getPluginForFilename = function (sceneFilename) {
  71733. var queryStringPosition = sceneFilename.indexOf("?");
  71734. if (queryStringPosition !== -1) {
  71735. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  71736. }
  71737. var dotPosition = sceneFilename.lastIndexOf(".");
  71738. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  71739. return SceneLoader._getPluginForExtension(extension);
  71740. };
  71741. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  71742. SceneLoader._getDirectLoad = function (sceneFilename) {
  71743. if (sceneFilename.substr(0, 5) === "data:") {
  71744. return sceneFilename.substr(5);
  71745. }
  71746. return null;
  71747. };
  71748. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  71749. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  71750. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  71751. var plugin;
  71752. if (registeredPlugin.plugin.createPlugin) {
  71753. plugin = registeredPlugin.plugin.createPlugin();
  71754. }
  71755. else {
  71756. plugin = registeredPlugin.plugin;
  71757. }
  71758. var useArrayBuffer = registeredPlugin.isBinary;
  71759. var database;
  71760. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  71761. var dataCallback = function (data, responseURL) {
  71762. if (scene.isDisposed) {
  71763. onError("Scene has been disposed");
  71764. return;
  71765. }
  71766. scene.database = database;
  71767. onSuccess(plugin, data, responseURL);
  71768. };
  71769. var request = null;
  71770. var pluginDisposed = false;
  71771. var onDisposeObservable = plugin.onDisposeObservable;
  71772. if (onDisposeObservable) {
  71773. onDisposeObservable.add(function () {
  71774. pluginDisposed = true;
  71775. if (request) {
  71776. request.abort();
  71777. request = null;
  71778. }
  71779. onDispose();
  71780. });
  71781. }
  71782. var manifestChecked = function () {
  71783. if (pluginDisposed) {
  71784. return;
  71785. }
  71786. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  71787. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  71788. } : undefined, database, useArrayBuffer, function (request, exception) {
  71789. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  71790. });
  71791. };
  71792. if (directLoad) {
  71793. dataCallback(directLoad);
  71794. return plugin;
  71795. }
  71796. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  71797. var engine = scene.getEngine();
  71798. var canUseOfflineSupport = engine.enableOfflineSupport;
  71799. if (canUseOfflineSupport) {
  71800. // Also check for exceptions
  71801. var exceptionFound = false;
  71802. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  71803. var regex = _a[_i];
  71804. if (regex.test(fileInfo.url)) {
  71805. exceptionFound = true;
  71806. break;
  71807. }
  71808. }
  71809. canUseOfflineSupport = !exceptionFound;
  71810. }
  71811. if (canUseOfflineSupport) {
  71812. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  71813. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  71814. }
  71815. else {
  71816. manifestChecked();
  71817. }
  71818. }
  71819. // Loading file from disk via input file or drag'n'drop
  71820. else {
  71821. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  71822. if (file) {
  71823. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  71824. }
  71825. else {
  71826. onError("Unable to find file named " + fileInfo.name);
  71827. }
  71828. }
  71829. return plugin;
  71830. };
  71831. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  71832. var url;
  71833. var name;
  71834. if (!sceneFilename) {
  71835. url = rootUrl;
  71836. name = BABYLON.Tools.GetFilename(rootUrl);
  71837. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71838. }
  71839. else {
  71840. if (sceneFilename.substr(0, 1) === "/") {
  71841. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71842. return null;
  71843. }
  71844. url = rootUrl + sceneFilename;
  71845. name = sceneFilename;
  71846. }
  71847. ;
  71848. return {
  71849. url: url,
  71850. rootUrl: rootUrl,
  71851. name: name
  71852. };
  71853. };
  71854. // Public functions
  71855. SceneLoader.GetPluginForExtension = function (extension) {
  71856. return SceneLoader._getPluginForExtension(extension).plugin;
  71857. };
  71858. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  71859. return !!SceneLoader._registeredPlugins[extension];
  71860. };
  71861. SceneLoader.RegisterPlugin = function (plugin) {
  71862. if (typeof plugin.extensions === "string") {
  71863. var extension = plugin.extensions;
  71864. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  71865. plugin: plugin,
  71866. isBinary: false
  71867. };
  71868. }
  71869. else {
  71870. var extensions = plugin.extensions;
  71871. Object.keys(extensions).forEach(function (extension) {
  71872. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  71873. plugin: plugin,
  71874. isBinary: extensions[extension].isBinary
  71875. };
  71876. });
  71877. }
  71878. };
  71879. /**
  71880. * Import meshes into a scene
  71881. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  71882. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  71883. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  71884. * @param scene the instance of BABYLON.Scene to append to
  71885. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  71886. * @param onProgress a callback with a progress event for each file being loaded
  71887. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71888. * @param pluginExtension the extension used to determine the plugin
  71889. * @returns The loaded plugin
  71890. */
  71891. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71892. if (sceneFilename === void 0) { sceneFilename = ""; }
  71893. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71894. if (onSuccess === void 0) { onSuccess = null; }
  71895. if (onProgress === void 0) { onProgress = null; }
  71896. if (onError === void 0) { onError = null; }
  71897. if (pluginExtension === void 0) { pluginExtension = null; }
  71898. if (!scene) {
  71899. BABYLON.Tools.Error("No scene available to import mesh to");
  71900. return null;
  71901. }
  71902. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  71903. if (!fileInfo) {
  71904. return null;
  71905. }
  71906. var loadingToken = {};
  71907. scene._addPendingData(loadingToken);
  71908. var disposeHandler = function () {
  71909. scene._removePendingData(loadingToken);
  71910. };
  71911. var errorHandler = function (message, exception) {
  71912. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  71913. if (onError) {
  71914. onError(scene, errorMessage, exception);
  71915. }
  71916. else {
  71917. BABYLON.Tools.Error(errorMessage);
  71918. // should the exception be thrown?
  71919. }
  71920. disposeHandler();
  71921. };
  71922. var progressHandler = onProgress ? function (event) {
  71923. try {
  71924. onProgress(event);
  71925. }
  71926. catch (e) {
  71927. errorHandler("Error in onProgress callback", e);
  71928. }
  71929. } : undefined;
  71930. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  71931. scene.importedMeshesFiles.push(fileInfo.url);
  71932. if (onSuccess) {
  71933. try {
  71934. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  71935. }
  71936. catch (e) {
  71937. errorHandler("Error in onSuccess callback", e);
  71938. }
  71939. }
  71940. scene._removePendingData(loadingToken);
  71941. };
  71942. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  71943. if (plugin.rewriteRootURL) {
  71944. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  71945. }
  71946. if (plugin.importMesh) {
  71947. var syncedPlugin = plugin;
  71948. var meshes = new Array();
  71949. var particleSystems = new Array();
  71950. var skeletons = new Array();
  71951. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  71952. return;
  71953. }
  71954. scene.loadingPluginName = plugin.name;
  71955. successHandler(meshes, particleSystems, skeletons, []);
  71956. }
  71957. else {
  71958. var asyncedPlugin = plugin;
  71959. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  71960. scene.loadingPluginName = plugin.name;
  71961. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  71962. }).catch(function (error) {
  71963. errorHandler(error.message, error);
  71964. });
  71965. }
  71966. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71967. };
  71968. /**
  71969. * Import meshes into a scene
  71970. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  71971. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  71972. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  71973. * @param scene the instance of BABYLON.Scene to append to
  71974. * @param onProgress a callback with a progress event for each file being loaded
  71975. * @param pluginExtension the extension used to determine the plugin
  71976. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  71977. */
  71978. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71979. if (sceneFilename === void 0) { sceneFilename = ""; }
  71980. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71981. if (onProgress === void 0) { onProgress = null; }
  71982. if (pluginExtension === void 0) { pluginExtension = null; }
  71983. return new Promise(function (resolve, reject) {
  71984. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  71985. resolve({
  71986. meshes: meshes,
  71987. particleSystems: particleSystems,
  71988. skeletons: skeletons,
  71989. animationGroups: animationGroups
  71990. });
  71991. }, onProgress, function (scene, message, exception) {
  71992. reject(exception || new Error(message));
  71993. }, pluginExtension);
  71994. });
  71995. };
  71996. /**
  71997. * Load a scene
  71998. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  71999. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72000. * @param engine is the instance of BABYLON.Engine to use to create the scene
  72001. * @param onSuccess a callback with the scene when import succeeds
  72002. * @param onProgress a callback with a progress event for each file being loaded
  72003. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  72004. * @param pluginExtension the extension used to determine the plugin
  72005. * @returns The loaded plugin
  72006. */
  72007. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  72008. if (onSuccess === void 0) { onSuccess = null; }
  72009. if (onProgress === void 0) { onProgress = null; }
  72010. if (onError === void 0) { onError = null; }
  72011. if (pluginExtension === void 0) { pluginExtension = null; }
  72012. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  72013. };
  72014. /**
  72015. * Load a scene
  72016. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72017. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72018. * @param engine is the instance of BABYLON.Engine to use to create the scene
  72019. * @param onProgress a callback with a progress event for each file being loaded
  72020. * @param pluginExtension the extension used to determine the plugin
  72021. * @returns The loaded scene
  72022. */
  72023. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  72024. if (onProgress === void 0) { onProgress = null; }
  72025. if (pluginExtension === void 0) { pluginExtension = null; }
  72026. return new Promise(function (resolve, reject) {
  72027. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  72028. resolve(scene);
  72029. }, onProgress, function (scene, message, exception) {
  72030. reject(exception || new Error(message));
  72031. }, pluginExtension);
  72032. });
  72033. };
  72034. /**
  72035. * Append a scene
  72036. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72037. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72038. * @param scene is the instance of BABYLON.Scene to append to
  72039. * @param onSuccess a callback with the scene when import succeeds
  72040. * @param onProgress a callback with a progress event for each file being loaded
  72041. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  72042. * @param pluginExtension the extension used to determine the plugin
  72043. * @returns The loaded plugin
  72044. */
  72045. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  72046. if (sceneFilename === void 0) { sceneFilename = ""; }
  72047. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72048. if (onSuccess === void 0) { onSuccess = null; }
  72049. if (onProgress === void 0) { onProgress = null; }
  72050. if (onError === void 0) { onError = null; }
  72051. if (pluginExtension === void 0) { pluginExtension = null; }
  72052. if (!scene) {
  72053. BABYLON.Tools.Error("No scene available to append to");
  72054. return null;
  72055. }
  72056. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  72057. if (!fileInfo) {
  72058. return null;
  72059. }
  72060. if (SceneLoader.ShowLoadingScreen) {
  72061. scene.getEngine().displayLoadingUI();
  72062. }
  72063. var loadingToken = {};
  72064. scene._addPendingData(loadingToken);
  72065. var disposeHandler = function () {
  72066. scene._removePendingData(loadingToken);
  72067. scene.getEngine().hideLoadingUI();
  72068. };
  72069. var errorHandler = function (message, exception) {
  72070. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  72071. if (onError) {
  72072. onError(scene, errorMessage, exception);
  72073. }
  72074. else {
  72075. BABYLON.Tools.Error(errorMessage);
  72076. // should the exception be thrown?
  72077. }
  72078. disposeHandler();
  72079. };
  72080. var progressHandler = onProgress ? function (event) {
  72081. try {
  72082. onProgress(event);
  72083. }
  72084. catch (e) {
  72085. errorHandler("Error in onProgress callback", e);
  72086. }
  72087. } : undefined;
  72088. var successHandler = function () {
  72089. if (onSuccess) {
  72090. try {
  72091. onSuccess(scene);
  72092. }
  72093. catch (e) {
  72094. errorHandler("Error in onSuccess callback", e);
  72095. }
  72096. }
  72097. scene._removePendingData(loadingToken);
  72098. };
  72099. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  72100. if (plugin.load) {
  72101. var syncedPlugin = plugin;
  72102. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  72103. return;
  72104. }
  72105. scene.loadingPluginName = plugin.name;
  72106. successHandler();
  72107. }
  72108. else {
  72109. var asyncedPlugin = plugin;
  72110. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  72111. scene.loadingPluginName = plugin.name;
  72112. successHandler();
  72113. }).catch(function (error) {
  72114. errorHandler(error.message, error);
  72115. });
  72116. }
  72117. if (SceneLoader.ShowLoadingScreen) {
  72118. scene.executeWhenReady(function () {
  72119. scene.getEngine().hideLoadingUI();
  72120. });
  72121. }
  72122. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  72123. };
  72124. /**
  72125. * Append a scene
  72126. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72127. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72128. * @param scene is the instance of BABYLON.Scene to append to
  72129. * @param onProgress a callback with a progress event for each file being loaded
  72130. * @param pluginExtension the extension used to determine the plugin
  72131. * @returns The given scene
  72132. */
  72133. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  72134. if (sceneFilename === void 0) { sceneFilename = ""; }
  72135. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72136. if (onProgress === void 0) { onProgress = null; }
  72137. if (pluginExtension === void 0) { pluginExtension = null; }
  72138. return new Promise(function (resolve, reject) {
  72139. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  72140. resolve(scene);
  72141. }, onProgress, function (scene, message, exception) {
  72142. reject(exception || new Error(message));
  72143. }, pluginExtension);
  72144. });
  72145. };
  72146. /**
  72147. * Load a scene into an asset container
  72148. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72149. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72150. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  72151. * @param onSuccess a callback with the scene when import succeeds
  72152. * @param onProgress a callback with a progress event for each file being loaded
  72153. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  72154. * @param pluginExtension the extension used to determine the plugin
  72155. * @returns The loaded plugin
  72156. */
  72157. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  72158. if (sceneFilename === void 0) { sceneFilename = ""; }
  72159. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72160. if (onSuccess === void 0) { onSuccess = null; }
  72161. if (onProgress === void 0) { onProgress = null; }
  72162. if (onError === void 0) { onError = null; }
  72163. if (pluginExtension === void 0) { pluginExtension = null; }
  72164. if (!scene) {
  72165. BABYLON.Tools.Error("No scene available to load asset container to");
  72166. return null;
  72167. }
  72168. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  72169. if (!fileInfo) {
  72170. return null;
  72171. }
  72172. var loadingToken = {};
  72173. scene._addPendingData(loadingToken);
  72174. var disposeHandler = function () {
  72175. scene._removePendingData(loadingToken);
  72176. };
  72177. var errorHandler = function (message, exception) {
  72178. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  72179. if (onError) {
  72180. onError(scene, errorMessage, exception);
  72181. }
  72182. else {
  72183. BABYLON.Tools.Error(errorMessage);
  72184. // should the exception be thrown?
  72185. }
  72186. disposeHandler();
  72187. };
  72188. var progressHandler = onProgress ? function (event) {
  72189. try {
  72190. onProgress(event);
  72191. }
  72192. catch (e) {
  72193. errorHandler("Error in onProgress callback", e);
  72194. }
  72195. } : undefined;
  72196. var successHandler = function (assets) {
  72197. if (onSuccess) {
  72198. try {
  72199. onSuccess(assets);
  72200. }
  72201. catch (e) {
  72202. errorHandler("Error in onSuccess callback", e);
  72203. }
  72204. }
  72205. scene._removePendingData(loadingToken);
  72206. };
  72207. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  72208. if (plugin.loadAssetContainer) {
  72209. var syncedPlugin = plugin;
  72210. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  72211. if (!assetContainer) {
  72212. return;
  72213. }
  72214. scene.loadingPluginName = plugin.name;
  72215. successHandler(assetContainer);
  72216. }
  72217. else if (plugin.loadAssetContainerAsync) {
  72218. var asyncedPlugin = plugin;
  72219. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  72220. scene.loadingPluginName = plugin.name;
  72221. successHandler(assetContainer);
  72222. }).catch(function (error) {
  72223. errorHandler(error.message, error);
  72224. });
  72225. }
  72226. else {
  72227. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  72228. }
  72229. if (SceneLoader.ShowLoadingScreen) {
  72230. scene.executeWhenReady(function () {
  72231. scene.getEngine().hideLoadingUI();
  72232. });
  72233. }
  72234. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  72235. };
  72236. /**
  72237. * Load a scene into an asset container
  72238. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72239. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72240. * @param scene is the instance of BABYLON.Scene to append to
  72241. * @param onProgress a callback with a progress event for each file being loaded
  72242. * @param pluginExtension the extension used to determine the plugin
  72243. * @returns The loaded asset container
  72244. */
  72245. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  72246. if (sceneFilename === void 0) { sceneFilename = ""; }
  72247. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72248. if (onProgress === void 0) { onProgress = null; }
  72249. if (pluginExtension === void 0) { pluginExtension = null; }
  72250. return new Promise(function (resolve, reject) {
  72251. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  72252. resolve(assetContainer);
  72253. }, onProgress, function (scene, message, exception) {
  72254. reject(exception || new Error(message));
  72255. }, pluginExtension);
  72256. });
  72257. };
  72258. // Flags
  72259. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  72260. SceneLoader._ShowLoadingScreen = true;
  72261. SceneLoader._CleanBoneMatrixWeights = false;
  72262. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  72263. // Members
  72264. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  72265. SceneLoader._registeredPlugins = {};
  72266. return SceneLoader;
  72267. }());
  72268. BABYLON.SceneLoader = SceneLoader;
  72269. ;
  72270. })(BABYLON || (BABYLON = {}));
  72271. //# sourceMappingURL=babylon.sceneLoader.js.map
  72272. var BABYLON;
  72273. (function (BABYLON) {
  72274. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  72275. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  72276. var parsedMaterial = parsedData.materials[index];
  72277. if (parsedMaterial.id === id) {
  72278. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  72279. }
  72280. }
  72281. return null;
  72282. };
  72283. var isDescendantOf = function (mesh, names, hierarchyIds) {
  72284. for (var i in names) {
  72285. if (mesh.name === names[i]) {
  72286. hierarchyIds.push(mesh.id);
  72287. return true;
  72288. }
  72289. }
  72290. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  72291. hierarchyIds.push(mesh.id);
  72292. return true;
  72293. }
  72294. return false;
  72295. };
  72296. var logOperation = function (operation, producer) {
  72297. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  72298. };
  72299. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  72300. if (addToScene === void 0) { addToScene = false; }
  72301. var container = new BABYLON.AssetContainer(scene);
  72302. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72303. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72304. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72305. // and avoid problems with multiple concurrent .babylon loads.
  72306. var log = "importScene has failed JSON parse";
  72307. try {
  72308. var parsedData = JSON.parse(data);
  72309. log = "";
  72310. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  72311. var index;
  72312. var cache;
  72313. // Lights
  72314. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  72315. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  72316. var parsedLight = parsedData.lights[index];
  72317. var light = BABYLON.Light.Parse(parsedLight, scene);
  72318. if (light) {
  72319. container.lights.push(light);
  72320. log += (index === 0 ? "\n\tLights:" : "");
  72321. log += "\n\t\t" + light.toString(fullDetails);
  72322. }
  72323. }
  72324. }
  72325. // Animations
  72326. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  72327. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  72328. var parsedAnimation = parsedData.animations[index];
  72329. var animation = BABYLON.Animation.Parse(parsedAnimation);
  72330. scene.animations.push(animation);
  72331. container.animations.push(animation);
  72332. log += (index === 0 ? "\n\tAnimations:" : "");
  72333. log += "\n\t\t" + animation.toString(fullDetails);
  72334. }
  72335. }
  72336. // Materials
  72337. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  72338. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  72339. var parsedMaterial = parsedData.materials[index];
  72340. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  72341. container.materials.push(mat);
  72342. log += (index === 0 ? "\n\tMaterials:" : "");
  72343. log += "\n\t\t" + mat.toString(fullDetails);
  72344. }
  72345. }
  72346. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  72347. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  72348. var parsedMultiMaterial = parsedData.multiMaterials[index];
  72349. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  72350. container.multiMaterials.push(mmat);
  72351. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  72352. log += "\n\t\t" + mmat.toString(fullDetails);
  72353. }
  72354. }
  72355. // Morph targets
  72356. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  72357. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  72358. var managerData = _a[_i];
  72359. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  72360. }
  72361. }
  72362. // Skeletons
  72363. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  72364. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  72365. var parsedSkeleton = parsedData.skeletons[index];
  72366. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  72367. container.skeletons.push(skeleton);
  72368. log += (index === 0 ? "\n\tSkeletons:" : "");
  72369. log += "\n\t\t" + skeleton.toString(fullDetails);
  72370. }
  72371. }
  72372. // Geometries
  72373. var geometries = parsedData.geometries;
  72374. if (geometries !== undefined && geometries !== null) {
  72375. var addedGeometry = new Array();
  72376. // Boxes
  72377. var boxes = geometries.boxes;
  72378. if (boxes !== undefined && boxes !== null) {
  72379. for (index = 0, cache = boxes.length; index < cache; index++) {
  72380. var parsedBox = boxes[index];
  72381. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  72382. }
  72383. }
  72384. // Spheres
  72385. var spheres = geometries.spheres;
  72386. if (spheres !== undefined && spheres !== null) {
  72387. for (index = 0, cache = spheres.length; index < cache; index++) {
  72388. var parsedSphere = spheres[index];
  72389. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  72390. }
  72391. }
  72392. // Cylinders
  72393. var cylinders = geometries.cylinders;
  72394. if (cylinders !== undefined && cylinders !== null) {
  72395. for (index = 0, cache = cylinders.length; index < cache; index++) {
  72396. var parsedCylinder = cylinders[index];
  72397. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  72398. }
  72399. }
  72400. // Toruses
  72401. var toruses = geometries.toruses;
  72402. if (toruses !== undefined && toruses !== null) {
  72403. for (index = 0, cache = toruses.length; index < cache; index++) {
  72404. var parsedTorus = toruses[index];
  72405. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  72406. }
  72407. }
  72408. // Grounds
  72409. var grounds = geometries.grounds;
  72410. if (grounds !== undefined && grounds !== null) {
  72411. for (index = 0, cache = grounds.length; index < cache; index++) {
  72412. var parsedGround = grounds[index];
  72413. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  72414. }
  72415. }
  72416. // Planes
  72417. var planes = geometries.planes;
  72418. if (planes !== undefined && planes !== null) {
  72419. for (index = 0, cache = planes.length; index < cache; index++) {
  72420. var parsedPlane = planes[index];
  72421. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  72422. }
  72423. }
  72424. // TorusKnots
  72425. var torusKnots = geometries.torusKnots;
  72426. if (torusKnots !== undefined && torusKnots !== null) {
  72427. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  72428. var parsedTorusKnot = torusKnots[index];
  72429. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  72430. }
  72431. }
  72432. // VertexData
  72433. var vertexData = geometries.vertexData;
  72434. if (vertexData !== undefined && vertexData !== null) {
  72435. for (index = 0, cache = vertexData.length; index < cache; index++) {
  72436. var parsedVertexData = vertexData[index];
  72437. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  72438. }
  72439. }
  72440. addedGeometry.forEach(function (g) {
  72441. if (g) {
  72442. container.geometries.push(g);
  72443. }
  72444. });
  72445. }
  72446. // Transform nodes
  72447. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  72448. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  72449. var parsedTransformNode = parsedData.transformNodes[index];
  72450. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  72451. container.transformNodes.push(node);
  72452. }
  72453. }
  72454. // Meshes
  72455. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  72456. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  72457. var parsedMesh = parsedData.meshes[index];
  72458. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  72459. container.meshes.push(mesh);
  72460. log += (index === 0 ? "\n\tMeshes:" : "");
  72461. log += "\n\t\t" + mesh.toString(fullDetails);
  72462. }
  72463. }
  72464. // Cameras
  72465. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  72466. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  72467. var parsedCamera = parsedData.cameras[index];
  72468. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  72469. container.cameras.push(camera);
  72470. log += (index === 0 ? "\n\tCameras:" : "");
  72471. log += "\n\t\t" + camera.toString(fullDetails);
  72472. }
  72473. }
  72474. // Animation Groups
  72475. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  72476. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  72477. var parsedAnimationGroup = parsedData.animationGroups[index];
  72478. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  72479. container.animationGroups.push(animationGroup);
  72480. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  72481. log += "\n\t\t" + animationGroup.toString(fullDetails);
  72482. }
  72483. }
  72484. // Browsing all the graph to connect the dots
  72485. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  72486. var camera = scene.cameras[index];
  72487. if (camera._waitingParentId) {
  72488. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  72489. camera._waitingParentId = null;
  72490. }
  72491. }
  72492. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  72493. var light_1 = scene.lights[index];
  72494. if (light_1 && light_1._waitingParentId) {
  72495. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  72496. light_1._waitingParentId = null;
  72497. }
  72498. }
  72499. // Connect parents & children and parse actions
  72500. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  72501. var transformNode = scene.transformNodes[index];
  72502. if (transformNode._waitingParentId) {
  72503. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  72504. transformNode._waitingParentId = null;
  72505. }
  72506. }
  72507. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72508. var mesh = scene.meshes[index];
  72509. if (mesh._waitingParentId) {
  72510. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  72511. mesh._waitingParentId = null;
  72512. }
  72513. if (mesh._waitingActions) {
  72514. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  72515. mesh._waitingActions = null;
  72516. }
  72517. }
  72518. // freeze world matrix application
  72519. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72520. var currentMesh = scene.meshes[index];
  72521. if (currentMesh._waitingFreezeWorldMatrix) {
  72522. currentMesh.freezeWorldMatrix();
  72523. currentMesh._waitingFreezeWorldMatrix = null;
  72524. }
  72525. else {
  72526. currentMesh.computeWorldMatrix(true);
  72527. }
  72528. }
  72529. // Lights exclusions / inclusions
  72530. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  72531. var light_2 = scene.lights[index];
  72532. // Excluded check
  72533. if (light_2._excludedMeshesIds.length > 0) {
  72534. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  72535. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  72536. if (excludedMesh) {
  72537. light_2.excludedMeshes.push(excludedMesh);
  72538. }
  72539. }
  72540. light_2._excludedMeshesIds = [];
  72541. }
  72542. // Included check
  72543. if (light_2._includedOnlyMeshesIds.length > 0) {
  72544. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  72545. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  72546. if (includedOnlyMesh) {
  72547. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  72548. }
  72549. }
  72550. light_2._includedOnlyMeshesIds = [];
  72551. }
  72552. }
  72553. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  72554. // Actions (scene)
  72555. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  72556. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  72557. }
  72558. if (!addToScene) {
  72559. container.removeAllFromScene();
  72560. }
  72561. }
  72562. catch (err) {
  72563. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  72564. if (onError) {
  72565. onError(msg, err);
  72566. }
  72567. else {
  72568. BABYLON.Tools.Log(msg);
  72569. throw err;
  72570. }
  72571. }
  72572. finally {
  72573. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72574. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72575. }
  72576. }
  72577. return container;
  72578. };
  72579. BABYLON.SceneLoader.RegisterPlugin({
  72580. name: "babylon.js",
  72581. extensions: ".babylon",
  72582. canDirectLoad: function (data) {
  72583. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  72584. return true;
  72585. }
  72586. return false;
  72587. },
  72588. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  72589. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72590. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72591. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72592. // and avoid problems with multiple concurrent .babylon loads.
  72593. var log = "importMesh has failed JSON parse";
  72594. try {
  72595. var parsedData = JSON.parse(data);
  72596. log = "";
  72597. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  72598. if (!meshesNames) {
  72599. meshesNames = null;
  72600. }
  72601. else if (!Array.isArray(meshesNames)) {
  72602. meshesNames = [meshesNames];
  72603. }
  72604. var hierarchyIds = new Array();
  72605. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  72606. var loadedSkeletonsIds = [];
  72607. var loadedMaterialsIds = [];
  72608. var index;
  72609. var cache;
  72610. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  72611. var parsedMesh = parsedData.meshes[index];
  72612. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  72613. if (meshesNames !== null) {
  72614. // Remove found mesh name from list.
  72615. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  72616. }
  72617. //Geometry?
  72618. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  72619. //does the file contain geometries?
  72620. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  72621. //find the correct geometry and add it to the scene
  72622. var found = false;
  72623. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  72624. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  72625. return;
  72626. }
  72627. else {
  72628. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  72629. if (parsedGeometryData.id === parsedMesh.geometryId) {
  72630. switch (geometryType) {
  72631. case "boxes":
  72632. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  72633. break;
  72634. case "spheres":
  72635. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  72636. break;
  72637. case "cylinders":
  72638. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  72639. break;
  72640. case "toruses":
  72641. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  72642. break;
  72643. case "grounds":
  72644. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  72645. break;
  72646. case "planes":
  72647. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  72648. break;
  72649. case "torusKnots":
  72650. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  72651. break;
  72652. case "vertexData":
  72653. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  72654. break;
  72655. }
  72656. found = true;
  72657. }
  72658. });
  72659. }
  72660. });
  72661. if (found === false) {
  72662. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  72663. }
  72664. }
  72665. }
  72666. // Material ?
  72667. if (parsedMesh.materialId) {
  72668. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  72669. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  72670. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  72671. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  72672. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  72673. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  72674. var subMatId = parsedMultiMaterial.materials[matIndex];
  72675. loadedMaterialsIds.push(subMatId);
  72676. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  72677. if (mat) {
  72678. log += "\n\tMaterial " + mat.toString(fullDetails);
  72679. }
  72680. }
  72681. loadedMaterialsIds.push(parsedMultiMaterial.id);
  72682. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  72683. if (mmat) {
  72684. materialFound = true;
  72685. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  72686. }
  72687. break;
  72688. }
  72689. }
  72690. }
  72691. if (materialFound === false) {
  72692. loadedMaterialsIds.push(parsedMesh.materialId);
  72693. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  72694. if (!mat) {
  72695. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  72696. }
  72697. else {
  72698. log += "\n\tMaterial " + mat.toString(fullDetails);
  72699. }
  72700. }
  72701. }
  72702. // Skeleton ?
  72703. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  72704. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  72705. if (skeletonAlreadyLoaded === false) {
  72706. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  72707. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  72708. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  72709. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  72710. skeletons.push(skeleton);
  72711. loadedSkeletonsIds.push(parsedSkeleton.id);
  72712. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  72713. }
  72714. }
  72715. }
  72716. }
  72717. // Morph targets ?
  72718. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  72719. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  72720. var managerData = _a[_i];
  72721. BABYLON.MorphTargetManager.Parse(managerData, scene);
  72722. }
  72723. }
  72724. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  72725. meshes.push(mesh);
  72726. log += "\n\tMesh " + mesh.toString(fullDetails);
  72727. }
  72728. }
  72729. // Connecting parents
  72730. var currentMesh;
  72731. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72732. currentMesh = scene.meshes[index];
  72733. if (currentMesh._waitingParentId) {
  72734. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  72735. currentMesh._waitingParentId = null;
  72736. }
  72737. }
  72738. // freeze and compute world matrix application
  72739. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72740. currentMesh = scene.meshes[index];
  72741. if (currentMesh._waitingFreezeWorldMatrix) {
  72742. currentMesh.freezeWorldMatrix();
  72743. currentMesh._waitingFreezeWorldMatrix = null;
  72744. }
  72745. else {
  72746. currentMesh.computeWorldMatrix(true);
  72747. }
  72748. }
  72749. }
  72750. // Particles
  72751. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  72752. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  72753. if (parser) {
  72754. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  72755. var parsedParticleSystem = parsedData.particleSystems[index];
  72756. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  72757. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  72758. }
  72759. }
  72760. }
  72761. }
  72762. return true;
  72763. }
  72764. catch (err) {
  72765. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  72766. if (onError) {
  72767. onError(msg, err);
  72768. }
  72769. else {
  72770. BABYLON.Tools.Log(msg);
  72771. throw err;
  72772. }
  72773. }
  72774. finally {
  72775. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72776. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72777. }
  72778. }
  72779. return false;
  72780. },
  72781. load: function (scene, data, rootUrl, onError) {
  72782. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72783. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72784. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72785. // and avoid problems with multiple concurrent .babylon loads.
  72786. var log = "importScene has failed JSON parse";
  72787. try {
  72788. var parsedData = JSON.parse(data);
  72789. log = "";
  72790. // Scene
  72791. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  72792. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  72793. }
  72794. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  72795. scene.autoClear = parsedData.autoClear;
  72796. }
  72797. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  72798. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  72799. }
  72800. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  72801. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  72802. }
  72803. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  72804. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  72805. }
  72806. // Fog
  72807. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  72808. scene.fogMode = parsedData.fogMode;
  72809. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  72810. scene.fogStart = parsedData.fogStart;
  72811. scene.fogEnd = parsedData.fogEnd;
  72812. scene.fogDensity = parsedData.fogDensity;
  72813. log += "\tFog mode for scene: ";
  72814. switch (scene.fogMode) {
  72815. // getters not compiling, so using hardcoded
  72816. case 1:
  72817. log += "exp\n";
  72818. break;
  72819. case 2:
  72820. log += "exp2\n";
  72821. break;
  72822. case 3:
  72823. log += "linear\n";
  72824. break;
  72825. }
  72826. }
  72827. //Physics
  72828. if (parsedData.physicsEnabled) {
  72829. var physicsPlugin;
  72830. if (parsedData.physicsEngine === "cannon") {
  72831. physicsPlugin = new BABYLON.CannonJSPlugin();
  72832. }
  72833. else if (parsedData.physicsEngine === "oimo") {
  72834. physicsPlugin = new BABYLON.OimoJSPlugin();
  72835. }
  72836. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  72837. //else - default engine, which is currently oimo
  72838. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  72839. scene.enablePhysics(physicsGravity, physicsPlugin);
  72840. }
  72841. // Metadata
  72842. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  72843. scene.metadata = parsedData.metadata;
  72844. }
  72845. //collisions, if defined. otherwise, default is true
  72846. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  72847. scene.collisionsEnabled = parsedData.collisionsEnabled;
  72848. }
  72849. scene.workerCollisions = !!parsedData.workerCollisions;
  72850. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  72851. if (!container) {
  72852. return false;
  72853. }
  72854. if (parsedData.autoAnimate) {
  72855. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  72856. }
  72857. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  72858. scene.setActiveCameraByID(parsedData.activeCameraID);
  72859. }
  72860. // Environment texture
  72861. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  72862. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  72863. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  72864. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  72865. if (parsedData.environmentTextureRotationY) {
  72866. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  72867. }
  72868. scene.environmentTexture = hdrTexture;
  72869. }
  72870. else {
  72871. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  72872. if (parsedData.environmentTextureRotationY) {
  72873. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  72874. }
  72875. scene.environmentTexture = cubeTexture;
  72876. }
  72877. if (parsedData.createDefaultSkybox === true) {
  72878. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  72879. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  72880. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  72881. }
  72882. }
  72883. // Finish
  72884. return true;
  72885. }
  72886. catch (err) {
  72887. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  72888. if (onError) {
  72889. onError(msg, err);
  72890. }
  72891. else {
  72892. BABYLON.Tools.Log(msg);
  72893. throw err;
  72894. }
  72895. }
  72896. finally {
  72897. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72898. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72899. }
  72900. }
  72901. return false;
  72902. },
  72903. loadAssetContainer: function (scene, data, rootUrl, onError) {
  72904. var container = loadAssetContainer(scene, data, rootUrl, onError);
  72905. return container;
  72906. }
  72907. });
  72908. })(BABYLON || (BABYLON = {}));
  72909. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  72910. var BABYLON;
  72911. (function (BABYLON) {
  72912. var FilesInput = /** @class */ (function () {
  72913. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  72914. this.onProcessFileCallback = function () { return true; };
  72915. this._engine = engine;
  72916. this._currentScene = scene;
  72917. this._sceneLoadedCallback = sceneLoadedCallback;
  72918. this._progressCallback = progressCallback;
  72919. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  72920. this._textureLoadingCallback = textureLoadingCallback;
  72921. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  72922. this._onReloadCallback = onReloadCallback;
  72923. this._errorCallback = errorCallback;
  72924. }
  72925. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  72926. var _this = this;
  72927. if (elementToMonitor) {
  72928. this._elementToMonitor = elementToMonitor;
  72929. this._dragEnterHandler = function (e) { _this.drag(e); };
  72930. this._dragOverHandler = function (e) { _this.drag(e); };
  72931. this._dropHandler = function (e) { _this.drop(e); };
  72932. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  72933. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  72934. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  72935. }
  72936. };
  72937. FilesInput.prototype.dispose = function () {
  72938. if (!this._elementToMonitor) {
  72939. return;
  72940. }
  72941. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  72942. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  72943. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  72944. };
  72945. FilesInput.prototype.renderFunction = function () {
  72946. if (this._additionalRenderLoopLogicCallback) {
  72947. this._additionalRenderLoopLogicCallback();
  72948. }
  72949. if (this._currentScene) {
  72950. if (this._textureLoadingCallback) {
  72951. var remaining = this._currentScene.getWaitingItemsCount();
  72952. if (remaining > 0) {
  72953. this._textureLoadingCallback(remaining);
  72954. }
  72955. }
  72956. this._currentScene.render();
  72957. }
  72958. };
  72959. FilesInput.prototype.drag = function (e) {
  72960. e.stopPropagation();
  72961. e.preventDefault();
  72962. };
  72963. FilesInput.prototype.drop = function (eventDrop) {
  72964. eventDrop.stopPropagation();
  72965. eventDrop.preventDefault();
  72966. this.loadFiles(eventDrop);
  72967. };
  72968. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  72969. var _this = this;
  72970. var reader = folder.createReader();
  72971. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  72972. reader.readEntries(function (entries) {
  72973. remaining.count += entries.length;
  72974. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  72975. var entry = entries_1[_i];
  72976. if (entry.isFile) {
  72977. entry.file(function (file) {
  72978. file.correctName = relativePath + file.name;
  72979. files.push(file);
  72980. if (--remaining.count === 0) {
  72981. callback();
  72982. }
  72983. });
  72984. }
  72985. else if (entry.isDirectory) {
  72986. _this._traverseFolder(entry, files, remaining, callback);
  72987. }
  72988. }
  72989. if (--remaining.count) {
  72990. callback();
  72991. }
  72992. });
  72993. };
  72994. FilesInput.prototype._processFiles = function (files) {
  72995. for (var i = 0; i < files.length; i++) {
  72996. var name = files[i].correctName.toLowerCase();
  72997. var extension = name.split('.').pop();
  72998. if (!this.onProcessFileCallback(files[i], name, extension)) {
  72999. continue;
  73000. }
  73001. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  73002. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  73003. this._sceneFileToLoad = files[i];
  73004. }
  73005. FilesInput.FilesToLoad[name] = files[i];
  73006. }
  73007. };
  73008. FilesInput.prototype.loadFiles = function (event) {
  73009. var _this = this;
  73010. // Handling data transfer via drag'n'drop
  73011. if (event && event.dataTransfer && event.dataTransfer.files) {
  73012. this._filesToLoad = event.dataTransfer.files;
  73013. }
  73014. // Handling files from input files
  73015. if (event && event.target && event.target.files) {
  73016. this._filesToLoad = event.target.files;
  73017. }
  73018. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  73019. return;
  73020. }
  73021. if (this._startingProcessingFilesCallback) {
  73022. this._startingProcessingFilesCallback(this._filesToLoad);
  73023. }
  73024. if (this._filesToLoad && this._filesToLoad.length > 0) {
  73025. var files_1 = new Array();
  73026. var folders = [];
  73027. var items = event.dataTransfer ? event.dataTransfer.items : null;
  73028. for (var i = 0; i < this._filesToLoad.length; i++) {
  73029. var fileToLoad = this._filesToLoad[i];
  73030. var name_1 = fileToLoad.name.toLowerCase();
  73031. var entry = void 0;
  73032. fileToLoad.correctName = name_1;
  73033. if (items) {
  73034. var item = items[i];
  73035. if (item.getAsEntry) {
  73036. entry = item.getAsEntry();
  73037. }
  73038. else if (item.webkitGetAsEntry) {
  73039. entry = item.webkitGetAsEntry();
  73040. }
  73041. }
  73042. if (!entry) {
  73043. files_1.push(fileToLoad);
  73044. }
  73045. else {
  73046. if (entry.isDirectory) {
  73047. folders.push(entry);
  73048. }
  73049. else {
  73050. files_1.push(fileToLoad);
  73051. }
  73052. }
  73053. }
  73054. if (folders.length === 0) {
  73055. this._processFiles(files_1);
  73056. this._processReload();
  73057. }
  73058. else {
  73059. var remaining = { count: folders.length };
  73060. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  73061. var folder = folders_1[_i];
  73062. this._traverseFolder(folder, files_1, remaining, function () {
  73063. _this._processFiles(files_1);
  73064. if (remaining.count === 0) {
  73065. _this._processReload();
  73066. }
  73067. });
  73068. }
  73069. }
  73070. }
  73071. };
  73072. FilesInput.prototype._processReload = function () {
  73073. if (this._onReloadCallback) {
  73074. this._onReloadCallback(this._sceneFileToLoad);
  73075. }
  73076. else {
  73077. this.reload();
  73078. }
  73079. };
  73080. FilesInput.prototype.reload = function () {
  73081. var _this = this;
  73082. // If a scene file has been provided
  73083. if (this._sceneFileToLoad) {
  73084. if (this._currentScene) {
  73085. if (BABYLON.Tools.errorsCount > 0) {
  73086. BABYLON.Tools.ClearLogCache();
  73087. }
  73088. this._engine.stopRenderLoop();
  73089. }
  73090. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  73091. if (_this._progressCallback) {
  73092. _this._progressCallback(progress);
  73093. }
  73094. }).then(function (scene) {
  73095. if (_this._currentScene) {
  73096. _this._currentScene.dispose();
  73097. }
  73098. _this._currentScene = scene;
  73099. if (_this._sceneLoadedCallback) {
  73100. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  73101. }
  73102. // Wait for textures and shaders to be ready
  73103. _this._currentScene.executeWhenReady(function () {
  73104. _this._engine.runRenderLoop(function () {
  73105. _this.renderFunction();
  73106. });
  73107. });
  73108. }).catch(function (error) {
  73109. if (_this._errorCallback) {
  73110. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  73111. }
  73112. });
  73113. }
  73114. else {
  73115. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  73116. }
  73117. };
  73118. FilesInput.FilesToLoad = {};
  73119. return FilesInput;
  73120. }());
  73121. BABYLON.FilesInput = FilesInput;
  73122. })(BABYLON || (BABYLON = {}));
  73123. //# sourceMappingURL=babylon.filesInput.js.map
  73124. var BABYLON;
  73125. (function (BABYLON) {
  73126. var Tags = /** @class */ (function () {
  73127. function Tags() {
  73128. }
  73129. Tags.EnableFor = function (obj) {
  73130. obj._tags = obj._tags || {};
  73131. obj.hasTags = function () {
  73132. return Tags.HasTags(obj);
  73133. };
  73134. obj.addTags = function (tagsString) {
  73135. return Tags.AddTagsTo(obj, tagsString);
  73136. };
  73137. obj.removeTags = function (tagsString) {
  73138. return Tags.RemoveTagsFrom(obj, tagsString);
  73139. };
  73140. obj.matchesTagsQuery = function (tagsQuery) {
  73141. return Tags.MatchesQuery(obj, tagsQuery);
  73142. };
  73143. };
  73144. Tags.DisableFor = function (obj) {
  73145. delete obj._tags;
  73146. delete obj.hasTags;
  73147. delete obj.addTags;
  73148. delete obj.removeTags;
  73149. delete obj.matchesTagsQuery;
  73150. };
  73151. Tags.HasTags = function (obj) {
  73152. if (!obj._tags) {
  73153. return false;
  73154. }
  73155. return !BABYLON.Tools.IsEmpty(obj._tags);
  73156. };
  73157. Tags.GetTags = function (obj, asString) {
  73158. if (asString === void 0) { asString = true; }
  73159. if (!obj._tags) {
  73160. return null;
  73161. }
  73162. if (asString) {
  73163. var tagsArray = [];
  73164. for (var tag in obj._tags) {
  73165. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  73166. tagsArray.push(tag);
  73167. }
  73168. }
  73169. return tagsArray.join(" ");
  73170. }
  73171. else {
  73172. return obj._tags;
  73173. }
  73174. };
  73175. // the tags 'true' and 'false' are reserved and cannot be used as tags
  73176. // a tag cannot start with '||', '&&', and '!'
  73177. // it cannot contain whitespaces
  73178. Tags.AddTagsTo = function (obj, tagsString) {
  73179. if (!tagsString) {
  73180. return;
  73181. }
  73182. if (typeof tagsString !== "string") {
  73183. return;
  73184. }
  73185. var tags = tagsString.split(" ");
  73186. tags.forEach(function (tag, index, array) {
  73187. Tags._AddTagTo(obj, tag);
  73188. });
  73189. };
  73190. Tags._AddTagTo = function (obj, tag) {
  73191. tag = tag.trim();
  73192. if (tag === "" || tag === "true" || tag === "false") {
  73193. return;
  73194. }
  73195. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  73196. return;
  73197. }
  73198. Tags.EnableFor(obj);
  73199. obj._tags[tag] = true;
  73200. };
  73201. Tags.RemoveTagsFrom = function (obj, tagsString) {
  73202. if (!Tags.HasTags(obj)) {
  73203. return;
  73204. }
  73205. var tags = tagsString.split(" ");
  73206. for (var t in tags) {
  73207. Tags._RemoveTagFrom(obj, tags[t]);
  73208. }
  73209. };
  73210. Tags._RemoveTagFrom = function (obj, tag) {
  73211. delete obj._tags[tag];
  73212. };
  73213. Tags.MatchesQuery = function (obj, tagsQuery) {
  73214. if (tagsQuery === undefined) {
  73215. return true;
  73216. }
  73217. if (tagsQuery === "") {
  73218. return Tags.HasTags(obj);
  73219. }
  73220. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  73221. };
  73222. return Tags;
  73223. }());
  73224. BABYLON.Tags = Tags;
  73225. })(BABYLON || (BABYLON = {}));
  73226. //# sourceMappingURL=babylon.tags.js.map
  73227. var BABYLON;
  73228. (function (BABYLON) {
  73229. /**
  73230. * Class used to evalaute queries containing `and` and `or` operators
  73231. */
  73232. var AndOrNotEvaluator = /** @class */ (function () {
  73233. function AndOrNotEvaluator() {
  73234. }
  73235. /**
  73236. * Evaluate a query
  73237. * @param query defines the query to evaluate
  73238. * @param evaluateCallback defines the callback used to filter result
  73239. * @returns true if the query matches
  73240. */
  73241. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  73242. if (!query.match(/\([^\(\)]*\)/g)) {
  73243. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  73244. }
  73245. else {
  73246. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  73247. // remove parenthesis
  73248. r = r.slice(1, r.length - 1);
  73249. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  73250. });
  73251. }
  73252. if (query === "true") {
  73253. return true;
  73254. }
  73255. if (query === "false") {
  73256. return false;
  73257. }
  73258. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  73259. };
  73260. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  73261. evaluateCallback = evaluateCallback || (function (r) {
  73262. return r === "true" ? true : false;
  73263. });
  73264. var result;
  73265. var or = parenthesisContent.split("||");
  73266. for (var i in or) {
  73267. if (or.hasOwnProperty(i)) {
  73268. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  73269. var and = ori.split("&&");
  73270. if (and.length > 1) {
  73271. for (var j = 0; j < and.length; ++j) {
  73272. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  73273. if (andj !== "true" && andj !== "false") {
  73274. if (andj[0] === "!") {
  73275. result = !evaluateCallback(andj.substring(1));
  73276. }
  73277. else {
  73278. result = evaluateCallback(andj);
  73279. }
  73280. }
  73281. else {
  73282. result = andj === "true" ? true : false;
  73283. }
  73284. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  73285. ori = "false";
  73286. break;
  73287. }
  73288. }
  73289. }
  73290. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  73291. result = true;
  73292. break;
  73293. }
  73294. // result equals false (or undefined)
  73295. if (ori !== "true" && ori !== "false") {
  73296. if (ori[0] === "!") {
  73297. result = !evaluateCallback(ori.substring(1));
  73298. }
  73299. else {
  73300. result = evaluateCallback(ori);
  73301. }
  73302. }
  73303. else {
  73304. result = ori === "true" ? true : false;
  73305. }
  73306. }
  73307. }
  73308. // the whole parenthesis scope is replaced by 'true' or 'false'
  73309. return result ? "true" : "false";
  73310. };
  73311. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  73312. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  73313. // remove whitespaces
  73314. r = r.replace(/[\s]/g, function () { return ""; });
  73315. return r.length % 2 ? "!" : "";
  73316. });
  73317. booleanString = booleanString.trim();
  73318. if (booleanString === "!true") {
  73319. booleanString = "false";
  73320. }
  73321. else if (booleanString === "!false") {
  73322. booleanString = "true";
  73323. }
  73324. return booleanString;
  73325. };
  73326. return AndOrNotEvaluator;
  73327. }());
  73328. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  73329. })(BABYLON || (BABYLON = {}));
  73330. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  73331. var BABYLON;
  73332. (function (BABYLON) {
  73333. /**
  73334. * Class used to enable access to IndexedDB
  73335. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  73336. */
  73337. var Database = /** @class */ (function () {
  73338. /**
  73339. * Creates a new Database
  73340. * @param urlToScene defines the url to load the scene
  73341. * @param callbackManifestChecked defines the callback to use when manifest is checked
  73342. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  73343. */
  73344. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  73345. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  73346. var _this = this;
  73347. // Handling various flavors of prefixed version of IndexedDB
  73348. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  73349. this.callbackManifestChecked = callbackManifestChecked;
  73350. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  73351. this.db = null;
  73352. this._enableSceneOffline = false;
  73353. this._enableTexturesOffline = false;
  73354. this.manifestVersionFound = 0;
  73355. this.mustUpdateRessources = false;
  73356. this.hasReachedQuota = false;
  73357. if (!Database.IDBStorageEnabled) {
  73358. this.callbackManifestChecked(true);
  73359. }
  73360. else {
  73361. if (disableManifestCheck) {
  73362. this._enableSceneOffline = true;
  73363. this._enableTexturesOffline = true;
  73364. this.manifestVersionFound = 1;
  73365. BABYLON.Tools.SetImmediate(function () {
  73366. _this.callbackManifestChecked(true);
  73367. });
  73368. }
  73369. else {
  73370. this._checkManifestFile();
  73371. }
  73372. }
  73373. }
  73374. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  73375. /**
  73376. * Gets a boolean indicating if scene must be saved in the database
  73377. */
  73378. get: function () {
  73379. return this._enableSceneOffline;
  73380. },
  73381. enumerable: true,
  73382. configurable: true
  73383. });
  73384. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  73385. /**
  73386. * Gets a boolean indicating if textures must be saved in the database
  73387. */
  73388. get: function () {
  73389. return this._enableTexturesOffline;
  73390. },
  73391. enumerable: true,
  73392. configurable: true
  73393. });
  73394. Database.prototype._checkManifestFile = function () {
  73395. var _this = this;
  73396. var noManifestFile = function () {
  73397. _this._enableSceneOffline = false;
  73398. _this._enableTexturesOffline = false;
  73399. _this.callbackManifestChecked(false);
  73400. };
  73401. var timeStampUsed = false;
  73402. var manifestURL = this.currentSceneUrl + ".manifest";
  73403. var xhr = new XMLHttpRequest();
  73404. if (navigator.onLine) {
  73405. // Adding a timestamp to by-pass browsers' cache
  73406. timeStampUsed = true;
  73407. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  73408. }
  73409. xhr.open("GET", manifestURL, true);
  73410. xhr.addEventListener("load", function () {
  73411. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  73412. try {
  73413. var manifestFile = JSON.parse(xhr.response);
  73414. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  73415. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  73416. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  73417. _this.manifestVersionFound = manifestFile.version;
  73418. }
  73419. if (_this.callbackManifestChecked) {
  73420. _this.callbackManifestChecked(true);
  73421. }
  73422. }
  73423. catch (ex) {
  73424. noManifestFile();
  73425. }
  73426. }
  73427. else {
  73428. noManifestFile();
  73429. }
  73430. }, false);
  73431. xhr.addEventListener("error", function (event) {
  73432. if (timeStampUsed) {
  73433. timeStampUsed = false;
  73434. // Let's retry without the timeStamp
  73435. // It could fail when coupled with HTML5 Offline API
  73436. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  73437. xhr.open("GET", retryManifestURL, true);
  73438. xhr.send();
  73439. }
  73440. else {
  73441. noManifestFile();
  73442. }
  73443. }, false);
  73444. try {
  73445. xhr.send();
  73446. }
  73447. catch (ex) {
  73448. BABYLON.Tools.Error("Error on XHR send request.");
  73449. this.callbackManifestChecked(false);
  73450. }
  73451. };
  73452. /**
  73453. * Open the database and make it available
  73454. * @param successCallback defines the callback to call on success
  73455. * @param errorCallback defines the callback to call on error
  73456. */
  73457. Database.prototype.openAsync = function (successCallback, errorCallback) {
  73458. var _this = this;
  73459. var handleError = function () {
  73460. _this.isSupported = false;
  73461. if (errorCallback)
  73462. errorCallback();
  73463. };
  73464. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  73465. // Your browser doesn't support IndexedDB
  73466. this.isSupported = false;
  73467. if (errorCallback)
  73468. errorCallback();
  73469. }
  73470. else {
  73471. // If the DB hasn't been opened or created yet
  73472. if (!this.db) {
  73473. this.hasReachedQuota = false;
  73474. this.isSupported = true;
  73475. var request = this.idbFactory.open("babylonjs", 1);
  73476. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  73477. request.onerror = function (event) {
  73478. handleError();
  73479. };
  73480. // executes when a version change transaction cannot complete due to other active transactions
  73481. request.onblocked = function (event) {
  73482. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  73483. handleError();
  73484. };
  73485. // DB has been opened successfully
  73486. request.onsuccess = function (event) {
  73487. _this.db = request.result;
  73488. successCallback();
  73489. };
  73490. // Initialization of the DB. Creating Scenes & Textures stores
  73491. request.onupgradeneeded = function (event) {
  73492. _this.db = (event.target).result;
  73493. if (_this.db) {
  73494. try {
  73495. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  73496. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  73497. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  73498. }
  73499. catch (ex) {
  73500. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  73501. handleError();
  73502. }
  73503. }
  73504. };
  73505. }
  73506. // DB has already been created and opened
  73507. else {
  73508. if (successCallback)
  73509. successCallback();
  73510. }
  73511. }
  73512. };
  73513. /**
  73514. * Loads an image from the database
  73515. * @param url defines the url to load from
  73516. * @param image defines the target DOM image
  73517. */
  73518. Database.prototype.loadImageFromDB = function (url, image) {
  73519. var _this = this;
  73520. var completeURL = Database._ReturnFullUrlLocation(url);
  73521. var saveAndLoadImage = function () {
  73522. if (!_this.hasReachedQuota && _this.db !== null) {
  73523. // the texture is not yet in the DB, let's try to save it
  73524. _this._saveImageIntoDBAsync(completeURL, image);
  73525. }
  73526. // If the texture is not in the DB and we've reached the DB quota limit
  73527. // let's load it directly from the web
  73528. else {
  73529. image.src = url;
  73530. }
  73531. };
  73532. if (!this.mustUpdateRessources) {
  73533. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  73534. }
  73535. // First time we're download the images or update requested in the manifest file by a version change
  73536. else {
  73537. saveAndLoadImage();
  73538. }
  73539. };
  73540. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  73541. if (this.isSupported && this.db !== null) {
  73542. var texture;
  73543. var transaction = this.db.transaction(["textures"]);
  73544. transaction.onabort = function (event) {
  73545. image.src = url;
  73546. };
  73547. transaction.oncomplete = function (event) {
  73548. var blobTextureURL;
  73549. if (texture) {
  73550. var URL = window.URL || window.webkitURL;
  73551. blobTextureURL = URL.createObjectURL(texture.data);
  73552. image.onerror = function () {
  73553. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  73554. image.src = url;
  73555. };
  73556. image.src = blobTextureURL;
  73557. }
  73558. else {
  73559. notInDBCallback();
  73560. }
  73561. };
  73562. var getRequest = transaction.objectStore("textures").get(url);
  73563. getRequest.onsuccess = function (event) {
  73564. texture = (event.target).result;
  73565. };
  73566. getRequest.onerror = function (event) {
  73567. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  73568. image.src = url;
  73569. };
  73570. }
  73571. else {
  73572. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73573. image.src = url;
  73574. }
  73575. };
  73576. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  73577. var _this = this;
  73578. if (this.isSupported) {
  73579. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  73580. var generateBlobUrl = function () {
  73581. var blobTextureURL;
  73582. if (blob) {
  73583. var URL = window.URL || window.webkitURL;
  73584. try {
  73585. blobTextureURL = URL.createObjectURL(blob);
  73586. }
  73587. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  73588. catch (ex) {
  73589. blobTextureURL = URL.createObjectURL(blob);
  73590. }
  73591. }
  73592. if (blobTextureURL) {
  73593. image.src = blobTextureURL;
  73594. }
  73595. };
  73596. if (Database.IsUASupportingBlobStorage) { // Create XHR
  73597. var xhr = new XMLHttpRequest(), blob;
  73598. xhr.open("GET", url, true);
  73599. xhr.responseType = "blob";
  73600. xhr.addEventListener("load", function () {
  73601. if (xhr.status === 200 && _this.db) {
  73602. // Blob as response (XHR2)
  73603. blob = xhr.response;
  73604. var transaction = _this.db.transaction(["textures"], "readwrite");
  73605. // the transaction could abort because of a QuotaExceededError error
  73606. transaction.onabort = function (event) {
  73607. try {
  73608. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73609. var srcElement = (event.srcElement || event.target);
  73610. var error = srcElement.error;
  73611. if (error && error.name === "QuotaExceededError") {
  73612. _this.hasReachedQuota = true;
  73613. }
  73614. }
  73615. catch (ex) { }
  73616. generateBlobUrl();
  73617. };
  73618. transaction.oncomplete = function (event) {
  73619. generateBlobUrl();
  73620. };
  73621. var newTexture = { textureUrl: url, data: blob };
  73622. try {
  73623. // Put the blob into the dabase
  73624. var addRequest = transaction.objectStore("textures").put(newTexture);
  73625. addRequest.onsuccess = function (event) {
  73626. };
  73627. addRequest.onerror = function (event) {
  73628. generateBlobUrl();
  73629. };
  73630. }
  73631. catch (ex) {
  73632. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  73633. if (ex.code === 25) {
  73634. Database.IsUASupportingBlobStorage = false;
  73635. }
  73636. image.src = url;
  73637. }
  73638. }
  73639. else {
  73640. image.src = url;
  73641. }
  73642. }, false);
  73643. xhr.addEventListener("error", function (event) {
  73644. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  73645. image.src = url;
  73646. }, false);
  73647. xhr.send();
  73648. }
  73649. else {
  73650. image.src = url;
  73651. }
  73652. }
  73653. else {
  73654. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73655. image.src = url;
  73656. }
  73657. };
  73658. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  73659. var _this = this;
  73660. var updateVersion = function () {
  73661. // the version is not yet in the DB or we need to update it
  73662. _this._saveVersionIntoDBAsync(url, versionLoaded);
  73663. };
  73664. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  73665. };
  73666. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  73667. var _this = this;
  73668. if (this.isSupported && this.db) {
  73669. var version;
  73670. try {
  73671. var transaction = this.db.transaction(["versions"]);
  73672. transaction.oncomplete = function (event) {
  73673. if (version) {
  73674. // If the version in the JSON file is different from the version in DB
  73675. if (_this.manifestVersionFound !== version.data) {
  73676. _this.mustUpdateRessources = true;
  73677. updateInDBCallback();
  73678. }
  73679. else {
  73680. callback(version.data);
  73681. }
  73682. }
  73683. // version was not found in DB
  73684. else {
  73685. _this.mustUpdateRessources = true;
  73686. updateInDBCallback();
  73687. }
  73688. };
  73689. transaction.onabort = function (event) {
  73690. callback(-1);
  73691. };
  73692. var getRequest = transaction.objectStore("versions").get(url);
  73693. getRequest.onsuccess = function (event) {
  73694. version = (event.target).result;
  73695. };
  73696. getRequest.onerror = function (event) {
  73697. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  73698. callback(-1);
  73699. };
  73700. }
  73701. catch (ex) {
  73702. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  73703. callback(-1);
  73704. }
  73705. }
  73706. else {
  73707. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73708. callback(-1);
  73709. }
  73710. };
  73711. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  73712. var _this = this;
  73713. if (this.isSupported && !this.hasReachedQuota && this.db) {
  73714. try {
  73715. // Open a transaction to the database
  73716. var transaction = this.db.transaction(["versions"], "readwrite");
  73717. // the transaction could abort because of a QuotaExceededError error
  73718. transaction.onabort = function (event) {
  73719. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73720. var error = event.srcElement['error'];
  73721. if (error && error.name === "QuotaExceededError") {
  73722. _this.hasReachedQuota = true;
  73723. }
  73724. }
  73725. catch (ex) { }
  73726. callback(-1);
  73727. };
  73728. transaction.oncomplete = function (event) {
  73729. callback(_this.manifestVersionFound);
  73730. };
  73731. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  73732. // Put the scene into the database
  73733. var addRequest = transaction.objectStore("versions").put(newVersion);
  73734. addRequest.onsuccess = function (event) {
  73735. };
  73736. addRequest.onerror = function (event) {
  73737. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  73738. };
  73739. }
  73740. catch (ex) {
  73741. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  73742. callback(-1);
  73743. }
  73744. }
  73745. else {
  73746. callback(-1);
  73747. }
  73748. };
  73749. /**
  73750. * Loads a file from database
  73751. * @param url defines the URL to load from
  73752. * @param sceneLoaded defines a callback to call on success
  73753. * @param progressCallBack defines a callback to call when progress changed
  73754. * @param errorCallback defines a callback to call on error
  73755. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  73756. */
  73757. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  73758. var _this = this;
  73759. var completeUrl = Database._ReturnFullUrlLocation(url);
  73760. var saveAndLoadFile = function () {
  73761. // the scene is not yet in the DB, let's try to save it
  73762. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  73763. };
  73764. this._checkVersionFromDB(completeUrl, function (version) {
  73765. if (version !== -1) {
  73766. if (!_this.mustUpdateRessources) {
  73767. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  73768. }
  73769. else {
  73770. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  73771. }
  73772. }
  73773. else {
  73774. if (errorCallback) {
  73775. errorCallback();
  73776. }
  73777. }
  73778. });
  73779. };
  73780. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  73781. if (this.isSupported && this.db) {
  73782. var targetStore;
  73783. if (url.indexOf(".babylon") !== -1) {
  73784. targetStore = "scenes";
  73785. }
  73786. else {
  73787. targetStore = "textures";
  73788. }
  73789. var file;
  73790. var transaction = this.db.transaction([targetStore]);
  73791. transaction.oncomplete = function (event) {
  73792. if (file) {
  73793. callback(file.data);
  73794. }
  73795. // file was not found in DB
  73796. else {
  73797. notInDBCallback();
  73798. }
  73799. };
  73800. transaction.onabort = function (event) {
  73801. notInDBCallback();
  73802. };
  73803. var getRequest = transaction.objectStore(targetStore).get(url);
  73804. getRequest.onsuccess = function (event) {
  73805. file = (event.target).result;
  73806. };
  73807. getRequest.onerror = function (event) {
  73808. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  73809. notInDBCallback();
  73810. };
  73811. }
  73812. else {
  73813. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73814. callback();
  73815. }
  73816. };
  73817. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  73818. var _this = this;
  73819. if (this.isSupported) {
  73820. var targetStore;
  73821. if (url.indexOf(".babylon") !== -1) {
  73822. targetStore = "scenes";
  73823. }
  73824. else {
  73825. targetStore = "textures";
  73826. }
  73827. // Create XHR
  73828. var xhr = new XMLHttpRequest();
  73829. var fileData;
  73830. xhr.open("GET", url + "?" + Date.now(), true);
  73831. if (useArrayBuffer) {
  73832. xhr.responseType = "arraybuffer";
  73833. }
  73834. if (progressCallback) {
  73835. xhr.onprogress = progressCallback;
  73836. }
  73837. xhr.addEventListener("load", function () {
  73838. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  73839. // Blob as response (XHR2)
  73840. //fileData = xhr.responseText;
  73841. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  73842. if (!_this.hasReachedQuota && _this.db) {
  73843. // Open a transaction to the database
  73844. var transaction = _this.db.transaction([targetStore], "readwrite");
  73845. // the transaction could abort because of a QuotaExceededError error
  73846. transaction.onabort = function (event) {
  73847. try {
  73848. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73849. var error = event.srcElement['error'];
  73850. if (error && error.name === "QuotaExceededError") {
  73851. _this.hasReachedQuota = true;
  73852. }
  73853. }
  73854. catch (ex) { }
  73855. callback(fileData);
  73856. };
  73857. transaction.oncomplete = function (event) {
  73858. callback(fileData);
  73859. };
  73860. var newFile;
  73861. if (targetStore === "scenes") {
  73862. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  73863. }
  73864. else {
  73865. newFile = { textureUrl: url, data: fileData };
  73866. }
  73867. try {
  73868. // Put the scene into the database
  73869. var addRequest = transaction.objectStore(targetStore).put(newFile);
  73870. addRequest.onsuccess = function (event) {
  73871. };
  73872. addRequest.onerror = function (event) {
  73873. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  73874. };
  73875. }
  73876. catch (ex) {
  73877. callback(fileData);
  73878. }
  73879. }
  73880. else {
  73881. callback(fileData);
  73882. }
  73883. }
  73884. else {
  73885. if (xhr.status >= 400 && errorCallback) {
  73886. errorCallback(xhr);
  73887. }
  73888. else {
  73889. callback();
  73890. }
  73891. }
  73892. }, false);
  73893. xhr.addEventListener("error", function (event) {
  73894. BABYLON.Tools.Error("error on XHR request.");
  73895. callback();
  73896. }, false);
  73897. xhr.send();
  73898. }
  73899. else {
  73900. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73901. callback();
  73902. }
  73903. };
  73904. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  73905. Database.IsUASupportingBlobStorage = true;
  73906. /** Gets a boolean indicating if Database storate is enabled */
  73907. Database.IDBStorageEnabled = true;
  73908. Database._ParseURL = function (url) {
  73909. var a = document.createElement('a');
  73910. a.href = url;
  73911. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  73912. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  73913. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  73914. return absLocation;
  73915. };
  73916. Database._ReturnFullUrlLocation = function (url) {
  73917. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  73918. return (Database._ParseURL(window.location.href) + url);
  73919. }
  73920. else {
  73921. return url;
  73922. }
  73923. };
  73924. return Database;
  73925. }());
  73926. BABYLON.Database = Database;
  73927. })(BABYLON || (BABYLON = {}));
  73928. //# sourceMappingURL=babylon.database.js.map
  73929. var BABYLON;
  73930. (function (BABYLON) {
  73931. var FresnelParameters = /** @class */ (function () {
  73932. function FresnelParameters() {
  73933. this._isEnabled = true;
  73934. this.leftColor = BABYLON.Color3.White();
  73935. this.rightColor = BABYLON.Color3.Black();
  73936. this.bias = 0;
  73937. this.power = 1;
  73938. }
  73939. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  73940. get: function () {
  73941. return this._isEnabled;
  73942. },
  73943. set: function (value) {
  73944. if (this._isEnabled === value) {
  73945. return;
  73946. }
  73947. this._isEnabled = value;
  73948. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  73949. },
  73950. enumerable: true,
  73951. configurable: true
  73952. });
  73953. FresnelParameters.prototype.clone = function () {
  73954. var newFresnelParameters = new FresnelParameters();
  73955. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  73956. return newFresnelParameters;
  73957. };
  73958. FresnelParameters.prototype.serialize = function () {
  73959. var serializationObject = {};
  73960. serializationObject.isEnabled = this.isEnabled;
  73961. serializationObject.leftColor = this.leftColor.asArray();
  73962. serializationObject.rightColor = this.rightColor.asArray();
  73963. serializationObject.bias = this.bias;
  73964. serializationObject.power = this.power;
  73965. return serializationObject;
  73966. };
  73967. FresnelParameters.Parse = function (parsedFresnelParameters) {
  73968. var fresnelParameters = new FresnelParameters();
  73969. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  73970. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  73971. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  73972. fresnelParameters.bias = parsedFresnelParameters.bias;
  73973. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  73974. return fresnelParameters;
  73975. };
  73976. return FresnelParameters;
  73977. }());
  73978. BABYLON.FresnelParameters = FresnelParameters;
  73979. })(BABYLON || (BABYLON = {}));
  73980. //# sourceMappingURL=babylon.fresnelParameters.js.map
  73981. var BABYLON;
  73982. (function (BABYLON) {
  73983. var MultiMaterial = /** @class */ (function (_super) {
  73984. __extends(MultiMaterial, _super);
  73985. function MultiMaterial(name, scene) {
  73986. var _this = _super.call(this, name, scene, true) || this;
  73987. scene.multiMaterials.push(_this);
  73988. _this.subMaterials = new Array();
  73989. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  73990. return _this;
  73991. }
  73992. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  73993. get: function () {
  73994. return this._subMaterials;
  73995. },
  73996. set: function (value) {
  73997. this._subMaterials = value;
  73998. this._hookArray(value);
  73999. },
  74000. enumerable: true,
  74001. configurable: true
  74002. });
  74003. MultiMaterial.prototype._hookArray = function (array) {
  74004. var _this = this;
  74005. var oldPush = array.push;
  74006. array.push = function () {
  74007. var items = [];
  74008. for (var _i = 0; _i < arguments.length; _i++) {
  74009. items[_i] = arguments[_i];
  74010. }
  74011. var result = oldPush.apply(array, items);
  74012. _this._markAllSubMeshesAsTexturesDirty();
  74013. return result;
  74014. };
  74015. var oldSplice = array.splice;
  74016. array.splice = function (index, deleteCount) {
  74017. var deleted = oldSplice.apply(array, [index, deleteCount]);
  74018. _this._markAllSubMeshesAsTexturesDirty();
  74019. return deleted;
  74020. };
  74021. };
  74022. // Properties
  74023. MultiMaterial.prototype.getSubMaterial = function (index) {
  74024. if (index < 0 || index >= this.subMaterials.length) {
  74025. return this.getScene().defaultMaterial;
  74026. }
  74027. return this.subMaterials[index];
  74028. };
  74029. MultiMaterial.prototype.getActiveTextures = function () {
  74030. var _a;
  74031. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  74032. if (subMaterial) {
  74033. return subMaterial.getActiveTextures();
  74034. }
  74035. else {
  74036. return [];
  74037. }
  74038. }));
  74039. };
  74040. // Methods
  74041. MultiMaterial.prototype.getClassName = function () {
  74042. return "MultiMaterial";
  74043. };
  74044. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  74045. for (var index = 0; index < this.subMaterials.length; index++) {
  74046. var subMaterial = this.subMaterials[index];
  74047. if (subMaterial) {
  74048. if (subMaterial.storeEffectOnSubMeshes) {
  74049. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  74050. return false;
  74051. }
  74052. continue;
  74053. }
  74054. if (!subMaterial.isReady(mesh)) {
  74055. return false;
  74056. }
  74057. }
  74058. }
  74059. return true;
  74060. };
  74061. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  74062. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  74063. for (var index = 0; index < this.subMaterials.length; index++) {
  74064. var subMaterial = null;
  74065. var current = this.subMaterials[index];
  74066. if (cloneChildren && current) {
  74067. subMaterial = current.clone(name + "-" + current.name);
  74068. }
  74069. else {
  74070. subMaterial = this.subMaterials[index];
  74071. }
  74072. newMultiMaterial.subMaterials.push(subMaterial);
  74073. }
  74074. return newMultiMaterial;
  74075. };
  74076. MultiMaterial.prototype.serialize = function () {
  74077. var serializationObject = {};
  74078. serializationObject.name = this.name;
  74079. serializationObject.id = this.id;
  74080. if (BABYLON.Tags) {
  74081. serializationObject.tags = BABYLON.Tags.GetTags(this);
  74082. }
  74083. serializationObject.materials = [];
  74084. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  74085. var subMat = this.subMaterials[matIndex];
  74086. if (subMat) {
  74087. serializationObject.materials.push(subMat.id);
  74088. }
  74089. else {
  74090. serializationObject.materials.push(null);
  74091. }
  74092. }
  74093. return serializationObject;
  74094. };
  74095. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  74096. var scene = this.getScene();
  74097. if (!scene) {
  74098. return;
  74099. }
  74100. var index = scene.multiMaterials.indexOf(this);
  74101. if (index >= 0) {
  74102. scene.multiMaterials.splice(index, 1);
  74103. }
  74104. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  74105. };
  74106. return MultiMaterial;
  74107. }(BABYLON.Material));
  74108. BABYLON.MultiMaterial = MultiMaterial;
  74109. })(BABYLON || (BABYLON = {}));
  74110. //# sourceMappingURL=babylon.multiMaterial.js.map
  74111. var BABYLON;
  74112. (function (BABYLON) {
  74113. var FreeCameraTouchInput = /** @class */ (function () {
  74114. function FreeCameraTouchInput() {
  74115. this._offsetX = null;
  74116. this._offsetY = null;
  74117. this._pointerPressed = new Array();
  74118. this.touchAngularSensibility = 200000.0;
  74119. this.touchMoveSensibility = 250.0;
  74120. }
  74121. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  74122. var _this = this;
  74123. var previousPosition = null;
  74124. if (this._pointerInput === undefined) {
  74125. this._onLostFocus = function (evt) {
  74126. _this._offsetX = null;
  74127. _this._offsetY = null;
  74128. };
  74129. this._pointerInput = function (p, s) {
  74130. var evt = p.event;
  74131. if (evt.pointerType === "mouse") {
  74132. return;
  74133. }
  74134. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  74135. if (!noPreventDefault) {
  74136. evt.preventDefault();
  74137. }
  74138. _this._pointerPressed.push(evt.pointerId);
  74139. if (_this._pointerPressed.length !== 1) {
  74140. return;
  74141. }
  74142. previousPosition = {
  74143. x: evt.clientX,
  74144. y: evt.clientY
  74145. };
  74146. }
  74147. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  74148. if (!noPreventDefault) {
  74149. evt.preventDefault();
  74150. }
  74151. var index = _this._pointerPressed.indexOf(evt.pointerId);
  74152. if (index === -1) {
  74153. return;
  74154. }
  74155. _this._pointerPressed.splice(index, 1);
  74156. if (index != 0) {
  74157. return;
  74158. }
  74159. previousPosition = null;
  74160. _this._offsetX = null;
  74161. _this._offsetY = null;
  74162. }
  74163. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  74164. if (!noPreventDefault) {
  74165. evt.preventDefault();
  74166. }
  74167. if (!previousPosition) {
  74168. return;
  74169. }
  74170. var index = _this._pointerPressed.indexOf(evt.pointerId);
  74171. if (index != 0) {
  74172. return;
  74173. }
  74174. _this._offsetX = evt.clientX - previousPosition.x;
  74175. _this._offsetY = -(evt.clientY - previousPosition.y);
  74176. }
  74177. };
  74178. }
  74179. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  74180. if (this._onLostFocus) {
  74181. element.addEventListener("blur", this._onLostFocus);
  74182. }
  74183. };
  74184. FreeCameraTouchInput.prototype.detachControl = function (element) {
  74185. if (this._pointerInput && element) {
  74186. if (this._observer) {
  74187. this.camera.getScene().onPointerObservable.remove(this._observer);
  74188. this._observer = null;
  74189. }
  74190. if (this._onLostFocus) {
  74191. element.removeEventListener("blur", this._onLostFocus);
  74192. this._onLostFocus = null;
  74193. }
  74194. this._pointerPressed = [];
  74195. this._offsetX = null;
  74196. this._offsetY = null;
  74197. }
  74198. };
  74199. FreeCameraTouchInput.prototype.checkInputs = function () {
  74200. if (this._offsetX && this._offsetY) {
  74201. var camera = this.camera;
  74202. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  74203. if (this._pointerPressed.length > 1) {
  74204. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  74205. }
  74206. else {
  74207. var speed = camera._computeLocalCameraSpeed();
  74208. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  74209. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  74210. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  74211. }
  74212. }
  74213. };
  74214. FreeCameraTouchInput.prototype.getClassName = function () {
  74215. return "FreeCameraTouchInput";
  74216. };
  74217. FreeCameraTouchInput.prototype.getSimpleName = function () {
  74218. return "touch";
  74219. };
  74220. __decorate([
  74221. BABYLON.serialize()
  74222. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  74223. __decorate([
  74224. BABYLON.serialize()
  74225. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  74226. return FreeCameraTouchInput;
  74227. }());
  74228. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  74229. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  74230. })(BABYLON || (BABYLON = {}));
  74231. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  74232. var BABYLON;
  74233. (function (BABYLON) {
  74234. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  74235. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  74236. });
  74237. // We're mainly based on the logic defined into the FreeCamera code
  74238. var TouchCamera = /** @class */ (function (_super) {
  74239. __extends(TouchCamera, _super);
  74240. //-- end properties for backward compatibility for inputs
  74241. function TouchCamera(name, position, scene) {
  74242. var _this = _super.call(this, name, position, scene) || this;
  74243. _this.inputs.addTouch();
  74244. _this._setupInputs();
  74245. return _this;
  74246. }
  74247. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  74248. //-- Begin properties for backward compatibility for inputs
  74249. get: function () {
  74250. var touch = this.inputs.attached["touch"];
  74251. if (touch)
  74252. return touch.touchAngularSensibility;
  74253. return 0;
  74254. },
  74255. set: function (value) {
  74256. var touch = this.inputs.attached["touch"];
  74257. if (touch)
  74258. touch.touchAngularSensibility = value;
  74259. },
  74260. enumerable: true,
  74261. configurable: true
  74262. });
  74263. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  74264. get: function () {
  74265. var touch = this.inputs.attached["touch"];
  74266. if (touch)
  74267. return touch.touchMoveSensibility;
  74268. return 0;
  74269. },
  74270. set: function (value) {
  74271. var touch = this.inputs.attached["touch"];
  74272. if (touch)
  74273. touch.touchMoveSensibility = value;
  74274. },
  74275. enumerable: true,
  74276. configurable: true
  74277. });
  74278. TouchCamera.prototype.getClassName = function () {
  74279. return "TouchCamera";
  74280. };
  74281. /** @hidden */
  74282. TouchCamera.prototype._setupInputs = function () {
  74283. var mouse = this.inputs.attached["mouse"];
  74284. if (mouse) {
  74285. mouse.touchEnabled = false;
  74286. }
  74287. };
  74288. return TouchCamera;
  74289. }(BABYLON.FreeCamera));
  74290. BABYLON.TouchCamera = TouchCamera;
  74291. })(BABYLON || (BABYLON = {}));
  74292. //# sourceMappingURL=babylon.touchCamera.js.map
  74293. var BABYLON;
  74294. (function (BABYLON) {
  74295. var ProceduralTexture = /** @class */ (function (_super) {
  74296. __extends(ProceduralTexture, _super);
  74297. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  74298. if (fallbackTexture === void 0) { fallbackTexture = null; }
  74299. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74300. if (isCube === void 0) { isCube = false; }
  74301. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  74302. _this.isCube = isCube;
  74303. _this.isEnabled = true;
  74304. _this._currentRefreshId = -1;
  74305. _this._refreshRate = 1;
  74306. /**
  74307. * Event raised when the texture is generated
  74308. */
  74309. _this.onGeneratedObservable = new BABYLON.Observable();
  74310. _this._vertexBuffers = {};
  74311. _this._uniforms = new Array();
  74312. _this._samplers = new Array();
  74313. /** @hidden */
  74314. _this._textures = {};
  74315. _this._floats = {};
  74316. _this._ints = {};
  74317. _this._floatsArrays = {};
  74318. _this._colors3 = {};
  74319. _this._colors4 = {};
  74320. _this._vectors2 = {};
  74321. _this._vectors3 = {};
  74322. _this._matrices = {};
  74323. _this._fallbackTextureUsed = false;
  74324. _this._cachedDefines = "";
  74325. _this._contentUpdateId = -1;
  74326. scene = _this.getScene();
  74327. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  74328. if (!component) {
  74329. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  74330. scene._addComponent(component);
  74331. }
  74332. scene.proceduralTextures.push(_this);
  74333. _this._engine = scene.getEngine();
  74334. _this.name = name;
  74335. _this.isRenderTarget = true;
  74336. _this._size = size;
  74337. _this._generateMipMaps = generateMipMaps;
  74338. _this.setFragment(fragment);
  74339. _this._fallbackTexture = fallbackTexture;
  74340. if (isCube) {
  74341. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  74342. _this.setFloat("face", 0);
  74343. }
  74344. else {
  74345. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  74346. }
  74347. // VBO
  74348. var vertices = [];
  74349. vertices.push(1, 1);
  74350. vertices.push(-1, 1);
  74351. vertices.push(-1, -1);
  74352. vertices.push(1, -1);
  74353. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74354. _this._createIndexBuffer();
  74355. return _this;
  74356. }
  74357. /**
  74358. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  74359. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  74360. */
  74361. ProceduralTexture.prototype.getContent = function () {
  74362. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  74363. return this._contentData;
  74364. }
  74365. this._contentData = this.readPixels(0, 0, this._contentData);
  74366. this._contentUpdateId = this._currentRefreshId;
  74367. return this._contentData;
  74368. };
  74369. ProceduralTexture.prototype._createIndexBuffer = function () {
  74370. var engine = this._engine;
  74371. // Indices
  74372. var indices = [];
  74373. indices.push(0);
  74374. indices.push(1);
  74375. indices.push(2);
  74376. indices.push(0);
  74377. indices.push(2);
  74378. indices.push(3);
  74379. this._indexBuffer = engine.createIndexBuffer(indices);
  74380. };
  74381. /** @hidden */
  74382. ProceduralTexture.prototype._rebuild = function () {
  74383. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74384. if (vb) {
  74385. vb._rebuild();
  74386. }
  74387. this._createIndexBuffer();
  74388. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  74389. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  74390. }
  74391. };
  74392. ProceduralTexture.prototype.reset = function () {
  74393. if (this._effect === undefined) {
  74394. return;
  74395. }
  74396. var engine = this._engine;
  74397. engine._releaseEffect(this._effect);
  74398. };
  74399. ProceduralTexture.prototype._getDefines = function () {
  74400. return "";
  74401. };
  74402. ProceduralTexture.prototype.isReady = function () {
  74403. var _this = this;
  74404. var engine = this._engine;
  74405. var shaders;
  74406. if (!this._fragment) {
  74407. return false;
  74408. }
  74409. if (this._fallbackTextureUsed) {
  74410. return true;
  74411. }
  74412. var defines = this._getDefines();
  74413. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  74414. return true;
  74415. }
  74416. if (this._fragment.fragmentElement !== undefined) {
  74417. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  74418. }
  74419. else {
  74420. shaders = { vertex: "procedural", fragment: this._fragment };
  74421. }
  74422. this._cachedDefines = defines;
  74423. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  74424. _this.releaseInternalTexture();
  74425. if (_this._fallbackTexture) {
  74426. _this._texture = _this._fallbackTexture._texture;
  74427. if (_this._texture) {
  74428. _this._texture.incrementReferences();
  74429. }
  74430. }
  74431. _this._fallbackTextureUsed = true;
  74432. });
  74433. return this._effect.isReady();
  74434. };
  74435. ProceduralTexture.prototype.resetRefreshCounter = function () {
  74436. this._currentRefreshId = -1;
  74437. };
  74438. ProceduralTexture.prototype.setFragment = function (fragment) {
  74439. this._fragment = fragment;
  74440. };
  74441. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  74442. get: function () {
  74443. return this._refreshRate;
  74444. },
  74445. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  74446. set: function (value) {
  74447. this._refreshRate = value;
  74448. this.resetRefreshCounter();
  74449. },
  74450. enumerable: true,
  74451. configurable: true
  74452. });
  74453. /** @hidden */
  74454. ProceduralTexture.prototype._shouldRender = function () {
  74455. if (!this.isEnabled || !this.isReady() || !this._texture) {
  74456. if (this._texture) {
  74457. this._texture.isReady = false;
  74458. }
  74459. return false;
  74460. }
  74461. if (this._fallbackTextureUsed) {
  74462. return false;
  74463. }
  74464. if (this._currentRefreshId === -1) { // At least render once
  74465. this._currentRefreshId = 1;
  74466. return true;
  74467. }
  74468. if (this.refreshRate === this._currentRefreshId) {
  74469. this._currentRefreshId = 1;
  74470. return true;
  74471. }
  74472. this._currentRefreshId++;
  74473. return false;
  74474. };
  74475. ProceduralTexture.prototype.getRenderSize = function () {
  74476. return this._size;
  74477. };
  74478. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  74479. if (this._fallbackTextureUsed) {
  74480. return;
  74481. }
  74482. this.releaseInternalTexture();
  74483. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  74484. // Update properties
  74485. this._size = size;
  74486. this._generateMipMaps = generateMipMaps;
  74487. };
  74488. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  74489. if (this._uniforms.indexOf(uniformName) === -1) {
  74490. this._uniforms.push(uniformName);
  74491. }
  74492. };
  74493. ProceduralTexture.prototype.setTexture = function (name, texture) {
  74494. if (this._samplers.indexOf(name) === -1) {
  74495. this._samplers.push(name);
  74496. }
  74497. this._textures[name] = texture;
  74498. return this;
  74499. };
  74500. ProceduralTexture.prototype.setFloat = function (name, value) {
  74501. this._checkUniform(name);
  74502. this._floats[name] = value;
  74503. return this;
  74504. };
  74505. /**
  74506. * Set the value of an uniform to an integer value
  74507. * @param name defines the name of the uniform
  74508. * @param value defines the value to set
  74509. * @returns the current procedural texture
  74510. */
  74511. ProceduralTexture.prototype.setInt = function (name, value) {
  74512. this._checkUniform(name);
  74513. this._ints[name] = value;
  74514. return this;
  74515. };
  74516. ProceduralTexture.prototype.setFloats = function (name, value) {
  74517. this._checkUniform(name);
  74518. this._floatsArrays[name] = value;
  74519. return this;
  74520. };
  74521. ProceduralTexture.prototype.setColor3 = function (name, value) {
  74522. this._checkUniform(name);
  74523. this._colors3[name] = value;
  74524. return this;
  74525. };
  74526. ProceduralTexture.prototype.setColor4 = function (name, value) {
  74527. this._checkUniform(name);
  74528. this._colors4[name] = value;
  74529. return this;
  74530. };
  74531. ProceduralTexture.prototype.setVector2 = function (name, value) {
  74532. this._checkUniform(name);
  74533. this._vectors2[name] = value;
  74534. return this;
  74535. };
  74536. ProceduralTexture.prototype.setVector3 = function (name, value) {
  74537. this._checkUniform(name);
  74538. this._vectors3[name] = value;
  74539. return this;
  74540. };
  74541. ProceduralTexture.prototype.setMatrix = function (name, value) {
  74542. this._checkUniform(name);
  74543. this._matrices[name] = value;
  74544. return this;
  74545. };
  74546. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  74547. var scene = this.getScene();
  74548. if (!scene) {
  74549. return;
  74550. }
  74551. var engine = this._engine;
  74552. // Render
  74553. engine.enableEffect(this._effect);
  74554. engine.setState(false);
  74555. // Texture
  74556. for (var name in this._textures) {
  74557. this._effect.setTexture(name, this._textures[name]);
  74558. }
  74559. // Float
  74560. for (name in this._ints) {
  74561. this._effect.setInt(name, this._ints[name]);
  74562. }
  74563. // Float
  74564. for (name in this._floats) {
  74565. this._effect.setFloat(name, this._floats[name]);
  74566. }
  74567. // Floats
  74568. for (name in this._floatsArrays) {
  74569. this._effect.setArray(name, this._floatsArrays[name]);
  74570. }
  74571. // Color3
  74572. for (name in this._colors3) {
  74573. this._effect.setColor3(name, this._colors3[name]);
  74574. }
  74575. // Color4
  74576. for (name in this._colors4) {
  74577. var color = this._colors4[name];
  74578. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  74579. }
  74580. // Vector2
  74581. for (name in this._vectors2) {
  74582. this._effect.setVector2(name, this._vectors2[name]);
  74583. }
  74584. // Vector3
  74585. for (name in this._vectors3) {
  74586. this._effect.setVector3(name, this._vectors3[name]);
  74587. }
  74588. // Matrix
  74589. for (name in this._matrices) {
  74590. this._effect.setMatrix(name, this._matrices[name]);
  74591. }
  74592. if (!this._texture) {
  74593. return;
  74594. }
  74595. if (this.isCube) {
  74596. for (var face = 0; face < 6; face++) {
  74597. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  74598. // VBOs
  74599. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74600. this._effect.setFloat("face", face);
  74601. // Clear
  74602. engine.clear(scene.clearColor, true, true, true);
  74603. // Draw order
  74604. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74605. // Mipmaps
  74606. if (face === 5) {
  74607. engine.generateMipMapsForCubemap(this._texture);
  74608. }
  74609. }
  74610. }
  74611. else {
  74612. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  74613. // VBOs
  74614. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74615. // Clear
  74616. engine.clear(scene.clearColor, true, true, true);
  74617. // Draw order
  74618. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74619. }
  74620. // Unbind
  74621. engine.unBindFramebuffer(this._texture, this.isCube);
  74622. if (this.onGenerated) {
  74623. this.onGenerated();
  74624. }
  74625. this.onGeneratedObservable.notifyObservers(this);
  74626. };
  74627. ProceduralTexture.prototype.clone = function () {
  74628. var textureSize = this.getSize();
  74629. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  74630. // Base texture
  74631. newTexture.hasAlpha = this.hasAlpha;
  74632. newTexture.level = this.level;
  74633. // RenderTarget Texture
  74634. newTexture.coordinatesMode = this.coordinatesMode;
  74635. return newTexture;
  74636. };
  74637. ProceduralTexture.prototype.dispose = function () {
  74638. var scene = this.getScene();
  74639. if (!scene) {
  74640. return;
  74641. }
  74642. var index = scene.proceduralTextures.indexOf(this);
  74643. if (index >= 0) {
  74644. scene.proceduralTextures.splice(index, 1);
  74645. }
  74646. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74647. if (vertexBuffer) {
  74648. vertexBuffer.dispose();
  74649. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74650. }
  74651. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  74652. this._indexBuffer = null;
  74653. }
  74654. _super.prototype.dispose.call(this);
  74655. };
  74656. __decorate([
  74657. BABYLON.serialize()
  74658. ], ProceduralTexture.prototype, "_size", void 0);
  74659. __decorate([
  74660. BABYLON.serialize()
  74661. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  74662. __decorate([
  74663. BABYLON.serialize()
  74664. ], ProceduralTexture.prototype, "isEnabled", void 0);
  74665. __decorate([
  74666. BABYLON.serialize()
  74667. ], ProceduralTexture.prototype, "refreshRate", null);
  74668. return ProceduralTexture;
  74669. }(BABYLON.Texture));
  74670. BABYLON.ProceduralTexture = ProceduralTexture;
  74671. })(BABYLON || (BABYLON = {}));
  74672. //# sourceMappingURL=babylon.proceduralTexture.js.map
  74673. var BABYLON;
  74674. (function (BABYLON) {
  74675. /**
  74676. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  74677. * in a given scene.
  74678. */
  74679. var ProceduralTextureSceneComponent = /** @class */ (function () {
  74680. /**
  74681. * Creates a new instance of the component for the given scene
  74682. * @param scene Defines the scene to register the component in
  74683. */
  74684. function ProceduralTextureSceneComponent(scene) {
  74685. /**
  74686. * The component name helpfull to identify the component in the list of scene components.
  74687. */
  74688. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  74689. this.scene = scene;
  74690. this.scene.proceduralTextures = new Array();
  74691. scene.layers = new Array();
  74692. }
  74693. /**
  74694. * Registers the component in a given scene
  74695. */
  74696. ProceduralTextureSceneComponent.prototype.register = function () {
  74697. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  74698. };
  74699. /**
  74700. * Rebuilds the elements related to this component in case of
  74701. * context lost for instance.
  74702. */
  74703. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  74704. // Nothing to do here.
  74705. };
  74706. /**
  74707. * Disposes the component and the associated ressources.
  74708. */
  74709. ProceduralTextureSceneComponent.prototype.dispose = function () {
  74710. // Nothing to do here.
  74711. };
  74712. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  74713. if (this.scene.proceduralTexturesEnabled) {
  74714. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  74715. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  74716. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  74717. if (proceduralTexture._shouldRender()) {
  74718. proceduralTexture.render();
  74719. }
  74720. }
  74721. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  74722. }
  74723. };
  74724. return ProceduralTextureSceneComponent;
  74725. }());
  74726. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  74727. })(BABYLON || (BABYLON = {}));
  74728. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  74729. var BABYLON;
  74730. (function (BABYLON) {
  74731. var CustomProceduralTexture = /** @class */ (function (_super) {
  74732. __extends(CustomProceduralTexture, _super);
  74733. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  74734. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  74735. _this._animate = true;
  74736. _this._time = 0;
  74737. _this._texturePath = texturePath;
  74738. //Try to load json
  74739. _this.loadJson(texturePath);
  74740. _this.refreshRate = 1;
  74741. return _this;
  74742. }
  74743. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  74744. var _this = this;
  74745. var noConfigFile = function () {
  74746. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  74747. try {
  74748. _this.setFragment(_this._texturePath);
  74749. }
  74750. catch (ex) {
  74751. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  74752. }
  74753. };
  74754. var configFileUrl = jsonUrl + "/config.json";
  74755. var xhr = new XMLHttpRequest();
  74756. xhr.open("GET", configFileUrl, true);
  74757. xhr.addEventListener("load", function () {
  74758. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  74759. try {
  74760. _this._config = JSON.parse(xhr.response);
  74761. _this.updateShaderUniforms();
  74762. _this.updateTextures();
  74763. _this.setFragment(_this._texturePath + "/custom");
  74764. _this._animate = _this._config.animate;
  74765. _this.refreshRate = _this._config.refreshrate;
  74766. }
  74767. catch (ex) {
  74768. noConfigFile();
  74769. }
  74770. }
  74771. else {
  74772. noConfigFile();
  74773. }
  74774. }, false);
  74775. xhr.addEventListener("error", function () {
  74776. noConfigFile();
  74777. }, false);
  74778. try {
  74779. xhr.send();
  74780. }
  74781. catch (ex) {
  74782. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  74783. }
  74784. };
  74785. CustomProceduralTexture.prototype.isReady = function () {
  74786. if (!_super.prototype.isReady.call(this)) {
  74787. return false;
  74788. }
  74789. for (var name in this._textures) {
  74790. var texture = this._textures[name];
  74791. if (!texture.isReady()) {
  74792. return false;
  74793. }
  74794. }
  74795. return true;
  74796. };
  74797. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  74798. var scene = this.getScene();
  74799. if (this._animate && scene) {
  74800. this._time += scene.getAnimationRatio() * 0.03;
  74801. this.updateShaderUniforms();
  74802. }
  74803. _super.prototype.render.call(this, useCameraPostProcess);
  74804. };
  74805. CustomProceduralTexture.prototype.updateTextures = function () {
  74806. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  74807. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  74808. }
  74809. };
  74810. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  74811. if (this._config) {
  74812. for (var j = 0; j < this._config.uniforms.length; j++) {
  74813. var uniform = this._config.uniforms[j];
  74814. switch (uniform.type) {
  74815. case "float":
  74816. this.setFloat(uniform.name, uniform.value);
  74817. break;
  74818. case "color3":
  74819. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  74820. break;
  74821. case "color4":
  74822. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  74823. break;
  74824. case "vector2":
  74825. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  74826. break;
  74827. case "vector3":
  74828. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  74829. break;
  74830. }
  74831. }
  74832. }
  74833. this.setFloat("time", this._time);
  74834. };
  74835. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  74836. get: function () {
  74837. return this._animate;
  74838. },
  74839. set: function (value) {
  74840. this._animate = value;
  74841. },
  74842. enumerable: true,
  74843. configurable: true
  74844. });
  74845. return CustomProceduralTexture;
  74846. }(BABYLON.ProceduralTexture));
  74847. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  74848. })(BABYLON || (BABYLON = {}));
  74849. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  74850. var BABYLON;
  74851. (function (BABYLON) {
  74852. var FreeCameraGamepadInput = /** @class */ (function () {
  74853. function FreeCameraGamepadInput() {
  74854. this.gamepadAngularSensibility = 200;
  74855. this.gamepadMoveSensibility = 40;
  74856. // private members
  74857. this._cameraTransform = BABYLON.Matrix.Identity();
  74858. this._deltaTransform = BABYLON.Vector3.Zero();
  74859. this._vector3 = BABYLON.Vector3.Zero();
  74860. this._vector2 = BABYLON.Vector2.Zero();
  74861. }
  74862. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  74863. var _this = this;
  74864. var manager = this.camera.getScene().gamepadManager;
  74865. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74866. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74867. // prioritize XBOX gamepads.
  74868. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  74869. _this.gamepad = gamepad;
  74870. }
  74871. }
  74872. });
  74873. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74874. if (_this.gamepad === gamepad) {
  74875. _this.gamepad = null;
  74876. }
  74877. });
  74878. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  74879. };
  74880. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  74881. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74882. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74883. this.gamepad = null;
  74884. };
  74885. FreeCameraGamepadInput.prototype.checkInputs = function () {
  74886. if (this.gamepad && this.gamepad.leftStick) {
  74887. var camera = this.camera;
  74888. var LSValues = this.gamepad.leftStick;
  74889. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  74890. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  74891. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  74892. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  74893. var RSValues = this.gamepad.rightStick;
  74894. if (RSValues) {
  74895. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  74896. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  74897. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  74898. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  74899. }
  74900. else {
  74901. RSValues = { x: 0, y: 0 };
  74902. }
  74903. if (!camera.rotationQuaternion) {
  74904. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  74905. }
  74906. else {
  74907. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  74908. }
  74909. var speed = camera._computeLocalCameraSpeed() * 50.0;
  74910. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  74911. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  74912. camera.cameraDirection.addInPlace(this._deltaTransform);
  74913. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  74914. camera.cameraRotation.addInPlace(this._vector2);
  74915. }
  74916. };
  74917. FreeCameraGamepadInput.prototype.getClassName = function () {
  74918. return "FreeCameraGamepadInput";
  74919. };
  74920. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  74921. return "gamepad";
  74922. };
  74923. __decorate([
  74924. BABYLON.serialize()
  74925. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  74926. __decorate([
  74927. BABYLON.serialize()
  74928. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  74929. return FreeCameraGamepadInput;
  74930. }());
  74931. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  74932. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  74933. })(BABYLON || (BABYLON = {}));
  74934. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  74935. var BABYLON;
  74936. (function (BABYLON) {
  74937. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  74938. function ArcRotateCameraGamepadInput() {
  74939. this.gamepadRotationSensibility = 80;
  74940. this.gamepadMoveSensibility = 40;
  74941. }
  74942. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  74943. var _this = this;
  74944. var manager = this.camera.getScene().gamepadManager;
  74945. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74946. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74947. // prioritize XBOX gamepads.
  74948. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  74949. _this.gamepad = gamepad;
  74950. }
  74951. }
  74952. });
  74953. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74954. if (_this.gamepad === gamepad) {
  74955. _this.gamepad = null;
  74956. }
  74957. });
  74958. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  74959. };
  74960. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  74961. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74962. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74963. this.gamepad = null;
  74964. };
  74965. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  74966. if (this.gamepad) {
  74967. var camera = this.camera;
  74968. var RSValues = this.gamepad.rightStick;
  74969. if (RSValues) {
  74970. if (RSValues.x != 0) {
  74971. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  74972. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  74973. camera.inertialAlphaOffset += normalizedRX;
  74974. }
  74975. }
  74976. if (RSValues.y != 0) {
  74977. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  74978. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  74979. camera.inertialBetaOffset += normalizedRY;
  74980. }
  74981. }
  74982. }
  74983. var LSValues = this.gamepad.leftStick;
  74984. if (LSValues && LSValues.y != 0) {
  74985. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  74986. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  74987. this.camera.inertialRadiusOffset -= normalizedLY;
  74988. }
  74989. }
  74990. }
  74991. };
  74992. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  74993. return "ArcRotateCameraGamepadInput";
  74994. };
  74995. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  74996. return "gamepad";
  74997. };
  74998. __decorate([
  74999. BABYLON.serialize()
  75000. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  75001. __decorate([
  75002. BABYLON.serialize()
  75003. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  75004. return ArcRotateCameraGamepadInput;
  75005. }());
  75006. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  75007. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  75008. })(BABYLON || (BABYLON = {}));
  75009. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  75010. var BABYLON;
  75011. (function (BABYLON) {
  75012. var GamepadManager = /** @class */ (function () {
  75013. function GamepadManager(_scene) {
  75014. var _this = this;
  75015. this._scene = _scene;
  75016. this._babylonGamepads = [];
  75017. this._oneGamepadConnected = false;
  75018. /** @hidden */
  75019. this._isMonitoring = false;
  75020. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  75021. if (!BABYLON.Tools.IsWindowObjectExist()) {
  75022. this._gamepadEventSupported = false;
  75023. }
  75024. else {
  75025. this._gamepadEventSupported = 'GamepadEvent' in window;
  75026. this._gamepadSupport = (navigator.getGamepads ||
  75027. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  75028. }
  75029. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  75030. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  75031. for (var i in _this._babylonGamepads) {
  75032. var gamepad = _this._babylonGamepads[i];
  75033. if (gamepad && gamepad._isConnected) {
  75034. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  75035. }
  75036. }
  75037. });
  75038. this._onGamepadConnectedEvent = function (evt) {
  75039. var gamepad = evt.gamepad;
  75040. if (gamepad.index in _this._babylonGamepads) {
  75041. if (_this._babylonGamepads[gamepad.index].isConnected) {
  75042. return;
  75043. }
  75044. }
  75045. var newGamepad;
  75046. if (_this._babylonGamepads[gamepad.index]) {
  75047. newGamepad = _this._babylonGamepads[gamepad.index];
  75048. newGamepad.browserGamepad = gamepad;
  75049. newGamepad._isConnected = true;
  75050. }
  75051. else {
  75052. newGamepad = _this._addNewGamepad(gamepad);
  75053. }
  75054. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  75055. _this._startMonitoringGamepads();
  75056. };
  75057. this._onGamepadDisconnectedEvent = function (evt) {
  75058. var gamepad = evt.gamepad;
  75059. // Remove the gamepad from the list of gamepads to monitor.
  75060. for (var i in _this._babylonGamepads) {
  75061. if (_this._babylonGamepads[i].index === gamepad.index) {
  75062. var disconnectedGamepad = _this._babylonGamepads[i];
  75063. disconnectedGamepad._isConnected = false;
  75064. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  75065. break;
  75066. }
  75067. }
  75068. };
  75069. if (this._gamepadSupport) {
  75070. //first add already-connected gamepads
  75071. this._updateGamepadObjects();
  75072. if (this._babylonGamepads.length) {
  75073. this._startMonitoringGamepads();
  75074. }
  75075. // Checking if the gamepad connected event is supported (like in Firefox)
  75076. if (this._gamepadEventSupported) {
  75077. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  75078. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  75079. }
  75080. else {
  75081. this._startMonitoringGamepads();
  75082. }
  75083. }
  75084. }
  75085. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  75086. get: function () {
  75087. return this._babylonGamepads;
  75088. },
  75089. enumerable: true,
  75090. configurable: true
  75091. });
  75092. GamepadManager.prototype.getGamepadByType = function (type) {
  75093. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  75094. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  75095. var gamepad = _a[_i];
  75096. if (gamepad && gamepad.type === type) {
  75097. return gamepad;
  75098. }
  75099. }
  75100. return null;
  75101. };
  75102. GamepadManager.prototype.dispose = function () {
  75103. if (this._gamepadEventSupported) {
  75104. if (this._onGamepadConnectedEvent) {
  75105. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  75106. }
  75107. if (this._onGamepadDisconnectedEvent) {
  75108. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  75109. }
  75110. this._onGamepadConnectedEvent = null;
  75111. this._onGamepadDisconnectedEvent = null;
  75112. }
  75113. this._babylonGamepads.forEach(function (gamepad) {
  75114. gamepad.dispose();
  75115. });
  75116. this.onGamepadConnectedObservable.clear();
  75117. this.onGamepadDisconnectedObservable.clear();
  75118. this._oneGamepadConnected = false;
  75119. this._stopMonitoringGamepads();
  75120. this._babylonGamepads = [];
  75121. };
  75122. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  75123. if (!this._oneGamepadConnected) {
  75124. this._oneGamepadConnected = true;
  75125. }
  75126. var newGamepad;
  75127. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  75128. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  75129. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  75130. }
  75131. // if pose is supported, use the (WebVR) pose enabled controller
  75132. else if (gamepad.pose) {
  75133. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  75134. }
  75135. else {
  75136. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  75137. }
  75138. this._babylonGamepads[newGamepad.index] = newGamepad;
  75139. return newGamepad;
  75140. };
  75141. GamepadManager.prototype._startMonitoringGamepads = function () {
  75142. if (!this._isMonitoring) {
  75143. this._isMonitoring = true;
  75144. //back-comp
  75145. if (!this._scene) {
  75146. this._checkGamepadsStatus();
  75147. }
  75148. }
  75149. };
  75150. GamepadManager.prototype._stopMonitoringGamepads = function () {
  75151. this._isMonitoring = false;
  75152. };
  75153. /** @hidden */
  75154. GamepadManager.prototype._checkGamepadsStatus = function () {
  75155. var _this = this;
  75156. // Hack to be compatible Chrome
  75157. this._updateGamepadObjects();
  75158. for (var i in this._babylonGamepads) {
  75159. var gamepad = this._babylonGamepads[i];
  75160. if (!gamepad || !gamepad.isConnected) {
  75161. continue;
  75162. }
  75163. gamepad.update();
  75164. }
  75165. if (this._isMonitoring && !this._scene) {
  75166. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  75167. }
  75168. };
  75169. // This function is called only on Chrome, which does not properly support
  75170. // connection/disconnection events and forces you to recopy again the gamepad object
  75171. GamepadManager.prototype._updateGamepadObjects = function () {
  75172. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  75173. for (var i = 0; i < gamepads.length; i++) {
  75174. var gamepad = gamepads[i];
  75175. if (gamepad) {
  75176. if (!this._babylonGamepads[gamepad.index]) {
  75177. var newGamepad = this._addNewGamepad(gamepad);
  75178. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  75179. }
  75180. else {
  75181. // Forced to copy again this object for Chrome for unknown reason
  75182. this._babylonGamepads[i].browserGamepad = gamepad;
  75183. if (!this._babylonGamepads[i].isConnected) {
  75184. this._babylonGamepads[i]._isConnected = true;
  75185. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  75186. }
  75187. }
  75188. }
  75189. }
  75190. };
  75191. return GamepadManager;
  75192. }());
  75193. BABYLON.GamepadManager = GamepadManager;
  75194. })(BABYLON || (BABYLON = {}));
  75195. //# sourceMappingURL=babylon.gamepadManager.js.map
  75196. var BABYLON;
  75197. (function (BABYLON) {
  75198. var StickValues = /** @class */ (function () {
  75199. function StickValues(x, y) {
  75200. this.x = x;
  75201. this.y = y;
  75202. }
  75203. return StickValues;
  75204. }());
  75205. BABYLON.StickValues = StickValues;
  75206. var Gamepad = /** @class */ (function () {
  75207. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  75208. if (leftStickX === void 0) { leftStickX = 0; }
  75209. if (leftStickY === void 0) { leftStickY = 1; }
  75210. if (rightStickX === void 0) { rightStickX = 2; }
  75211. if (rightStickY === void 0) { rightStickY = 3; }
  75212. this.id = id;
  75213. this.index = index;
  75214. this.browserGamepad = browserGamepad;
  75215. this._leftStick = { x: 0, y: 0 };
  75216. this._rightStick = { x: 0, y: 0 };
  75217. /** @hidden */
  75218. this._isConnected = true;
  75219. this._invertLeftStickY = false;
  75220. this.type = Gamepad.GAMEPAD;
  75221. this._leftStickAxisX = leftStickX;
  75222. this._leftStickAxisY = leftStickY;
  75223. this._rightStickAxisX = rightStickX;
  75224. this._rightStickAxisY = rightStickY;
  75225. if (this.browserGamepad.axes.length >= 2) {
  75226. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  75227. }
  75228. if (this.browserGamepad.axes.length >= 4) {
  75229. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  75230. }
  75231. }
  75232. Object.defineProperty(Gamepad.prototype, "isConnected", {
  75233. get: function () {
  75234. return this._isConnected;
  75235. },
  75236. enumerable: true,
  75237. configurable: true
  75238. });
  75239. Gamepad.prototype.onleftstickchanged = function (callback) {
  75240. this._onleftstickchanged = callback;
  75241. };
  75242. Gamepad.prototype.onrightstickchanged = function (callback) {
  75243. this._onrightstickchanged = callback;
  75244. };
  75245. Object.defineProperty(Gamepad.prototype, "leftStick", {
  75246. get: function () {
  75247. return this._leftStick;
  75248. },
  75249. set: function (newValues) {
  75250. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  75251. this._onleftstickchanged(newValues);
  75252. }
  75253. this._leftStick = newValues;
  75254. },
  75255. enumerable: true,
  75256. configurable: true
  75257. });
  75258. Object.defineProperty(Gamepad.prototype, "rightStick", {
  75259. get: function () {
  75260. return this._rightStick;
  75261. },
  75262. set: function (newValues) {
  75263. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  75264. this._onrightstickchanged(newValues);
  75265. }
  75266. this._rightStick = newValues;
  75267. },
  75268. enumerable: true,
  75269. configurable: true
  75270. });
  75271. Gamepad.prototype.update = function () {
  75272. if (this._leftStick) {
  75273. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  75274. if (this._invertLeftStickY) {
  75275. this.leftStick.y *= -1;
  75276. }
  75277. }
  75278. if (this._rightStick) {
  75279. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  75280. }
  75281. };
  75282. Gamepad.prototype.dispose = function () {
  75283. };
  75284. Gamepad.GAMEPAD = 0;
  75285. Gamepad.GENERIC = 1;
  75286. Gamepad.XBOX = 2;
  75287. Gamepad.POSE_ENABLED = 3;
  75288. return Gamepad;
  75289. }());
  75290. BABYLON.Gamepad = Gamepad;
  75291. var GenericPad = /** @class */ (function (_super) {
  75292. __extends(GenericPad, _super);
  75293. function GenericPad(id, index, browserGamepad) {
  75294. var _this = _super.call(this, id, index, browserGamepad) || this;
  75295. _this.onButtonDownObservable = new BABYLON.Observable();
  75296. _this.onButtonUpObservable = new BABYLON.Observable();
  75297. _this.type = Gamepad.GENERIC;
  75298. _this._buttons = new Array(browserGamepad.buttons.length);
  75299. return _this;
  75300. }
  75301. GenericPad.prototype.onbuttondown = function (callback) {
  75302. this._onbuttondown = callback;
  75303. };
  75304. GenericPad.prototype.onbuttonup = function (callback) {
  75305. this._onbuttonup = callback;
  75306. };
  75307. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  75308. if (newValue !== currentValue) {
  75309. if (newValue === 1) {
  75310. if (this._onbuttondown) {
  75311. this._onbuttondown(buttonIndex);
  75312. }
  75313. this.onButtonDownObservable.notifyObservers(buttonIndex);
  75314. }
  75315. if (newValue === 0) {
  75316. if (this._onbuttonup) {
  75317. this._onbuttonup(buttonIndex);
  75318. }
  75319. this.onButtonUpObservable.notifyObservers(buttonIndex);
  75320. }
  75321. }
  75322. return newValue;
  75323. };
  75324. GenericPad.prototype.update = function () {
  75325. _super.prototype.update.call(this);
  75326. for (var index = 0; index < this._buttons.length; index++) {
  75327. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  75328. }
  75329. };
  75330. GenericPad.prototype.dispose = function () {
  75331. _super.prototype.dispose.call(this);
  75332. this.onButtonDownObservable.clear();
  75333. this.onButtonUpObservable.clear();
  75334. };
  75335. return GenericPad;
  75336. }(Gamepad));
  75337. BABYLON.GenericPad = GenericPad;
  75338. })(BABYLON || (BABYLON = {}));
  75339. //# sourceMappingURL=babylon.gamepad.js.map
  75340. var BABYLON;
  75341. (function (BABYLON) {
  75342. /**
  75343. * Defines supported buttons for XBox360 compatible gamepads
  75344. */
  75345. var Xbox360Button;
  75346. (function (Xbox360Button) {
  75347. /** A */
  75348. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  75349. /** B */
  75350. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  75351. /** X */
  75352. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  75353. /** Y */
  75354. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  75355. /** Start */
  75356. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  75357. /** Back */
  75358. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  75359. /** Left button */
  75360. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  75361. /** Right button */
  75362. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  75363. /** Left stick */
  75364. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  75365. /** Right stick */
  75366. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  75367. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  75368. /** Defines values for XBox360 DPad */
  75369. var Xbox360Dpad;
  75370. (function (Xbox360Dpad) {
  75371. /** Up */
  75372. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  75373. /** Down */
  75374. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  75375. /** Left */
  75376. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  75377. /** Right */
  75378. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  75379. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  75380. /**
  75381. * Defines a XBox360 gamepad
  75382. */
  75383. var Xbox360Pad = /** @class */ (function (_super) {
  75384. __extends(Xbox360Pad, _super);
  75385. /**
  75386. * Creates a new XBox360 gamepad object
  75387. * @param id defines the id of this gamepad
  75388. * @param index defines its index
  75389. * @param gamepad defines the internal HTML gamepad object
  75390. * @param xboxOne defines if it is a XBox One gamepad
  75391. */
  75392. function Xbox360Pad(id, index, gamepad, xboxOne) {
  75393. if (xboxOne === void 0) { xboxOne = false; }
  75394. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  75395. _this._leftTrigger = 0;
  75396. _this._rightTrigger = 0;
  75397. /** Observable raised when a button is pressed */
  75398. _this.onButtonDownObservable = new BABYLON.Observable();
  75399. /** Observable raised when a button is released */
  75400. _this.onButtonUpObservable = new BABYLON.Observable();
  75401. /** Observable raised when a pad is pressed */
  75402. _this.onPadDownObservable = new BABYLON.Observable();
  75403. /** Observable raised when a pad is released */
  75404. _this.onPadUpObservable = new BABYLON.Observable();
  75405. _this._buttonA = 0;
  75406. _this._buttonB = 0;
  75407. _this._buttonX = 0;
  75408. _this._buttonY = 0;
  75409. _this._buttonBack = 0;
  75410. _this._buttonStart = 0;
  75411. _this._buttonLB = 0;
  75412. _this._buttonRB = 0;
  75413. _this._buttonLeftStick = 0;
  75414. _this._buttonRightStick = 0;
  75415. _this._dPadUp = 0;
  75416. _this._dPadDown = 0;
  75417. _this._dPadLeft = 0;
  75418. _this._dPadRight = 0;
  75419. _this._isXboxOnePad = false;
  75420. _this.type = BABYLON.Gamepad.XBOX;
  75421. _this._isXboxOnePad = xboxOne;
  75422. return _this;
  75423. }
  75424. /**
  75425. * Defines the callback to call when left trigger is pressed
  75426. * @param callback defines the callback to use
  75427. */
  75428. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  75429. this._onlefttriggerchanged = callback;
  75430. };
  75431. /**
  75432. * Defines the callback to call when right trigger is pressed
  75433. * @param callback defines the callback to use
  75434. */
  75435. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  75436. this._onrighttriggerchanged = callback;
  75437. };
  75438. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  75439. /**
  75440. * Gets or sets left trigger value
  75441. */
  75442. get: function () {
  75443. return this._leftTrigger;
  75444. },
  75445. set: function (newValue) {
  75446. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  75447. this._onlefttriggerchanged(newValue);
  75448. }
  75449. this._leftTrigger = newValue;
  75450. },
  75451. enumerable: true,
  75452. configurable: true
  75453. });
  75454. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  75455. /**
  75456. * Gets or sets right trigger value
  75457. */
  75458. get: function () {
  75459. return this._rightTrigger;
  75460. },
  75461. set: function (newValue) {
  75462. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  75463. this._onrighttriggerchanged(newValue);
  75464. }
  75465. this._rightTrigger = newValue;
  75466. },
  75467. enumerable: true,
  75468. configurable: true
  75469. });
  75470. /**
  75471. * Defines the callback to call when a button is pressed
  75472. * @param callback defines the callback to use
  75473. */
  75474. Xbox360Pad.prototype.onbuttondown = function (callback) {
  75475. this._onbuttondown = callback;
  75476. };
  75477. /**
  75478. * Defines the callback to call when a button is released
  75479. * @param callback defines the callback to use
  75480. */
  75481. Xbox360Pad.prototype.onbuttonup = function (callback) {
  75482. this._onbuttonup = callback;
  75483. };
  75484. /**
  75485. * Defines the callback to call when a pad is pressed
  75486. * @param callback defines the callback to use
  75487. */
  75488. Xbox360Pad.prototype.ondpaddown = function (callback) {
  75489. this._ondpaddown = callback;
  75490. };
  75491. /**
  75492. * Defines the callback to call when a pad is released
  75493. * @param callback defines the callback to use
  75494. */
  75495. Xbox360Pad.prototype.ondpadup = function (callback) {
  75496. this._ondpadup = callback;
  75497. };
  75498. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  75499. if (newValue !== currentValue) {
  75500. if (newValue === 1) {
  75501. if (this._onbuttondown) {
  75502. this._onbuttondown(buttonType);
  75503. }
  75504. this.onButtonDownObservable.notifyObservers(buttonType);
  75505. }
  75506. if (newValue === 0) {
  75507. if (this._onbuttonup) {
  75508. this._onbuttonup(buttonType);
  75509. }
  75510. this.onButtonUpObservable.notifyObservers(buttonType);
  75511. }
  75512. }
  75513. return newValue;
  75514. };
  75515. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  75516. if (newValue !== currentValue) {
  75517. if (newValue === 1) {
  75518. if (this._ondpaddown) {
  75519. this._ondpaddown(buttonType);
  75520. }
  75521. this.onPadDownObservable.notifyObservers(buttonType);
  75522. }
  75523. if (newValue === 0) {
  75524. if (this._ondpadup) {
  75525. this._ondpadup(buttonType);
  75526. }
  75527. this.onPadUpObservable.notifyObservers(buttonType);
  75528. }
  75529. }
  75530. return newValue;
  75531. };
  75532. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  75533. /** Gets or sets value of A button */
  75534. get: function () {
  75535. return this._buttonA;
  75536. },
  75537. set: function (value) {
  75538. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  75539. },
  75540. enumerable: true,
  75541. configurable: true
  75542. });
  75543. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  75544. /** Gets or sets value of B button */
  75545. get: function () {
  75546. return this._buttonB;
  75547. },
  75548. set: function (value) {
  75549. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  75550. },
  75551. enumerable: true,
  75552. configurable: true
  75553. });
  75554. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  75555. /** Gets or sets value of X button */
  75556. get: function () {
  75557. return this._buttonX;
  75558. },
  75559. set: function (value) {
  75560. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  75561. },
  75562. enumerable: true,
  75563. configurable: true
  75564. });
  75565. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  75566. /** Gets or sets value of Y button */
  75567. get: function () {
  75568. return this._buttonY;
  75569. },
  75570. set: function (value) {
  75571. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  75572. },
  75573. enumerable: true,
  75574. configurable: true
  75575. });
  75576. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  75577. /** Gets or sets value of Start button */
  75578. get: function () {
  75579. return this._buttonStart;
  75580. },
  75581. set: function (value) {
  75582. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  75583. },
  75584. enumerable: true,
  75585. configurable: true
  75586. });
  75587. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  75588. /** Gets or sets value of Back button */
  75589. get: function () {
  75590. return this._buttonBack;
  75591. },
  75592. set: function (value) {
  75593. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  75594. },
  75595. enumerable: true,
  75596. configurable: true
  75597. });
  75598. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  75599. /** Gets or sets value of Left button */
  75600. get: function () {
  75601. return this._buttonLB;
  75602. },
  75603. set: function (value) {
  75604. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  75605. },
  75606. enumerable: true,
  75607. configurable: true
  75608. });
  75609. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  75610. /** Gets or sets value of Right button */
  75611. get: function () {
  75612. return this._buttonRB;
  75613. },
  75614. set: function (value) {
  75615. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  75616. },
  75617. enumerable: true,
  75618. configurable: true
  75619. });
  75620. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  75621. /** Gets or sets value of left stick */
  75622. get: function () {
  75623. return this._buttonLeftStick;
  75624. },
  75625. set: function (value) {
  75626. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  75627. },
  75628. enumerable: true,
  75629. configurable: true
  75630. });
  75631. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  75632. /** Gets or sets value of right stick */
  75633. get: function () {
  75634. return this._buttonRightStick;
  75635. },
  75636. set: function (value) {
  75637. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  75638. },
  75639. enumerable: true,
  75640. configurable: true
  75641. });
  75642. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  75643. /** Gets or sets value of DPad up */
  75644. get: function () {
  75645. return this._dPadUp;
  75646. },
  75647. set: function (value) {
  75648. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  75649. },
  75650. enumerable: true,
  75651. configurable: true
  75652. });
  75653. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  75654. /** Gets or sets value of DPad down */
  75655. get: function () {
  75656. return this._dPadDown;
  75657. },
  75658. set: function (value) {
  75659. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  75660. },
  75661. enumerable: true,
  75662. configurable: true
  75663. });
  75664. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  75665. /** Gets or sets value of DPad left */
  75666. get: function () {
  75667. return this._dPadLeft;
  75668. },
  75669. set: function (value) {
  75670. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  75671. },
  75672. enumerable: true,
  75673. configurable: true
  75674. });
  75675. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  75676. /** Gets or sets value of DPad right */
  75677. get: function () {
  75678. return this._dPadRight;
  75679. },
  75680. set: function (value) {
  75681. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  75682. },
  75683. enumerable: true,
  75684. configurable: true
  75685. });
  75686. /**
  75687. * Force the gamepad to synchronize with device values
  75688. */
  75689. Xbox360Pad.prototype.update = function () {
  75690. _super.prototype.update.call(this);
  75691. if (this._isXboxOnePad) {
  75692. this.buttonA = this.browserGamepad.buttons[0].value;
  75693. this.buttonB = this.browserGamepad.buttons[1].value;
  75694. this.buttonX = this.browserGamepad.buttons[2].value;
  75695. this.buttonY = this.browserGamepad.buttons[3].value;
  75696. this.buttonLB = this.browserGamepad.buttons[4].value;
  75697. this.buttonRB = this.browserGamepad.buttons[5].value;
  75698. this.leftTrigger = this.browserGamepad.axes[2];
  75699. this.rightTrigger = this.browserGamepad.axes[5];
  75700. this.buttonBack = this.browserGamepad.buttons[9].value;
  75701. this.buttonStart = this.browserGamepad.buttons[8].value;
  75702. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  75703. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  75704. this.dPadUp = this.browserGamepad.buttons[11].value;
  75705. this.dPadDown = this.browserGamepad.buttons[12].value;
  75706. this.dPadLeft = this.browserGamepad.buttons[13].value;
  75707. this.dPadRight = this.browserGamepad.buttons[14].value;
  75708. }
  75709. else {
  75710. this.buttonA = this.browserGamepad.buttons[0].value;
  75711. this.buttonB = this.browserGamepad.buttons[1].value;
  75712. this.buttonX = this.browserGamepad.buttons[2].value;
  75713. this.buttonY = this.browserGamepad.buttons[3].value;
  75714. this.buttonLB = this.browserGamepad.buttons[4].value;
  75715. this.buttonRB = this.browserGamepad.buttons[5].value;
  75716. this.leftTrigger = this.browserGamepad.buttons[6].value;
  75717. this.rightTrigger = this.browserGamepad.buttons[7].value;
  75718. this.buttonBack = this.browserGamepad.buttons[8].value;
  75719. this.buttonStart = this.browserGamepad.buttons[9].value;
  75720. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  75721. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  75722. this.dPadUp = this.browserGamepad.buttons[12].value;
  75723. this.dPadDown = this.browserGamepad.buttons[13].value;
  75724. this.dPadLeft = this.browserGamepad.buttons[14].value;
  75725. this.dPadRight = this.browserGamepad.buttons[15].value;
  75726. }
  75727. };
  75728. Xbox360Pad.prototype.dispose = function () {
  75729. _super.prototype.dispose.call(this);
  75730. this.onButtonDownObservable.clear();
  75731. this.onButtonUpObservable.clear();
  75732. this.onPadDownObservable.clear();
  75733. this.onPadUpObservable.clear();
  75734. };
  75735. return Xbox360Pad;
  75736. }(BABYLON.Gamepad));
  75737. BABYLON.Xbox360Pad = Xbox360Pad;
  75738. })(BABYLON || (BABYLON = {}));
  75739. //# sourceMappingURL=babylon.xboxGamepad.js.map
  75740. var BABYLON;
  75741. (function (BABYLON) {
  75742. /**
  75743. * Defines the types of pose enabled controllers that are supported
  75744. */
  75745. var PoseEnabledControllerType;
  75746. (function (PoseEnabledControllerType) {
  75747. /**
  75748. * HTC Vive
  75749. */
  75750. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  75751. /**
  75752. * Oculus Rift
  75753. */
  75754. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  75755. /**
  75756. * Windows mixed reality
  75757. */
  75758. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  75759. /**
  75760. * Samsung gear VR
  75761. */
  75762. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  75763. /**
  75764. * Google Daydream
  75765. */
  75766. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  75767. /**
  75768. * Generic
  75769. */
  75770. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  75771. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  75772. /**
  75773. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  75774. */
  75775. var PoseEnabledControllerHelper = /** @class */ (function () {
  75776. function PoseEnabledControllerHelper() {
  75777. }
  75778. /**
  75779. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  75780. * @param vrGamepad the gamepad to initialized
  75781. * @returns a vr controller of the type the gamepad identified as
  75782. */
  75783. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  75784. // Oculus Touch
  75785. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  75786. return new BABYLON.OculusTouchController(vrGamepad);
  75787. }
  75788. // Windows Mixed Reality controllers
  75789. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  75790. return new BABYLON.WindowsMotionController(vrGamepad);
  75791. }
  75792. // HTC Vive
  75793. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  75794. return new BABYLON.ViveController(vrGamepad);
  75795. }
  75796. // Samsung/Oculus Gear VR or Oculus Go
  75797. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  75798. return new BABYLON.GearVRController(vrGamepad);
  75799. }
  75800. // Google Daydream
  75801. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  75802. return new BABYLON.DaydreamController(vrGamepad);
  75803. }
  75804. // Generic
  75805. else {
  75806. return new BABYLON.GenericController(vrGamepad);
  75807. }
  75808. };
  75809. return PoseEnabledControllerHelper;
  75810. }());
  75811. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  75812. /**
  75813. * Defines the PoseEnabledController object that contains state of a vr capable controller
  75814. */
  75815. var PoseEnabledController = /** @class */ (function (_super) {
  75816. __extends(PoseEnabledController, _super);
  75817. /**
  75818. * Creates a new PoseEnabledController from a gamepad
  75819. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  75820. */
  75821. function PoseEnabledController(browserGamepad) {
  75822. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  75823. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  75824. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  75825. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  75826. /**
  75827. * The device position in babylon space
  75828. */
  75829. _this.devicePosition = BABYLON.Vector3.Zero();
  75830. /**
  75831. * The device rotation in babylon space
  75832. */
  75833. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  75834. /**
  75835. * The scale factor of the device in babylon space
  75836. */
  75837. _this.deviceScaleFactor = 1;
  75838. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  75839. /**
  75840. * Internal, matrix used to convert room space to babylon space
  75841. * @hidden
  75842. */
  75843. _this._deviceToWorld = BABYLON.Matrix.Identity();
  75844. /**
  75845. * Node to be used when casting a ray from the controller
  75846. * @hidden
  75847. */
  75848. _this._pointingPoseNode = null;
  75849. _this._workingMatrix = BABYLON.Matrix.Identity();
  75850. /**
  75851. * @hidden
  75852. */
  75853. _this._meshAttachedObservable = new BABYLON.Observable();
  75854. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  75855. _this.controllerType = PoseEnabledControllerType.GENERIC;
  75856. _this.position = BABYLON.Vector3.Zero();
  75857. _this.rotationQuaternion = new BABYLON.Quaternion();
  75858. _this._calculatedPosition = BABYLON.Vector3.Zero();
  75859. _this._calculatedRotation = new BABYLON.Quaternion();
  75860. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  75861. return _this;
  75862. }
  75863. /**
  75864. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  75865. */
  75866. PoseEnabledController.prototype.update = function () {
  75867. _super.prototype.update.call(this);
  75868. this._updatePoseAndMesh();
  75869. };
  75870. /**
  75871. * Updates only the pose device and mesh without doing any button event checking
  75872. */
  75873. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  75874. var pose = this.browserGamepad.pose;
  75875. this.updateFromDevice(pose);
  75876. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  75877. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  75878. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  75879. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  75880. if (this._mesh) {
  75881. this._mesh.position.copyFrom(this.devicePosition);
  75882. if (this._mesh.rotationQuaternion) {
  75883. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  75884. }
  75885. }
  75886. };
  75887. /**
  75888. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  75889. * @param poseData raw pose fromthe device
  75890. */
  75891. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  75892. if (poseData) {
  75893. this.rawPose = poseData;
  75894. if (poseData.position) {
  75895. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  75896. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  75897. this._deviceRoomPosition.z *= -1;
  75898. }
  75899. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  75900. this._calculatedPosition.addInPlace(this.position);
  75901. }
  75902. var pose = this.rawPose;
  75903. if (poseData.orientation && pose.orientation) {
  75904. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  75905. if (this._mesh) {
  75906. if (this._mesh.getScene().useRightHandedSystem) {
  75907. this._deviceRoomRotationQuaternion.z *= -1;
  75908. this._deviceRoomRotationQuaternion.w *= -1;
  75909. }
  75910. else {
  75911. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  75912. }
  75913. }
  75914. // if the camera is set, rotate to the camera's rotation
  75915. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  75916. }
  75917. }
  75918. };
  75919. /**
  75920. * Attaches a mesh to the controller
  75921. * @param mesh the mesh to be attached
  75922. */
  75923. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  75924. if (this._mesh) {
  75925. this._mesh.parent = null;
  75926. }
  75927. this._mesh = mesh;
  75928. if (this._poseControlledCamera) {
  75929. this._mesh.parent = this._poseControlledCamera;
  75930. }
  75931. if (!this._mesh.rotationQuaternion) {
  75932. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  75933. }
  75934. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  75935. this._updatePoseAndMesh();
  75936. if (this._pointingPoseNode) {
  75937. var parents = [];
  75938. var obj = this._pointingPoseNode;
  75939. while (obj.parent) {
  75940. parents.push(obj.parent);
  75941. obj = obj.parent;
  75942. }
  75943. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  75944. }
  75945. this._meshAttachedObservable.notifyObservers(mesh);
  75946. };
  75947. /**
  75948. * Attaches the controllers mesh to a camera
  75949. * @param camera the camera the mesh should be attached to
  75950. */
  75951. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  75952. this._poseControlledCamera = camera;
  75953. if (this._mesh) {
  75954. this._mesh.parent = this._poseControlledCamera;
  75955. }
  75956. };
  75957. /**
  75958. * Disposes of the controller
  75959. */
  75960. PoseEnabledController.prototype.dispose = function () {
  75961. if (this._mesh) {
  75962. this._mesh.dispose();
  75963. }
  75964. this._mesh = null;
  75965. _super.prototype.dispose.call(this);
  75966. };
  75967. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  75968. /**
  75969. * The mesh that is attached to the controller
  75970. */
  75971. get: function () {
  75972. return this._mesh;
  75973. },
  75974. enumerable: true,
  75975. configurable: true
  75976. });
  75977. /**
  75978. * Gets the ray of the controller in the direction the controller is pointing
  75979. * @param length the length the resulting ray should be
  75980. * @returns a ray in the direction the controller is pointing
  75981. */
  75982. PoseEnabledController.prototype.getForwardRay = function (length) {
  75983. if (length === void 0) { length = 100; }
  75984. if (!this.mesh) {
  75985. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  75986. }
  75987. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  75988. var origin = m.getTranslation();
  75989. var forward = new BABYLON.Vector3(0, 0, -1);
  75990. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  75991. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  75992. return new BABYLON.Ray(origin, direction, length);
  75993. };
  75994. /**
  75995. * Name of the child mesh that can be used to cast a ray from the controller
  75996. */
  75997. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  75998. return PoseEnabledController;
  75999. }(BABYLON.Gamepad));
  76000. BABYLON.PoseEnabledController = PoseEnabledController;
  76001. })(BABYLON || (BABYLON = {}));
  76002. //# sourceMappingURL=babylon.poseEnabledController.js.map
  76003. var BABYLON;
  76004. (function (BABYLON) {
  76005. /**
  76006. * Defines the WebVRController object that represents controllers tracked in 3D space
  76007. */
  76008. var WebVRController = /** @class */ (function (_super) {
  76009. __extends(WebVRController, _super);
  76010. /**
  76011. * Creates a new WebVRController from a gamepad
  76012. * @param vrGamepad the gamepad that the WebVRController should be created from
  76013. */
  76014. function WebVRController(vrGamepad) {
  76015. var _this = _super.call(this, vrGamepad) || this;
  76016. // Observables
  76017. /**
  76018. * Fired when the trigger state has changed
  76019. */
  76020. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  76021. /**
  76022. * Fired when the main button state has changed
  76023. */
  76024. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  76025. /**
  76026. * Fired when the secondary button state has changed
  76027. */
  76028. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  76029. /**
  76030. * Fired when the pad state has changed
  76031. */
  76032. _this.onPadStateChangedObservable = new BABYLON.Observable();
  76033. /**
  76034. * Fired when controllers stick values have changed
  76035. */
  76036. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  76037. /**
  76038. * X and Y axis corrisponding to the controllers joystick
  76039. */
  76040. _this.pad = { x: 0, y: 0 };
  76041. // avoid GC, store state in a tmp object
  76042. _this._changes = {
  76043. pressChanged: false,
  76044. touchChanged: false,
  76045. valueChanged: false,
  76046. changed: false
  76047. };
  76048. _this._buttons = new Array(vrGamepad.buttons.length);
  76049. _this.hand = vrGamepad.hand;
  76050. return _this;
  76051. }
  76052. /**
  76053. * Fired when a controller button's state has changed
  76054. * @param callback the callback containing the button that was modified
  76055. */
  76056. WebVRController.prototype.onButtonStateChange = function (callback) {
  76057. this._onButtonStateChange = callback;
  76058. };
  76059. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  76060. /**
  76061. * The default controller model for the controller
  76062. */
  76063. get: function () {
  76064. return this._defaultModel;
  76065. },
  76066. enumerable: true,
  76067. configurable: true
  76068. });
  76069. /**
  76070. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  76071. */
  76072. WebVRController.prototype.update = function () {
  76073. _super.prototype.update.call(this);
  76074. for (var index = 0; index < this._buttons.length; index++) {
  76075. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  76076. }
  76077. ;
  76078. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  76079. this.pad.x = this.leftStick.x;
  76080. this.pad.y = this.leftStick.y;
  76081. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  76082. }
  76083. };
  76084. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  76085. if (!newState) {
  76086. newState = {
  76087. pressed: false,
  76088. touched: false,
  76089. value: 0
  76090. };
  76091. }
  76092. if (!currentState) {
  76093. this._buttons[buttonIndex] = {
  76094. pressed: newState.pressed,
  76095. touched: newState.touched,
  76096. value: newState.value
  76097. };
  76098. return;
  76099. }
  76100. this._checkChanges(newState, currentState);
  76101. if (this._changes.changed) {
  76102. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  76103. this._handleButtonChange(buttonIndex, newState, this._changes);
  76104. }
  76105. this._buttons[buttonIndex].pressed = newState.pressed;
  76106. this._buttons[buttonIndex].touched = newState.touched;
  76107. // oculus triggers are never 0, thou not touched.
  76108. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  76109. };
  76110. WebVRController.prototype._checkChanges = function (newState, currentState) {
  76111. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  76112. this._changes.touchChanged = newState.touched !== currentState.touched;
  76113. this._changes.valueChanged = newState.value !== currentState.value;
  76114. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  76115. return this._changes;
  76116. };
  76117. /**
  76118. * Disposes of th webVRCOntroller
  76119. */
  76120. WebVRController.prototype.dispose = function () {
  76121. _super.prototype.dispose.call(this);
  76122. this.onTriggerStateChangedObservable.clear();
  76123. this.onMainButtonStateChangedObservable.clear();
  76124. this.onSecondaryButtonStateChangedObservable.clear();
  76125. this.onPadStateChangedObservable.clear();
  76126. this.onPadValuesChangedObservable.clear();
  76127. };
  76128. return WebVRController;
  76129. }(BABYLON.PoseEnabledController));
  76130. BABYLON.WebVRController = WebVRController;
  76131. })(BABYLON || (BABYLON = {}));
  76132. //# sourceMappingURL=babylon.webVRController.js.map
  76133. var BABYLON;
  76134. (function (BABYLON) {
  76135. /**
  76136. * Oculus Touch Controller
  76137. */
  76138. var OculusTouchController = /** @class */ (function (_super) {
  76139. __extends(OculusTouchController, _super);
  76140. /**
  76141. * Creates a new OculusTouchController from a gamepad
  76142. * @param vrGamepad the gamepad that the controller should be created from
  76143. */
  76144. function OculusTouchController(vrGamepad) {
  76145. var _this = _super.call(this, vrGamepad) || this;
  76146. /**
  76147. * Fired when the secondary trigger on this controller is modified
  76148. */
  76149. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  76150. /**
  76151. * Fired when the thumb rest on this controller is modified
  76152. */
  76153. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  76154. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  76155. return _this;
  76156. }
  76157. /**
  76158. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76159. * @param scene scene in which to add meshes
  76160. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76161. */
  76162. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76163. var _this = this;
  76164. var meshName;
  76165. // Hand
  76166. if (this.hand === 'left') {
  76167. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  76168. }
  76169. else { // Right is the default if no hand is specified
  76170. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  76171. }
  76172. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  76173. /*
  76174. Parent Mesh name: oculus_touch_left
  76175. - body
  76176. - trigger
  76177. - thumbstick
  76178. - grip
  76179. - button_y
  76180. - button_x
  76181. - button_enter
  76182. */
  76183. _this._defaultModel = newMeshes[1];
  76184. _this.attachToMesh(_this._defaultModel);
  76185. if (meshLoaded) {
  76186. meshLoaded(_this._defaultModel);
  76187. }
  76188. });
  76189. };
  76190. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  76191. /**
  76192. * Fired when the A button on this controller is modified
  76193. */
  76194. get: function () {
  76195. if (this.hand === 'right') {
  76196. return this.onMainButtonStateChangedObservable;
  76197. }
  76198. else {
  76199. throw new Error('No A button on left hand');
  76200. }
  76201. },
  76202. enumerable: true,
  76203. configurable: true
  76204. });
  76205. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  76206. /**
  76207. * Fired when the B button on this controller is modified
  76208. */
  76209. get: function () {
  76210. if (this.hand === 'right') {
  76211. return this.onSecondaryButtonStateChangedObservable;
  76212. }
  76213. else {
  76214. throw new Error('No B button on left hand');
  76215. }
  76216. },
  76217. enumerable: true,
  76218. configurable: true
  76219. });
  76220. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  76221. /**
  76222. * Fired when the X button on this controller is modified
  76223. */
  76224. get: function () {
  76225. if (this.hand === 'left') {
  76226. return this.onMainButtonStateChangedObservable;
  76227. }
  76228. else {
  76229. throw new Error('No X button on right hand');
  76230. }
  76231. },
  76232. enumerable: true,
  76233. configurable: true
  76234. });
  76235. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  76236. /**
  76237. * Fired when the Y button on this controller is modified
  76238. */
  76239. get: function () {
  76240. if (this.hand === 'left') {
  76241. return this.onSecondaryButtonStateChangedObservable;
  76242. }
  76243. else {
  76244. throw new Error('No Y button on right hand');
  76245. }
  76246. },
  76247. enumerable: true,
  76248. configurable: true
  76249. });
  76250. /**
  76251. * Called once for each button that changed state since the last frame
  76252. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  76253. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  76254. * 2) secondary trigger (same)
  76255. * 3) A (right) X (left), touch, pressed = value
  76256. * 4) B / Y
  76257. * 5) thumb rest
  76258. * @param buttonIdx Which button index changed
  76259. * @param state New state of the button
  76260. * @param changes Which properties on the state changed since last frame
  76261. */
  76262. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76263. var notifyObject = state; //{ state: state, changes: changes };
  76264. var triggerDirection = this.hand === 'right' ? -1 : 1;
  76265. switch (buttonIdx) {
  76266. case 0:
  76267. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  76268. return;
  76269. case 1: // index trigger
  76270. if (this._defaultModel) {
  76271. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  76272. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  76273. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  76274. }
  76275. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  76276. return;
  76277. case 2: // secondary trigger
  76278. if (this._defaultModel) {
  76279. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  76280. }
  76281. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  76282. return;
  76283. case 3:
  76284. if (this._defaultModel) {
  76285. if (notifyObject.pressed) {
  76286. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  76287. }
  76288. else {
  76289. (this._defaultModel.getChildren()[1]).position.y = 0;
  76290. }
  76291. }
  76292. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  76293. return;
  76294. case 4:
  76295. if (this._defaultModel) {
  76296. if (notifyObject.pressed) {
  76297. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  76298. }
  76299. else {
  76300. (this._defaultModel.getChildren()[2]).position.y = 0;
  76301. }
  76302. }
  76303. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  76304. return;
  76305. case 5:
  76306. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  76307. return;
  76308. }
  76309. };
  76310. /**
  76311. * Base Url for the controller model.
  76312. */
  76313. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  76314. /**
  76315. * File name for the left controller model.
  76316. */
  76317. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  76318. /**
  76319. * File name for the right controller model.
  76320. */
  76321. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  76322. return OculusTouchController;
  76323. }(BABYLON.WebVRController));
  76324. BABYLON.OculusTouchController = OculusTouchController;
  76325. })(BABYLON || (BABYLON = {}));
  76326. //# sourceMappingURL=babylon.oculusTouchController.js.map
  76327. var BABYLON;
  76328. (function (BABYLON) {
  76329. /**
  76330. * Vive Controller
  76331. */
  76332. var ViveController = /** @class */ (function (_super) {
  76333. __extends(ViveController, _super);
  76334. /**
  76335. * Creates a new ViveController from a gamepad
  76336. * @param vrGamepad the gamepad that the controller should be created from
  76337. */
  76338. function ViveController(vrGamepad) {
  76339. var _this = _super.call(this, vrGamepad) || this;
  76340. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  76341. _this._invertLeftStickY = true;
  76342. return _this;
  76343. }
  76344. /**
  76345. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76346. * @param scene scene in which to add meshes
  76347. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76348. */
  76349. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76350. var _this = this;
  76351. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  76352. /*
  76353. Parent Mesh name: ViveWand
  76354. - body
  76355. - r_gripper
  76356. - l_gripper
  76357. - menu_button
  76358. - system_button
  76359. - trackpad
  76360. - trigger
  76361. - LED
  76362. */
  76363. _this._defaultModel = newMeshes[1];
  76364. _this.attachToMesh(_this._defaultModel);
  76365. if (meshLoaded) {
  76366. meshLoaded(_this._defaultModel);
  76367. }
  76368. });
  76369. };
  76370. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  76371. /**
  76372. * Fired when the left button on this controller is modified
  76373. */
  76374. get: function () {
  76375. return this.onMainButtonStateChangedObservable;
  76376. },
  76377. enumerable: true,
  76378. configurable: true
  76379. });
  76380. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  76381. /**
  76382. * Fired when the right button on this controller is modified
  76383. */
  76384. get: function () {
  76385. return this.onMainButtonStateChangedObservable;
  76386. },
  76387. enumerable: true,
  76388. configurable: true
  76389. });
  76390. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  76391. /**
  76392. * Fired when the menu button on this controller is modified
  76393. */
  76394. get: function () {
  76395. return this.onSecondaryButtonStateChangedObservable;
  76396. },
  76397. enumerable: true,
  76398. configurable: true
  76399. });
  76400. /**
  76401. * Called once for each button that changed state since the last frame
  76402. * Vive mapping:
  76403. * 0: touchpad
  76404. * 1: trigger
  76405. * 2: left AND right buttons
  76406. * 3: menu button
  76407. * @param buttonIdx Which button index changed
  76408. * @param state New state of the button
  76409. * @param changes Which properties on the state changed since last frame
  76410. */
  76411. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76412. var notifyObject = state; //{ state: state, changes: changes };
  76413. switch (buttonIdx) {
  76414. case 0:
  76415. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  76416. return;
  76417. case 1: // index trigger
  76418. if (this._defaultModel) {
  76419. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  76420. }
  76421. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  76422. return;
  76423. case 2: // left AND right button
  76424. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  76425. return;
  76426. case 3:
  76427. if (this._defaultModel) {
  76428. if (notifyObject.pressed) {
  76429. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  76430. }
  76431. else {
  76432. (this._defaultModel.getChildren()[2]).position.y = 0;
  76433. }
  76434. }
  76435. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  76436. return;
  76437. }
  76438. };
  76439. /**
  76440. * Base Url for the controller model.
  76441. */
  76442. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  76443. /**
  76444. * File name for the controller model.
  76445. */
  76446. ViveController.MODEL_FILENAME = 'wand.babylon';
  76447. return ViveController;
  76448. }(BABYLON.WebVRController));
  76449. BABYLON.ViveController = ViveController;
  76450. })(BABYLON || (BABYLON = {}));
  76451. //# sourceMappingURL=babylon.viveController.js.map
  76452. var BABYLON;
  76453. (function (BABYLON) {
  76454. /**
  76455. * Generic Controller
  76456. */
  76457. var GenericController = /** @class */ (function (_super) {
  76458. __extends(GenericController, _super);
  76459. /**
  76460. * Creates a new GenericController from a gamepad
  76461. * @param vrGamepad the gamepad that the controller should be created from
  76462. */
  76463. function GenericController(vrGamepad) {
  76464. return _super.call(this, vrGamepad) || this;
  76465. }
  76466. /**
  76467. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76468. * @param scene scene in which to add meshes
  76469. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76470. */
  76471. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76472. var _this = this;
  76473. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  76474. _this._defaultModel = newMeshes[1];
  76475. _this.attachToMesh(_this._defaultModel);
  76476. if (meshLoaded) {
  76477. meshLoaded(_this._defaultModel);
  76478. }
  76479. });
  76480. };
  76481. /**
  76482. * Called once for each button that changed state since the last frame
  76483. * @param buttonIdx Which button index changed
  76484. * @param state New state of the button
  76485. * @param changes Which properties on the state changed since last frame
  76486. */
  76487. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76488. console.log("Button id: " + buttonIdx + "state: ");
  76489. console.dir(state);
  76490. };
  76491. /**
  76492. * Base Url for the controller model.
  76493. */
  76494. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76495. /**
  76496. * File name for the controller model.
  76497. */
  76498. GenericController.MODEL_FILENAME = 'generic.babylon';
  76499. return GenericController;
  76500. }(BABYLON.WebVRController));
  76501. BABYLON.GenericController = GenericController;
  76502. })(BABYLON || (BABYLON = {}));
  76503. //# sourceMappingURL=babylon.genericController.js.map
  76504. var BABYLON;
  76505. (function (BABYLON) {
  76506. /**
  76507. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  76508. */
  76509. var LoadedMeshInfo = /** @class */ (function () {
  76510. function LoadedMeshInfo() {
  76511. /**
  76512. * Map of the button meshes contained in the controller
  76513. */
  76514. this.buttonMeshes = {};
  76515. /**
  76516. * Map of the axis meshes contained in the controller
  76517. */
  76518. this.axisMeshes = {};
  76519. }
  76520. return LoadedMeshInfo;
  76521. }());
  76522. /**
  76523. * Defines the WindowsMotionController object that the state of the windows motion controller
  76524. */
  76525. var WindowsMotionController = /** @class */ (function (_super) {
  76526. __extends(WindowsMotionController, _super);
  76527. /**
  76528. * Creates a new WindowsMotionController from a gamepad
  76529. * @param vrGamepad the gamepad that the controller should be created from
  76530. */
  76531. function WindowsMotionController(vrGamepad) {
  76532. var _this = _super.call(this, vrGamepad) || this;
  76533. _this._mapping = {
  76534. // Semantic button names
  76535. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  76536. // A mapping of the button name to glTF model node name
  76537. // that should be transformed by button value.
  76538. buttonMeshNames: {
  76539. 'trigger': 'SELECT',
  76540. 'menu': 'MENU',
  76541. 'grip': 'GRASP',
  76542. 'thumbstick': 'THUMBSTICK_PRESS',
  76543. 'trackpad': 'TOUCHPAD_PRESS'
  76544. },
  76545. // This mapping is used to translate from the Motion Controller to Babylon semantics
  76546. buttonObservableNames: {
  76547. 'trigger': 'onTriggerStateChangedObservable',
  76548. 'menu': 'onSecondaryButtonStateChangedObservable',
  76549. 'grip': 'onMainButtonStateChangedObservable',
  76550. 'thumbstick': 'onPadStateChangedObservable',
  76551. 'trackpad': 'onTrackpadChangedObservable'
  76552. },
  76553. // A mapping of the axis name to glTF model node name
  76554. // that should be transformed by axis value.
  76555. // This array mirrors the browserGamepad.axes array, such that
  76556. // the mesh corresponding to axis 0 is in this array index 0.
  76557. axisMeshNames: [
  76558. 'THUMBSTICK_X',
  76559. 'THUMBSTICK_Y',
  76560. 'TOUCHPAD_TOUCH_X',
  76561. 'TOUCHPAD_TOUCH_Y'
  76562. ],
  76563. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  76564. };
  76565. /**
  76566. * Fired when the trackpad on this controller is clicked
  76567. */
  76568. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  76569. /**
  76570. * Fired when the trackpad on this controller is modified
  76571. */
  76572. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  76573. /**
  76574. * The current x and y values of this controller's trackpad
  76575. */
  76576. _this.trackpad = { x: 0, y: 0 };
  76577. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  76578. _this._loadedMeshInfo = null;
  76579. return _this;
  76580. }
  76581. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  76582. /**
  76583. * Fired when the trigger on this controller is modified
  76584. */
  76585. get: function () {
  76586. return this.onTriggerStateChangedObservable;
  76587. },
  76588. enumerable: true,
  76589. configurable: true
  76590. });
  76591. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  76592. /**
  76593. * Fired when the menu button on this controller is modified
  76594. */
  76595. get: function () {
  76596. return this.onSecondaryButtonStateChangedObservable;
  76597. },
  76598. enumerable: true,
  76599. configurable: true
  76600. });
  76601. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  76602. /**
  76603. * Fired when the grip button on this controller is modified
  76604. */
  76605. get: function () {
  76606. return this.onMainButtonStateChangedObservable;
  76607. },
  76608. enumerable: true,
  76609. configurable: true
  76610. });
  76611. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  76612. /**
  76613. * Fired when the thumbstick button on this controller is modified
  76614. */
  76615. get: function () {
  76616. return this.onPadStateChangedObservable;
  76617. },
  76618. enumerable: true,
  76619. configurable: true
  76620. });
  76621. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  76622. /**
  76623. * Fired when the touchpad button on this controller is modified
  76624. */
  76625. get: function () {
  76626. return this.onTrackpadChangedObservable;
  76627. },
  76628. enumerable: true,
  76629. configurable: true
  76630. });
  76631. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  76632. /**
  76633. * Fired when the touchpad values on this controller are modified
  76634. */
  76635. get: function () {
  76636. return this.onTrackpadValuesChangedObservable;
  76637. },
  76638. enumerable: true,
  76639. configurable: true
  76640. });
  76641. WindowsMotionController.prototype._updateTrackpad = function () {
  76642. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  76643. this.trackpad.x = this.browserGamepad["axes"][2];
  76644. this.trackpad.y = this.browserGamepad["axes"][3];
  76645. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  76646. }
  76647. };
  76648. /**
  76649. * Called once per frame by the engine.
  76650. */
  76651. WindowsMotionController.prototype.update = function () {
  76652. _super.prototype.update.call(this);
  76653. if (this.browserGamepad.axes) {
  76654. this._updateTrackpad();
  76655. // Only need to animate axes if there is a loaded mesh
  76656. if (this._loadedMeshInfo) {
  76657. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  76658. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  76659. }
  76660. }
  76661. }
  76662. };
  76663. /**
  76664. * Called once for each button that changed state since the last frame
  76665. * @param buttonIdx Which button index changed
  76666. * @param state New state of the button
  76667. * @param changes Which properties on the state changed since last frame
  76668. */
  76669. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76670. var buttonName = this._mapping.buttons[buttonIdx];
  76671. if (!buttonName) {
  76672. return;
  76673. }
  76674. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  76675. this._updateTrackpad();
  76676. // Only emit events for buttons that we know how to map from index to name
  76677. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  76678. if (observable) {
  76679. observable.notifyObservers(state);
  76680. }
  76681. this._lerpButtonTransform(buttonName, state.value);
  76682. };
  76683. /**
  76684. * Moves the buttons on the controller mesh based on their current state
  76685. * @param buttonName the name of the button to move
  76686. * @param buttonValue the value of the button which determines the buttons new position
  76687. */
  76688. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  76689. // If there is no loaded mesh, there is nothing to transform.
  76690. if (!this._loadedMeshInfo) {
  76691. return;
  76692. }
  76693. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  76694. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  76695. return;
  76696. }
  76697. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  76698. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  76699. };
  76700. /**
  76701. * Moves the axis on the controller mesh based on its current state
  76702. * @param axis the index of the axis
  76703. * @param axisValue the value of the axis which determines the meshes new position
  76704. * @hidden
  76705. */
  76706. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  76707. if (!this._loadedMeshInfo) {
  76708. return;
  76709. }
  76710. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  76711. if (!meshInfo) {
  76712. return;
  76713. }
  76714. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  76715. return;
  76716. }
  76717. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  76718. var lerpValue = axisValue * 0.5 + 0.5;
  76719. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  76720. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  76721. };
  76722. /**
  76723. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76724. * @param scene scene in which to add meshes
  76725. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76726. */
  76727. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  76728. var _this = this;
  76729. if (forceDefault === void 0) { forceDefault = false; }
  76730. var path;
  76731. var filename;
  76732. // Checking if GLB loader is present
  76733. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  76734. // Determine the device specific folder based on the ID suffix
  76735. var device = 'default';
  76736. if (this.id && !forceDefault) {
  76737. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  76738. device = ((match && match[0]) || device);
  76739. }
  76740. // Hand
  76741. if (this.hand === 'left') {
  76742. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  76743. }
  76744. else { // Right is the default if no hand is specified
  76745. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  76746. }
  76747. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  76748. }
  76749. else {
  76750. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  76751. path = BABYLON.GenericController.MODEL_BASE_URL;
  76752. filename = BABYLON.GenericController.MODEL_FILENAME;
  76753. }
  76754. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  76755. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  76756. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  76757. if (!_this._loadedMeshInfo) {
  76758. return;
  76759. }
  76760. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  76761. _this.attachToMesh(_this._defaultModel);
  76762. if (meshLoaded) {
  76763. meshLoaded(_this._defaultModel);
  76764. }
  76765. }, null, function (scene, message) {
  76766. BABYLON.Tools.Log(message);
  76767. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  76768. if (!forceDefault) {
  76769. _this.initControllerMesh(scene, meshLoaded, true);
  76770. }
  76771. });
  76772. };
  76773. /**
  76774. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  76775. * can be transformed by button presses and axes values, based on this._mapping.
  76776. *
  76777. * @param scene scene in which the meshes exist
  76778. * @param meshes list of meshes that make up the controller model to process
  76779. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  76780. */
  76781. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  76782. var loadedMeshInfo = null;
  76783. // Create a new mesh to contain the glTF hierarchy
  76784. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  76785. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  76786. var childMesh = null;
  76787. for (var i = 0; i < meshes.length; i++) {
  76788. var mesh = meshes[i];
  76789. if (!mesh.parent) {
  76790. // Exclude controller meshes from picking results
  76791. mesh.isPickable = false;
  76792. // Handle root node, attach to the new parentMesh
  76793. childMesh = mesh;
  76794. break;
  76795. }
  76796. }
  76797. if (childMesh) {
  76798. childMesh.setParent(parentMesh);
  76799. // Create our mesh info. Note that this method will always return non-null.
  76800. loadedMeshInfo = this.createMeshInfo(parentMesh);
  76801. }
  76802. else {
  76803. BABYLON.Tools.Warn('Could not find root node in model file.');
  76804. }
  76805. return loadedMeshInfo;
  76806. };
  76807. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  76808. var loadedMeshInfo = new LoadedMeshInfo();
  76809. var i;
  76810. loadedMeshInfo.rootNode = rootNode;
  76811. // Reset the caches
  76812. loadedMeshInfo.buttonMeshes = {};
  76813. loadedMeshInfo.axisMeshes = {};
  76814. // Button Meshes
  76815. for (i = 0; i < this._mapping.buttons.length; i++) {
  76816. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  76817. if (!buttonMeshName) {
  76818. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  76819. continue;
  76820. }
  76821. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  76822. if (!buttonMesh) {
  76823. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  76824. continue;
  76825. }
  76826. var buttonMeshInfo = {
  76827. index: i,
  76828. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  76829. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  76830. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  76831. };
  76832. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  76833. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  76834. }
  76835. else {
  76836. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  76837. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  76838. '(VALUE: ' + !!buttonMeshInfo.value +
  76839. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  76840. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  76841. ')');
  76842. }
  76843. }
  76844. // Axis Meshes
  76845. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  76846. var axisMeshName = this._mapping.axisMeshNames[i];
  76847. if (!axisMeshName) {
  76848. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  76849. continue;
  76850. }
  76851. var axisMesh = getChildByName(rootNode, axisMeshName);
  76852. if (!axisMesh) {
  76853. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  76854. continue;
  76855. }
  76856. var axisMeshInfo = {
  76857. index: i,
  76858. value: getImmediateChildByName(axisMesh, 'VALUE'),
  76859. min: getImmediateChildByName(axisMesh, 'MIN'),
  76860. max: getImmediateChildByName(axisMesh, 'MAX')
  76861. };
  76862. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  76863. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  76864. }
  76865. else {
  76866. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  76867. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  76868. '(VALUE: ' + !!axisMeshInfo.value +
  76869. ', MIN: ' + !!axisMeshInfo.min +
  76870. ', MAX:' + !!axisMeshInfo.max +
  76871. ')');
  76872. }
  76873. }
  76874. // Pointing Ray
  76875. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  76876. if (!loadedMeshInfo.pointingPoseNode) {
  76877. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  76878. }
  76879. else {
  76880. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  76881. }
  76882. return loadedMeshInfo;
  76883. // Look through all children recursively. This will return null if no mesh exists with the given name.
  76884. function getChildByName(node, name) {
  76885. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  76886. }
  76887. // Look through only immediate children. This will return null if no mesh exists with the given name.
  76888. function getImmediateChildByName(node, name) {
  76889. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  76890. }
  76891. };
  76892. /**
  76893. * Gets the ray of the controller in the direction the controller is pointing
  76894. * @param length the length the resulting ray should be
  76895. * @returns a ray in the direction the controller is pointing
  76896. */
  76897. WindowsMotionController.prototype.getForwardRay = function (length) {
  76898. if (length === void 0) { length = 100; }
  76899. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  76900. return _super.prototype.getForwardRay.call(this, length);
  76901. }
  76902. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  76903. var origin = m.getTranslation();
  76904. var forward = new BABYLON.Vector3(0, 0, -1);
  76905. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  76906. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  76907. return new BABYLON.Ray(origin, direction, length);
  76908. };
  76909. /**
  76910. * Disposes of the controller
  76911. */
  76912. WindowsMotionController.prototype.dispose = function () {
  76913. _super.prototype.dispose.call(this);
  76914. this.onTrackpadChangedObservable.clear();
  76915. };
  76916. /**
  76917. * The base url used to load the left and right controller models
  76918. */
  76919. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  76920. /**
  76921. * The name of the left controller model file
  76922. */
  76923. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  76924. /**
  76925. * The name of the right controller model file
  76926. */
  76927. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  76928. /**
  76929. * The controller name prefix for this controller type
  76930. */
  76931. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  76932. /**
  76933. * The controller id pattern for this controller type
  76934. */
  76935. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  76936. return WindowsMotionController;
  76937. }(BABYLON.WebVRController));
  76938. BABYLON.WindowsMotionController = WindowsMotionController;
  76939. })(BABYLON || (BABYLON = {}));
  76940. //# sourceMappingURL=babylon.windowsMotionController.js.map
  76941. var BABYLON;
  76942. (function (BABYLON) {
  76943. /**
  76944. * Gear VR Controller
  76945. */
  76946. var GearVRController = /** @class */ (function (_super) {
  76947. __extends(GearVRController, _super);
  76948. /**
  76949. * Creates a new GearVRController from a gamepad
  76950. * @param vrGamepad the gamepad that the controller should be created from
  76951. */
  76952. function GearVRController(vrGamepad) {
  76953. var _this = _super.call(this, vrGamepad) || this;
  76954. _this._maxRotationDistFromHeadset = Math.PI / 5;
  76955. _this._draggedRoomRotation = 0;
  76956. _this._tmpVector = new BABYLON.Vector3();
  76957. _this._buttonIndexToObservableNameMap = [
  76958. 'onTrackpadChangedObservable',
  76959. 'onTriggerStateChangedObservable' // Trigger
  76960. ];
  76961. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  76962. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  76963. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  76964. return _this;
  76965. }
  76966. /**
  76967. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  76968. * @param poseData raw pose fromthe device
  76969. */
  76970. GearVRController.prototype.updateFromDevice = function (poseData) {
  76971. _super.prototype.updateFromDevice.call(this, poseData);
  76972. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  76973. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  76974. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  76975. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  76976. // Find the radian distance away that the headset is from the controllers rotation
  76977. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  76978. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  76979. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  76980. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  76981. this._draggedRoomRotation += rotationAmount;
  76982. // Rotate controller around headset
  76983. var sin = Math.sin(-rotationAmount);
  76984. var cos = Math.cos(-rotationAmount);
  76985. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  76986. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  76987. }
  76988. }
  76989. }
  76990. };
  76991. /**
  76992. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76993. * @param scene scene in which to add meshes
  76994. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76995. */
  76996. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76997. var _this = this;
  76998. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  76999. // Offset the controller so it will rotate around the users wrist
  77000. var mesh = new BABYLON.Mesh("", scene);
  77001. newMeshes[1].parent = mesh;
  77002. newMeshes[1].position.z = -0.15;
  77003. _this._defaultModel = mesh;
  77004. _this.attachToMesh(_this._defaultModel);
  77005. if (meshLoaded) {
  77006. meshLoaded(_this._defaultModel);
  77007. }
  77008. });
  77009. };
  77010. /**
  77011. * Called once for each button that changed state since the last frame
  77012. * @param buttonIdx Which button index changed
  77013. * @param state New state of the button
  77014. * @param changes Which properties on the state changed since last frame
  77015. */
  77016. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  77017. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  77018. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  77019. // Only emit events for buttons that we know how to map from index to observable
  77020. var observable = this[observableName];
  77021. if (observable) {
  77022. observable.notifyObservers(state);
  77023. }
  77024. }
  77025. };
  77026. /**
  77027. * Base Url for the controller model.
  77028. */
  77029. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  77030. /**
  77031. * File name for the controller model.
  77032. */
  77033. GearVRController.MODEL_FILENAME = 'generic.babylon';
  77034. /**
  77035. * Gamepad Id prefix used to identify this controller.
  77036. */
  77037. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  77038. return GearVRController;
  77039. }(BABYLON.WebVRController));
  77040. BABYLON.GearVRController = GearVRController;
  77041. })(BABYLON || (BABYLON = {}));
  77042. //# sourceMappingURL=babylon.gearVRController.js.map
  77043. var BABYLON;
  77044. (function (BABYLON) {
  77045. /**
  77046. * Google Daydream controller
  77047. */
  77048. var DaydreamController = /** @class */ (function (_super) {
  77049. __extends(DaydreamController, _super);
  77050. /**
  77051. * Creates a new DaydreamController from a gamepad
  77052. * @param vrGamepad the gamepad that the controller should be created from
  77053. */
  77054. function DaydreamController(vrGamepad) {
  77055. var _this = _super.call(this, vrGamepad) || this;
  77056. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  77057. return _this;
  77058. }
  77059. /**
  77060. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  77061. * @param scene scene in which to add meshes
  77062. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  77063. */
  77064. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  77065. var _this = this;
  77066. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  77067. _this._defaultModel = newMeshes[1];
  77068. _this.attachToMesh(_this._defaultModel);
  77069. if (meshLoaded) {
  77070. meshLoaded(_this._defaultModel);
  77071. }
  77072. });
  77073. };
  77074. /**
  77075. * Called once for each button that changed state since the last frame
  77076. * @param buttonIdx Which button index changed
  77077. * @param state New state of the button
  77078. * @param changes Which properties on the state changed since last frame
  77079. */
  77080. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  77081. // Daydream controller only has 1 GamepadButton (on the trackpad).
  77082. if (buttonIdx === 0) {
  77083. var observable = this.onTriggerStateChangedObservable;
  77084. if (observable) {
  77085. observable.notifyObservers(state);
  77086. }
  77087. }
  77088. else {
  77089. // If the app or home buttons are ever made available
  77090. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  77091. }
  77092. };
  77093. /**
  77094. * Base Url for the controller model.
  77095. */
  77096. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  77097. /**
  77098. * File name for the controller model.
  77099. */
  77100. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  77101. /**
  77102. * Gamepad Id prefix used to identify Daydream Controller.
  77103. */
  77104. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  77105. return DaydreamController;
  77106. }(BABYLON.WebVRController));
  77107. BABYLON.DaydreamController = DaydreamController;
  77108. })(BABYLON || (BABYLON = {}));
  77109. //# sourceMappingURL=babylon.daydreamController.js.map
  77110. var BABYLON;
  77111. (function (BABYLON) {
  77112. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  77113. get: function () {
  77114. if (!this._gamepadManager) {
  77115. this._gamepadManager = new BABYLON.GamepadManager(this);
  77116. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  77117. if (!component) {
  77118. component = new GamepadSystemSceneComponent(this);
  77119. this._addComponent(component);
  77120. }
  77121. }
  77122. return this._gamepadManager;
  77123. },
  77124. enumerable: true,
  77125. configurable: true
  77126. });
  77127. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  77128. this.add(new BABYLON.FreeCameraGamepadInput());
  77129. return this;
  77130. };
  77131. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  77132. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  77133. return this;
  77134. };
  77135. /**
  77136. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  77137. */
  77138. var GamepadSystemSceneComponent = /** @class */ (function () {
  77139. /**
  77140. * Creates a new instance of the component for the given scene
  77141. * @param scene Defines the scene to register the component in
  77142. */
  77143. function GamepadSystemSceneComponent(scene) {
  77144. /**
  77145. * The component name helpfull to identify the component in the list of scene components.
  77146. */
  77147. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  77148. this.scene = scene;
  77149. }
  77150. /**
  77151. * Registers the component in a given scene
  77152. */
  77153. GamepadSystemSceneComponent.prototype.register = function () {
  77154. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  77155. };
  77156. /**
  77157. * Rebuilds the elements related to this component in case of
  77158. * context lost for instance.
  77159. */
  77160. GamepadSystemSceneComponent.prototype.rebuild = function () {
  77161. // Nothing to do for gamepads
  77162. };
  77163. /**
  77164. * Disposes the component and the associated ressources
  77165. */
  77166. GamepadSystemSceneComponent.prototype.dispose = function () {
  77167. var gamepadManager = this.scene._gamepadManager;
  77168. if (gamepadManager) {
  77169. gamepadManager.dispose();
  77170. this.scene._gamepadManager = null;
  77171. }
  77172. };
  77173. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  77174. var gamepadManager = this.scene._gamepadManager;
  77175. if (gamepadManager && gamepadManager._isMonitoring) {
  77176. gamepadManager._checkGamepadsStatus();
  77177. }
  77178. };
  77179. return GamepadSystemSceneComponent;
  77180. }());
  77181. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  77182. })(BABYLON || (BABYLON = {}));
  77183. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  77184. var BABYLON;
  77185. (function (BABYLON) {
  77186. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  77187. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  77188. });
  77189. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  77190. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  77191. });
  77192. var FollowCamera = /** @class */ (function (_super) {
  77193. __extends(FollowCamera, _super);
  77194. function FollowCamera(name, position, scene, lockedTarget) {
  77195. if (lockedTarget === void 0) { lockedTarget = null; }
  77196. var _this = _super.call(this, name, position, scene) || this;
  77197. _this.radius = 12;
  77198. _this.rotationOffset = 0;
  77199. _this.heightOffset = 4;
  77200. _this.cameraAcceleration = 0.05;
  77201. _this.maxCameraSpeed = 20;
  77202. _this.lockedTarget = lockedTarget;
  77203. return _this;
  77204. }
  77205. FollowCamera.prototype.getRadians = function (degrees) {
  77206. return degrees * Math.PI / 180;
  77207. };
  77208. FollowCamera.prototype.follow = function (cameraTarget) {
  77209. if (!cameraTarget)
  77210. return;
  77211. var yRotation;
  77212. if (cameraTarget.rotationQuaternion) {
  77213. var rotMatrix = new BABYLON.Matrix();
  77214. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  77215. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  77216. }
  77217. else {
  77218. yRotation = cameraTarget.rotation.y;
  77219. }
  77220. var radians = this.getRadians(this.rotationOffset) + yRotation;
  77221. var targetPosition = cameraTarget.getAbsolutePosition();
  77222. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  77223. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  77224. var dx = targetX - this.position.x;
  77225. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  77226. var dz = (targetZ) - this.position.z;
  77227. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  77228. var vy = dy * this.cameraAcceleration;
  77229. var vz = dz * this.cameraAcceleration * 2;
  77230. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  77231. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  77232. }
  77233. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  77234. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  77235. }
  77236. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  77237. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  77238. }
  77239. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  77240. this.setTarget(targetPosition);
  77241. };
  77242. /** @hidden */
  77243. FollowCamera.prototype._checkInputs = function () {
  77244. _super.prototype._checkInputs.call(this);
  77245. if (this.lockedTarget) {
  77246. this.follow(this.lockedTarget);
  77247. }
  77248. };
  77249. FollowCamera.prototype.getClassName = function () {
  77250. return "FollowCamera";
  77251. };
  77252. __decorate([
  77253. BABYLON.serialize()
  77254. ], FollowCamera.prototype, "radius", void 0);
  77255. __decorate([
  77256. BABYLON.serialize()
  77257. ], FollowCamera.prototype, "rotationOffset", void 0);
  77258. __decorate([
  77259. BABYLON.serialize()
  77260. ], FollowCamera.prototype, "heightOffset", void 0);
  77261. __decorate([
  77262. BABYLON.serialize()
  77263. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  77264. __decorate([
  77265. BABYLON.serialize()
  77266. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  77267. __decorate([
  77268. BABYLON.serializeAsMeshReference("lockedTargetId")
  77269. ], FollowCamera.prototype, "lockedTarget", void 0);
  77270. return FollowCamera;
  77271. }(BABYLON.TargetCamera));
  77272. BABYLON.FollowCamera = FollowCamera;
  77273. var ArcFollowCamera = /** @class */ (function (_super) {
  77274. __extends(ArcFollowCamera, _super);
  77275. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  77276. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  77277. _this.alpha = alpha;
  77278. _this.beta = beta;
  77279. _this.radius = radius;
  77280. _this.target = target;
  77281. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  77282. _this.follow();
  77283. return _this;
  77284. }
  77285. ArcFollowCamera.prototype.follow = function () {
  77286. if (!this.target) {
  77287. return;
  77288. }
  77289. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  77290. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  77291. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  77292. var targetPosition = this.target.getAbsolutePosition();
  77293. this.position = targetPosition.add(this._cartesianCoordinates);
  77294. this.setTarget(targetPosition);
  77295. };
  77296. /** @hidden */
  77297. ArcFollowCamera.prototype._checkInputs = function () {
  77298. _super.prototype._checkInputs.call(this);
  77299. this.follow();
  77300. };
  77301. ArcFollowCamera.prototype.getClassName = function () {
  77302. return "ArcFollowCamera";
  77303. };
  77304. return ArcFollowCamera;
  77305. }(BABYLON.TargetCamera));
  77306. BABYLON.ArcFollowCamera = ArcFollowCamera;
  77307. })(BABYLON || (BABYLON = {}));
  77308. //# sourceMappingURL=babylon.followCamera.js.map
  77309. var BABYLON;
  77310. (function (BABYLON) {
  77311. // We're mainly based on the logic defined into the FreeCamera code
  77312. var UniversalCamera = /** @class */ (function (_super) {
  77313. __extends(UniversalCamera, _super);
  77314. //-- end properties for backward compatibility for inputs
  77315. function UniversalCamera(name, position, scene) {
  77316. var _this = _super.call(this, name, position, scene) || this;
  77317. _this.inputs.addGamepad();
  77318. return _this;
  77319. }
  77320. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  77321. //-- Begin properties for backward compatibility for inputs
  77322. get: function () {
  77323. var gamepad = this.inputs.attached["gamepad"];
  77324. if (gamepad)
  77325. return gamepad.gamepadAngularSensibility;
  77326. return 0;
  77327. },
  77328. set: function (value) {
  77329. var gamepad = this.inputs.attached["gamepad"];
  77330. if (gamepad)
  77331. gamepad.gamepadAngularSensibility = value;
  77332. },
  77333. enumerable: true,
  77334. configurable: true
  77335. });
  77336. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  77337. get: function () {
  77338. var gamepad = this.inputs.attached["gamepad"];
  77339. if (gamepad)
  77340. return gamepad.gamepadMoveSensibility;
  77341. return 0;
  77342. },
  77343. set: function (value) {
  77344. var gamepad = this.inputs.attached["gamepad"];
  77345. if (gamepad)
  77346. gamepad.gamepadMoveSensibility = value;
  77347. },
  77348. enumerable: true,
  77349. configurable: true
  77350. });
  77351. UniversalCamera.prototype.getClassName = function () {
  77352. return "UniversalCamera";
  77353. };
  77354. return UniversalCamera;
  77355. }(BABYLON.TouchCamera));
  77356. BABYLON.UniversalCamera = UniversalCamera;
  77357. })(BABYLON || (BABYLON = {}));
  77358. //# sourceMappingURL=babylon.universalCamera.js.map
  77359. var BABYLON;
  77360. (function (BABYLON) {
  77361. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  77362. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  77363. });
  77364. // We're mainly based on the logic defined into the FreeCamera code
  77365. var GamepadCamera = /** @class */ (function (_super) {
  77366. __extends(GamepadCamera, _super);
  77367. //-- end properties for backward compatibility for inputs
  77368. function GamepadCamera(name, position, scene) {
  77369. return _super.call(this, name, position, scene) || this;
  77370. }
  77371. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  77372. //-- Begin properties for backward compatibility for inputs
  77373. get: function () {
  77374. var gamepad = this.inputs.attached["gamepad"];
  77375. if (gamepad)
  77376. return gamepad.gamepadAngularSensibility;
  77377. return 0;
  77378. },
  77379. set: function (value) {
  77380. var gamepad = this.inputs.attached["gamepad"];
  77381. if (gamepad)
  77382. gamepad.gamepadAngularSensibility = value;
  77383. },
  77384. enumerable: true,
  77385. configurable: true
  77386. });
  77387. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  77388. get: function () {
  77389. var gamepad = this.inputs.attached["gamepad"];
  77390. if (gamepad)
  77391. return gamepad.gamepadMoveSensibility;
  77392. return 0;
  77393. },
  77394. set: function (value) {
  77395. var gamepad = this.inputs.attached["gamepad"];
  77396. if (gamepad)
  77397. gamepad.gamepadMoveSensibility = value;
  77398. },
  77399. enumerable: true,
  77400. configurable: true
  77401. });
  77402. GamepadCamera.prototype.getClassName = function () {
  77403. return "GamepadCamera";
  77404. };
  77405. return GamepadCamera;
  77406. }(BABYLON.UniversalCamera));
  77407. BABYLON.GamepadCamera = GamepadCamera;
  77408. })(BABYLON || (BABYLON = {}));
  77409. //# sourceMappingURL=babylon.gamepadCamera.js.map
  77410. var BABYLON;
  77411. (function (BABYLON) {
  77412. var PostProcessRenderPipelineManager = /** @class */ (function () {
  77413. function PostProcessRenderPipelineManager() {
  77414. this._renderPipelines = {};
  77415. }
  77416. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  77417. this._renderPipelines[renderPipeline._name] = renderPipeline;
  77418. };
  77419. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  77420. if (unique === void 0) { unique = false; }
  77421. var renderPipeline = this._renderPipelines[renderPipelineName];
  77422. if (!renderPipeline) {
  77423. return;
  77424. }
  77425. renderPipeline._attachCameras(cameras, unique);
  77426. };
  77427. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  77428. var renderPipeline = this._renderPipelines[renderPipelineName];
  77429. if (!renderPipeline) {
  77430. return;
  77431. }
  77432. renderPipeline._detachCameras(cameras);
  77433. };
  77434. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  77435. var renderPipeline = this._renderPipelines[renderPipelineName];
  77436. if (!renderPipeline) {
  77437. return;
  77438. }
  77439. renderPipeline._enableEffect(renderEffectName, cameras);
  77440. };
  77441. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  77442. var renderPipeline = this._renderPipelines[renderPipelineName];
  77443. if (!renderPipeline) {
  77444. return;
  77445. }
  77446. renderPipeline._disableEffect(renderEffectName, cameras);
  77447. };
  77448. PostProcessRenderPipelineManager.prototype.update = function () {
  77449. for (var renderPipelineName in this._renderPipelines) {
  77450. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77451. var pipeline = this._renderPipelines[renderPipelineName];
  77452. if (!pipeline.isSupported) {
  77453. pipeline.dispose();
  77454. delete this._renderPipelines[renderPipelineName];
  77455. }
  77456. else {
  77457. pipeline._update();
  77458. }
  77459. }
  77460. }
  77461. };
  77462. /** @hidden */
  77463. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  77464. for (var renderPipelineName in this._renderPipelines) {
  77465. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77466. var pipeline = this._renderPipelines[renderPipelineName];
  77467. pipeline._rebuild();
  77468. }
  77469. }
  77470. };
  77471. PostProcessRenderPipelineManager.prototype.dispose = function () {
  77472. for (var renderPipelineName in this._renderPipelines) {
  77473. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77474. var pipeline = this._renderPipelines[renderPipelineName];
  77475. pipeline.dispose();
  77476. }
  77477. }
  77478. };
  77479. return PostProcessRenderPipelineManager;
  77480. }());
  77481. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  77482. })(BABYLON || (BABYLON = {}));
  77483. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  77484. var BABYLON;
  77485. (function (BABYLON) {
  77486. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  77487. get: function () {
  77488. if (!this._postProcessRenderPipelineManager) {
  77489. // Register the G Buffer component to the scene.
  77490. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  77491. if (!component) {
  77492. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  77493. this._addComponent(component);
  77494. }
  77495. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  77496. }
  77497. return this._postProcessRenderPipelineManager;
  77498. },
  77499. enumerable: true,
  77500. configurable: true
  77501. });
  77502. /**
  77503. * Defines the Render Pipeline scene component responsible to rendering pipelines
  77504. */
  77505. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  77506. /**
  77507. * Creates a new instance of the component for the given scene
  77508. * @param scene Defines the scene to register the component in
  77509. */
  77510. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  77511. /**
  77512. * The component name helpfull to identify the component in the list of scene components.
  77513. */
  77514. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  77515. this.scene = scene;
  77516. }
  77517. /**
  77518. * Registers the component in a given scene
  77519. */
  77520. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  77521. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  77522. };
  77523. /**
  77524. * Rebuilds the elements related to this component in case of
  77525. * context lost for instance.
  77526. */
  77527. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  77528. if (this.scene._postProcessRenderPipelineManager) {
  77529. this.scene._postProcessRenderPipelineManager._rebuild();
  77530. }
  77531. };
  77532. /**
  77533. * Disposes the component and the associated ressources
  77534. */
  77535. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  77536. if (this.scene._postProcessRenderPipelineManager) {
  77537. this.scene._postProcessRenderPipelineManager.dispose();
  77538. }
  77539. };
  77540. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77541. if (this.scene._postProcessRenderPipelineManager) {
  77542. this.scene._postProcessRenderPipelineManager.update();
  77543. }
  77544. };
  77545. return PostProcessRenderPipelineManagerSceneComponent;
  77546. }());
  77547. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  77548. })(BABYLON || (BABYLON = {}));
  77549. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  77550. var BABYLON;
  77551. (function (BABYLON) {
  77552. /**
  77553. * This represents a set of one or more post processes in Babylon.
  77554. * A post process can be used to apply a shader to a texture after it is rendered.
  77555. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  77556. */
  77557. var PostProcessRenderEffect = /** @class */ (function () {
  77558. /**
  77559. * Instantiates a post process render effect.
  77560. * A post process can be used to apply a shader to a texture after it is rendered.
  77561. * @param engine The engine the effect is tied to
  77562. * @param name The name of the effect
  77563. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  77564. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  77565. */
  77566. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  77567. this._name = name;
  77568. this._singleInstance = singleInstance || true;
  77569. this._getPostProcesses = getPostProcesses;
  77570. this._cameras = {};
  77571. this._indicesForCamera = {};
  77572. this._postProcesses = {};
  77573. }
  77574. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  77575. /**
  77576. * Checks if all the post processes in the effect are supported.
  77577. */
  77578. get: function () {
  77579. for (var index in this._postProcesses) {
  77580. if (this._postProcesses.hasOwnProperty(index)) {
  77581. var pps = this._postProcesses[index];
  77582. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  77583. if (!pps[ppIndex].isSupported) {
  77584. return false;
  77585. }
  77586. }
  77587. }
  77588. }
  77589. return true;
  77590. },
  77591. enumerable: true,
  77592. configurable: true
  77593. });
  77594. /**
  77595. * Updates the current state of the effect
  77596. * @hidden
  77597. */
  77598. PostProcessRenderEffect.prototype._update = function () {
  77599. };
  77600. /**
  77601. * Attaches the effect on cameras
  77602. * @param cameras The camera to attach to.
  77603. * @hidden
  77604. */
  77605. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  77606. var _this = this;
  77607. var cameraKey;
  77608. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77609. if (!cams) {
  77610. return;
  77611. }
  77612. for (var i = 0; i < cams.length; i++) {
  77613. var camera = cams[i];
  77614. var cameraName = camera.name;
  77615. if (this._singleInstance) {
  77616. cameraKey = 0;
  77617. }
  77618. else {
  77619. cameraKey = cameraName;
  77620. }
  77621. if (!this._postProcesses[cameraKey]) {
  77622. var postProcess = this._getPostProcesses();
  77623. if (postProcess) {
  77624. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  77625. }
  77626. }
  77627. if (!this._indicesForCamera[cameraName]) {
  77628. this._indicesForCamera[cameraName] = [];
  77629. }
  77630. this._postProcesses[cameraKey].forEach(function (postProcess) {
  77631. var index = camera.attachPostProcess(postProcess);
  77632. _this._indicesForCamera[cameraName].push(index);
  77633. });
  77634. if (!this._cameras[cameraName]) {
  77635. this._cameras[cameraName] = camera;
  77636. }
  77637. }
  77638. };
  77639. /**
  77640. * Detatches the effect on cameras
  77641. * @param cameras The camera to detatch from.
  77642. * @hidden
  77643. */
  77644. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  77645. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77646. if (!cams) {
  77647. return;
  77648. }
  77649. for (var i = 0; i < cams.length; i++) {
  77650. var camera = cams[i];
  77651. var cameraName = camera.name;
  77652. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77653. camera.detachPostProcess(postProcess);
  77654. });
  77655. if (this._cameras[cameraName]) {
  77656. //this._indicesForCamera.splice(index, 1);
  77657. this._cameras[cameraName] = null;
  77658. }
  77659. }
  77660. };
  77661. /**
  77662. * Enables the effect on given cameras
  77663. * @param cameras The camera to enable.
  77664. * @hidden
  77665. */
  77666. PostProcessRenderEffect.prototype._enable = function (cameras) {
  77667. var _this = this;
  77668. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77669. if (!cams) {
  77670. return;
  77671. }
  77672. for (var i = 0; i < cams.length; i++) {
  77673. var camera = cams[i];
  77674. var cameraName = camera.name;
  77675. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  77676. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  77677. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77678. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  77679. });
  77680. }
  77681. }
  77682. }
  77683. };
  77684. /**
  77685. * Disables the effect on the given cameras
  77686. * @param cameras The camera to disable.
  77687. * @hidden
  77688. */
  77689. PostProcessRenderEffect.prototype._disable = function (cameras) {
  77690. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77691. if (!cams) {
  77692. return;
  77693. }
  77694. for (var i = 0; i < cams.length; i++) {
  77695. var camera = cams[i];
  77696. var cameraName = camera.name;
  77697. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77698. camera.detachPostProcess(postProcess);
  77699. });
  77700. }
  77701. };
  77702. /**
  77703. * Gets a list of the post processes contained in the effect.
  77704. * @param camera The camera to get the post processes on.
  77705. * @returns The list of the post processes in the effect.
  77706. */
  77707. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  77708. if (this._singleInstance) {
  77709. return this._postProcesses[0];
  77710. }
  77711. else {
  77712. if (!camera) {
  77713. return null;
  77714. }
  77715. return this._postProcesses[camera.name];
  77716. }
  77717. };
  77718. return PostProcessRenderEffect;
  77719. }());
  77720. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  77721. })(BABYLON || (BABYLON = {}));
  77722. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  77723. var BABYLON;
  77724. (function (BABYLON) {
  77725. var PostProcessRenderPipeline = /** @class */ (function () {
  77726. function PostProcessRenderPipeline(engine, name) {
  77727. this.engine = engine;
  77728. this._name = name;
  77729. this._renderEffects = {};
  77730. this._renderEffectsForIsolatedPass = new Array();
  77731. this._cameras = [];
  77732. }
  77733. PostProcessRenderPipeline.prototype.getClassName = function () {
  77734. return "PostProcessRenderPipeline";
  77735. };
  77736. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  77737. get: function () {
  77738. for (var renderEffectName in this._renderEffects) {
  77739. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77740. if (!this._renderEffects[renderEffectName].isSupported) {
  77741. return false;
  77742. }
  77743. }
  77744. }
  77745. return true;
  77746. },
  77747. enumerable: true,
  77748. configurable: true
  77749. });
  77750. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  77751. this._renderEffects[renderEffect._name] = renderEffect;
  77752. };
  77753. // private
  77754. /** @hidden */
  77755. PostProcessRenderPipeline.prototype._rebuild = function () {
  77756. };
  77757. /** @hidden */
  77758. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  77759. var renderEffects = this._renderEffects[renderEffectName];
  77760. if (!renderEffects) {
  77761. return;
  77762. }
  77763. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  77764. };
  77765. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  77766. var renderEffects = this._renderEffects[renderEffectName];
  77767. if (!renderEffects) {
  77768. return;
  77769. }
  77770. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  77771. };
  77772. /** @hidden */
  77773. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  77774. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77775. if (!cams) {
  77776. return;
  77777. }
  77778. var indicesToDelete = [];
  77779. var i;
  77780. for (i = 0; i < cams.length; i++) {
  77781. var camera = cams[i];
  77782. var cameraName = camera.name;
  77783. if (this._cameras.indexOf(camera) === -1) {
  77784. this._cameras[cameraName] = camera;
  77785. }
  77786. else if (unique) {
  77787. indicesToDelete.push(i);
  77788. }
  77789. }
  77790. for (i = 0; i < indicesToDelete.length; i++) {
  77791. cameras.splice(indicesToDelete[i], 1);
  77792. }
  77793. for (var renderEffectName in this._renderEffects) {
  77794. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77795. this._renderEffects[renderEffectName]._attachCameras(cams);
  77796. }
  77797. }
  77798. };
  77799. /** @hidden */
  77800. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  77801. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77802. if (!cams) {
  77803. return;
  77804. }
  77805. for (var renderEffectName in this._renderEffects) {
  77806. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77807. this._renderEffects[renderEffectName]._detachCameras(cams);
  77808. }
  77809. }
  77810. for (var i = 0; i < cams.length; i++) {
  77811. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  77812. }
  77813. };
  77814. /** @hidden */
  77815. PostProcessRenderPipeline.prototype._update = function () {
  77816. for (var renderEffectName in this._renderEffects) {
  77817. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77818. this._renderEffects[renderEffectName]._update();
  77819. }
  77820. }
  77821. for (var i = 0; i < this._cameras.length; i++) {
  77822. var cameraName = this._cameras[i].name;
  77823. if (this._renderEffectsForIsolatedPass[cameraName]) {
  77824. this._renderEffectsForIsolatedPass[cameraName]._update();
  77825. }
  77826. }
  77827. };
  77828. /** @hidden */
  77829. PostProcessRenderPipeline.prototype._reset = function () {
  77830. this._renderEffects = {};
  77831. this._renderEffectsForIsolatedPass = new Array();
  77832. };
  77833. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  77834. // 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)
  77835. var effectKeys = Object.keys(this._renderEffects);
  77836. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  77837. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  77838. if (postProcesses) {
  77839. postProcesses[0].samples = sampleCount;
  77840. return true;
  77841. }
  77842. }
  77843. return false;
  77844. };
  77845. PostProcessRenderPipeline.prototype.dispose = function () {
  77846. // Must be implemented by children
  77847. };
  77848. __decorate([
  77849. BABYLON.serialize()
  77850. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  77851. return PostProcessRenderPipeline;
  77852. }());
  77853. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  77854. })(BABYLON || (BABYLON = {}));
  77855. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  77856. var BABYLON;
  77857. (function (BABYLON) {
  77858. /**
  77859. * This represents a depth renderer in Babylon.
  77860. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  77861. */
  77862. var DepthRenderer = /** @class */ (function () {
  77863. /**
  77864. * Instantiates a depth renderer
  77865. * @param scene The scene the renderer belongs to
  77866. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  77867. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  77868. */
  77869. function DepthRenderer(scene, type, camera) {
  77870. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  77871. if (camera === void 0) { camera = null; }
  77872. var _this = this;
  77873. /**
  77874. * Specifiess that the depth renderer will only be used within
  77875. * the camera it is created for.
  77876. * This can help forcing its rendering during the camera processing.
  77877. */
  77878. this.useOnlyInActiveCamera = false;
  77879. this._scene = scene;
  77880. // Register the G Buffer component to the scene.
  77881. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  77882. if (!component) {
  77883. component = new BABYLON.DepthRendererSceneComponent(scene);
  77884. scene._addComponent(component);
  77885. }
  77886. this._camera = camera;
  77887. var engine = scene.getEngine();
  77888. // Render target
  77889. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  77890. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77891. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77892. this._depthMap.refreshRate = 1;
  77893. this._depthMap.renderParticles = false;
  77894. this._depthMap.renderList = null;
  77895. // Camera to get depth map from to support multiple concurrent cameras
  77896. this._depthMap.activeCamera = this._camera;
  77897. this._depthMap.ignoreCameraViewport = true;
  77898. this._depthMap.useCameraPostProcesses = false;
  77899. // set default depth value to 1.0 (far away)
  77900. this._depthMap.onClearObservable.add(function (engine) {
  77901. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  77902. });
  77903. // Custom render function
  77904. var renderSubMesh = function (subMesh) {
  77905. var mesh = subMesh.getRenderingMesh();
  77906. var scene = _this._scene;
  77907. var engine = scene.getEngine();
  77908. var material = subMesh.getMaterial();
  77909. if (!material) {
  77910. return;
  77911. }
  77912. // Culling and reverse (right handed system)
  77913. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77914. // Managing instances
  77915. var batch = mesh._getInstancesRenderList(subMesh._id);
  77916. if (batch.mustReturn) {
  77917. return;
  77918. }
  77919. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77920. var camera = _this._camera || scene.activeCamera;
  77921. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  77922. engine.enableEffect(_this._effect);
  77923. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77924. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77925. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  77926. // Alpha test
  77927. if (material && material.needAlphaTesting()) {
  77928. var alphaTexture = material.getAlphaTestTexture();
  77929. if (alphaTexture) {
  77930. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77931. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77932. }
  77933. }
  77934. // Bones
  77935. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77936. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77937. }
  77938. // Draw
  77939. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77940. }
  77941. };
  77942. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77943. var index;
  77944. if (depthOnlySubMeshes.length) {
  77945. engine.setColorWrite(false);
  77946. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77947. renderSubMesh(depthOnlySubMeshes.data[index]);
  77948. }
  77949. engine.setColorWrite(true);
  77950. }
  77951. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77952. renderSubMesh(opaqueSubMeshes.data[index]);
  77953. }
  77954. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77955. renderSubMesh(alphaTestSubMeshes.data[index]);
  77956. }
  77957. };
  77958. }
  77959. /**
  77960. * Creates the depth rendering effect and checks if the effect is ready.
  77961. * @param subMesh The submesh to be used to render the depth map of
  77962. * @param useInstances If multiple world instances should be used
  77963. * @returns if the depth renderer is ready to render the depth map
  77964. */
  77965. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  77966. var material = subMesh.getMaterial();
  77967. if (material.disableDepthWrite) {
  77968. return false;
  77969. }
  77970. var defines = [];
  77971. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77972. var mesh = subMesh.getMesh();
  77973. // Alpha test
  77974. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  77975. defines.push("#define ALPHATEST");
  77976. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77977. attribs.push(BABYLON.VertexBuffer.UVKind);
  77978. defines.push("#define UV1");
  77979. }
  77980. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77981. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77982. defines.push("#define UV2");
  77983. }
  77984. }
  77985. // Bones
  77986. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77987. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77988. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77989. if (mesh.numBoneInfluencers > 4) {
  77990. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77991. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77992. }
  77993. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77994. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77995. }
  77996. else {
  77997. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77998. }
  77999. // Instances
  78000. if (useInstances) {
  78001. defines.push("#define INSTANCES");
  78002. attribs.push("world0");
  78003. attribs.push("world1");
  78004. attribs.push("world2");
  78005. attribs.push("world3");
  78006. }
  78007. // Get correct effect
  78008. var join = defines.join("\n");
  78009. if (this._cachedDefines !== join) {
  78010. this._cachedDefines = join;
  78011. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  78012. }
  78013. return this._effect.isReady();
  78014. };
  78015. /**
  78016. * Gets the texture which the depth map will be written to.
  78017. * @returns The depth map texture
  78018. */
  78019. DepthRenderer.prototype.getDepthMap = function () {
  78020. return this._depthMap;
  78021. };
  78022. /**
  78023. * Disposes of the depth renderer.
  78024. */
  78025. DepthRenderer.prototype.dispose = function () {
  78026. this._depthMap.dispose();
  78027. };
  78028. return DepthRenderer;
  78029. }());
  78030. BABYLON.DepthRenderer = DepthRenderer;
  78031. })(BABYLON || (BABYLON = {}));
  78032. //# sourceMappingURL=babylon.depthRenderer.js.map
  78033. var BABYLON;
  78034. (function (BABYLON) {
  78035. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  78036. camera = camera || this.activeCamera;
  78037. if (!camera) {
  78038. throw "No camera available to enable depth renderer";
  78039. }
  78040. if (!this._depthRenderer) {
  78041. this._depthRenderer = {};
  78042. }
  78043. if (!this._depthRenderer[camera.id]) {
  78044. var textureType = 0;
  78045. if (this.getEngine().getCaps().textureHalfFloatRender) {
  78046. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78047. }
  78048. else if (this.getEngine().getCaps().textureFloatRender) {
  78049. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78050. }
  78051. else {
  78052. throw "Depth renderer does not support int texture type";
  78053. }
  78054. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  78055. }
  78056. return this._depthRenderer[camera.id];
  78057. };
  78058. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  78059. camera = camera || this.activeCamera;
  78060. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  78061. return;
  78062. }
  78063. this._depthRenderer[camera.id].dispose();
  78064. delete this._depthRenderer[camera.id];
  78065. };
  78066. /**
  78067. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  78068. * in several rendering techniques.
  78069. */
  78070. var DepthRendererSceneComponent = /** @class */ (function () {
  78071. /**
  78072. * Creates a new instance of the component for the given scene
  78073. * @param scene Defines the scene to register the component in
  78074. */
  78075. function DepthRendererSceneComponent(scene) {
  78076. /**
  78077. * The component name helpfull to identify the component in the list of scene components.
  78078. */
  78079. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  78080. this.scene = scene;
  78081. }
  78082. /**
  78083. * Registers the component in a given scene
  78084. */
  78085. DepthRendererSceneComponent.prototype.register = function () {
  78086. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  78087. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  78088. };
  78089. /**
  78090. * Rebuilds the elements related to this component in case of
  78091. * context lost for instance.
  78092. */
  78093. DepthRendererSceneComponent.prototype.rebuild = function () {
  78094. // Nothing to do for this component
  78095. };
  78096. /**
  78097. * Disposes the component and the associated ressources
  78098. */
  78099. DepthRendererSceneComponent.prototype.dispose = function () {
  78100. for (var key in this.scene._depthRenderer) {
  78101. this.scene._depthRenderer[key].dispose();
  78102. }
  78103. };
  78104. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  78105. if (this.scene._depthRenderer) {
  78106. for (var key in this.scene._depthRenderer) {
  78107. var depthRenderer = this.scene._depthRenderer[key];
  78108. if (!depthRenderer.useOnlyInActiveCamera) {
  78109. renderTargets.push(depthRenderer.getDepthMap());
  78110. }
  78111. }
  78112. }
  78113. };
  78114. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  78115. if (this.scene._depthRenderer) {
  78116. for (var key in this.scene._depthRenderer) {
  78117. var depthRenderer = this.scene._depthRenderer[key];
  78118. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  78119. renderTargets.push(depthRenderer.getDepthMap());
  78120. }
  78121. }
  78122. }
  78123. };
  78124. return DepthRendererSceneComponent;
  78125. }());
  78126. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  78127. })(BABYLON || (BABYLON = {}));
  78128. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  78129. var BABYLON;
  78130. (function (BABYLON) {
  78131. /**
  78132. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  78133. */
  78134. var GeometryBufferRenderer = /** @class */ (function () {
  78135. /**
  78136. * Creates a new G Buffer for the scene
  78137. * @param scene The scene the buffer belongs to
  78138. * @param ratio How big is the buffer related to the main canvas.
  78139. */
  78140. function GeometryBufferRenderer(scene, ratio) {
  78141. if (ratio === void 0) { ratio = 1; }
  78142. this._enablePosition = false;
  78143. this._scene = scene;
  78144. this._ratio = ratio;
  78145. // Register the G Buffer component to the scene.
  78146. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  78147. if (!component) {
  78148. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  78149. scene._addComponent(component);
  78150. }
  78151. // Render target
  78152. this._createRenderTargets();
  78153. }
  78154. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  78155. /**
  78156. * Set the render list (meshes to be rendered) used in the G buffer.
  78157. */
  78158. set: function (meshes) {
  78159. this._multiRenderTarget.renderList = meshes;
  78160. },
  78161. enumerable: true,
  78162. configurable: true
  78163. });
  78164. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  78165. /**
  78166. * Gets wether or not G buffer are supported by the running hardware.
  78167. * This requires draw buffer supports
  78168. */
  78169. get: function () {
  78170. return this._multiRenderTarget.isSupported;
  78171. },
  78172. enumerable: true,
  78173. configurable: true
  78174. });
  78175. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  78176. /**
  78177. * Gets wether or not position are enabled for the G buffer.
  78178. */
  78179. get: function () {
  78180. return this._enablePosition;
  78181. },
  78182. /**
  78183. * Sets wether or not position are enabled for the G buffer.
  78184. */
  78185. set: function (enable) {
  78186. this._enablePosition = enable;
  78187. this.dispose();
  78188. this._createRenderTargets();
  78189. },
  78190. enumerable: true,
  78191. configurable: true
  78192. });
  78193. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  78194. /**
  78195. * Gets the scene associated with the buffer.
  78196. */
  78197. get: function () {
  78198. return this._scene;
  78199. },
  78200. enumerable: true,
  78201. configurable: true
  78202. });
  78203. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  78204. /**
  78205. * Gets the ratio used by the buffer during its creation.
  78206. * How big is the buffer related to the main canvas.
  78207. */
  78208. get: function () {
  78209. return this._ratio;
  78210. },
  78211. enumerable: true,
  78212. configurable: true
  78213. });
  78214. /**
  78215. * Checks wether everything is ready to render a submesh to the G buffer.
  78216. * @param subMesh the submesh to check readiness for
  78217. * @param useInstances is the mesh drawn using instance or not
  78218. * @returns true if ready otherwise false
  78219. */
  78220. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  78221. var material = subMesh.getMaterial();
  78222. if (material && material.disableDepthWrite) {
  78223. return false;
  78224. }
  78225. var defines = [];
  78226. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78227. var mesh = subMesh.getMesh();
  78228. // Alpha test
  78229. if (material && material.needAlphaTesting()) {
  78230. defines.push("#define ALPHATEST");
  78231. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78232. attribs.push(BABYLON.VertexBuffer.UVKind);
  78233. defines.push("#define UV1");
  78234. }
  78235. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78236. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78237. defines.push("#define UV2");
  78238. }
  78239. }
  78240. // Buffers
  78241. if (this._enablePosition) {
  78242. defines.push("#define POSITION");
  78243. }
  78244. // Bones
  78245. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78246. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78247. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78248. if (mesh.numBoneInfluencers > 4) {
  78249. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78250. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78251. }
  78252. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78253. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78254. }
  78255. else {
  78256. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78257. }
  78258. // Instances
  78259. if (useInstances) {
  78260. defines.push("#define INSTANCES");
  78261. attribs.push("world0");
  78262. attribs.push("world1");
  78263. attribs.push("world2");
  78264. attribs.push("world3");
  78265. }
  78266. // Get correct effect
  78267. var join = defines.join("\n");
  78268. if (this._cachedDefines !== join) {
  78269. this._cachedDefines = join;
  78270. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  78271. }
  78272. return this._effect.isReady();
  78273. };
  78274. /**
  78275. * Gets the current underlying G Buffer.
  78276. * @returns the buffer
  78277. */
  78278. GeometryBufferRenderer.prototype.getGBuffer = function () {
  78279. return this._multiRenderTarget;
  78280. };
  78281. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  78282. /**
  78283. * Gets the number of samples used to render the buffer (anti aliasing).
  78284. */
  78285. get: function () {
  78286. return this._multiRenderTarget.samples;
  78287. },
  78288. /**
  78289. * Sets the number of samples used to render the buffer (anti aliasing).
  78290. */
  78291. set: function (value) {
  78292. this._multiRenderTarget.samples = value;
  78293. },
  78294. enumerable: true,
  78295. configurable: true
  78296. });
  78297. /**
  78298. * Disposes the renderer and frees up associated resources.
  78299. */
  78300. GeometryBufferRenderer.prototype.dispose = function () {
  78301. this.getGBuffer().dispose();
  78302. };
  78303. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  78304. var _this = this;
  78305. var engine = this._scene.getEngine();
  78306. var count = this._enablePosition ? 3 : 2;
  78307. 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 });
  78308. if (!this.isSupported) {
  78309. return;
  78310. }
  78311. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78312. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78313. this._multiRenderTarget.refreshRate = 1;
  78314. this._multiRenderTarget.renderParticles = false;
  78315. this._multiRenderTarget.renderList = null;
  78316. // set default depth value to 1.0 (far away)
  78317. this._multiRenderTarget.onClearObservable.add(function (engine) {
  78318. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  78319. });
  78320. // Custom render function
  78321. var renderSubMesh = function (subMesh) {
  78322. var mesh = subMesh.getRenderingMesh();
  78323. var scene = _this._scene;
  78324. var engine = scene.getEngine();
  78325. var material = subMesh.getMaterial();
  78326. if (!material) {
  78327. return;
  78328. }
  78329. // Culling
  78330. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  78331. // Managing instances
  78332. var batch = mesh._getInstancesRenderList(subMesh._id);
  78333. if (batch.mustReturn) {
  78334. return;
  78335. }
  78336. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78337. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  78338. engine.enableEffect(_this._effect);
  78339. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  78340. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78341. _this._effect.setMatrix("view", scene.getViewMatrix());
  78342. // Alpha test
  78343. if (material && material.needAlphaTesting()) {
  78344. var alphaTexture = material.getAlphaTestTexture();
  78345. if (alphaTexture) {
  78346. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78347. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78348. }
  78349. }
  78350. // Bones
  78351. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78352. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78353. }
  78354. // Draw
  78355. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  78356. }
  78357. };
  78358. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78359. var index;
  78360. if (depthOnlySubMeshes.length) {
  78361. engine.setColorWrite(false);
  78362. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78363. renderSubMesh(depthOnlySubMeshes.data[index]);
  78364. }
  78365. engine.setColorWrite(true);
  78366. }
  78367. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78368. renderSubMesh(opaqueSubMeshes.data[index]);
  78369. }
  78370. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78371. renderSubMesh(alphaTestSubMeshes.data[index]);
  78372. }
  78373. };
  78374. };
  78375. return GeometryBufferRenderer;
  78376. }());
  78377. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  78378. })(BABYLON || (BABYLON = {}));
  78379. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  78380. var BABYLON;
  78381. (function (BABYLON) {
  78382. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  78383. get: function () {
  78384. this._geometryBufferRenderer;
  78385. },
  78386. set: function (value) {
  78387. if (value && value.isSupported) {
  78388. this._geometryBufferRenderer = value;
  78389. }
  78390. ;
  78391. },
  78392. enumerable: true,
  78393. configurable: true
  78394. });
  78395. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  78396. if (ratio === void 0) { ratio = 1; }
  78397. if (this._geometryBufferRenderer) {
  78398. return this._geometryBufferRenderer;
  78399. }
  78400. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  78401. if (!this._geometryBufferRenderer.isSupported) {
  78402. this._geometryBufferRenderer = null;
  78403. }
  78404. return this._geometryBufferRenderer;
  78405. };
  78406. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  78407. if (!this._geometryBufferRenderer) {
  78408. return;
  78409. }
  78410. this._geometryBufferRenderer.dispose();
  78411. this._geometryBufferRenderer = null;
  78412. };
  78413. /**
  78414. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  78415. * in several rendering techniques.
  78416. */
  78417. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  78418. /**
  78419. * Creates a new instance of the component for the given scene
  78420. * @param scene Defines the scene to register the component in
  78421. */
  78422. function GeometryBufferRendererSceneComponent(scene) {
  78423. /**
  78424. * The component name helpful to identify the component in the list of scene components.
  78425. */
  78426. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  78427. this.scene = scene;
  78428. }
  78429. /**
  78430. * Registers the component in a given scene
  78431. */
  78432. GeometryBufferRendererSceneComponent.prototype.register = function () {
  78433. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  78434. };
  78435. /**
  78436. * Rebuilds the elements related to this component in case of
  78437. * context lost for instance.
  78438. */
  78439. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  78440. // Nothing to do for this component
  78441. };
  78442. /**
  78443. * Disposes the component and the associated ressources
  78444. */
  78445. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  78446. // Nothing to do for this component
  78447. };
  78448. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  78449. if (this.scene._geometryBufferRenderer) {
  78450. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  78451. }
  78452. };
  78453. return GeometryBufferRendererSceneComponent;
  78454. }());
  78455. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  78456. })(BABYLON || (BABYLON = {}));
  78457. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  78458. var BABYLON;
  78459. (function (BABYLON) {
  78460. var SSAORenderingPipeline = /** @class */ (function (_super) {
  78461. __extends(SSAORenderingPipeline, _super);
  78462. /**
  78463. * @constructor
  78464. * @param {string} name - The rendering pipeline name
  78465. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78466. * @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 }
  78467. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78468. */
  78469. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  78470. var _this = _super.call(this, scene.getEngine(), name) || this;
  78471. // Members
  78472. /**
  78473. * The PassPostProcess id in the pipeline that contains the original scene color
  78474. */
  78475. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  78476. /**
  78477. * The SSAO PostProcess id in the pipeline
  78478. */
  78479. _this.SSAORenderEffect = "SSAORenderEffect";
  78480. /**
  78481. * The horizontal blur PostProcess id in the pipeline
  78482. */
  78483. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  78484. /**
  78485. * The vertical blur PostProcess id in the pipeline
  78486. */
  78487. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  78488. /**
  78489. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  78490. */
  78491. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  78492. /**
  78493. * The output strength of the SSAO post-process. Default value is 1.0.
  78494. */
  78495. _this.totalStrength = 1.0;
  78496. /**
  78497. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  78498. */
  78499. _this.radius = 0.0001;
  78500. /**
  78501. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  78502. * Must not be equal to fallOff and superior to fallOff.
  78503. * Default value is 0.975
  78504. */
  78505. _this.area = 0.0075;
  78506. /**
  78507. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  78508. * Must not be equal to area and inferior to area.
  78509. * Default value is 0.0
  78510. */
  78511. _this.fallOff = 0.000001;
  78512. /**
  78513. * The base color of the SSAO post-process
  78514. * The final result is "base + ssao" between [0, 1]
  78515. */
  78516. _this.base = 0.5;
  78517. _this._firstUpdate = true;
  78518. _this._scene = scene;
  78519. // Set up assets
  78520. _this._createRandomTexture();
  78521. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  78522. var ssaoRatio = ratio.ssaoRatio || ratio;
  78523. var combineRatio = ratio.combineRatio || ratio;
  78524. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  78525. _this._createSSAOPostProcess(ssaoRatio);
  78526. _this._createBlurPostProcess(ssaoRatio);
  78527. _this._createSSAOCombinePostProcess(combineRatio);
  78528. // Set up pipeline
  78529. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  78530. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  78531. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  78532. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  78533. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  78534. // Finish
  78535. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78536. if (cameras)
  78537. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78538. return _this;
  78539. }
  78540. // Public Methods
  78541. /**
  78542. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  78543. */
  78544. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  78545. if (disableDepthRender === void 0) { disableDepthRender = false; }
  78546. for (var i = 0; i < this._scene.cameras.length; i++) {
  78547. var camera = this._scene.cameras[i];
  78548. this._originalColorPostProcess.dispose(camera);
  78549. this._ssaoPostProcess.dispose(camera);
  78550. this._blurHPostProcess.dispose(camera);
  78551. this._blurVPostProcess.dispose(camera);
  78552. this._ssaoCombinePostProcess.dispose(camera);
  78553. }
  78554. this._randomTexture.dispose();
  78555. if (disableDepthRender)
  78556. this._scene.disableDepthRenderer();
  78557. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78558. _super.prototype.dispose.call(this);
  78559. };
  78560. // Private Methods
  78561. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  78562. var _this = this;
  78563. var size = 16;
  78564. 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);
  78565. 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);
  78566. this._blurHPostProcess.onActivateObservable.add(function () {
  78567. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  78568. _this._blurHPostProcess.kernel = size * dw;
  78569. });
  78570. this._blurVPostProcess.onActivateObservable.add(function () {
  78571. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  78572. _this._blurVPostProcess.kernel = size * dw;
  78573. });
  78574. };
  78575. /** @hidden */
  78576. SSAORenderingPipeline.prototype._rebuild = function () {
  78577. this._firstUpdate = true;
  78578. _super.prototype._rebuild.call(this);
  78579. };
  78580. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  78581. var _this = this;
  78582. var numSamples = 16;
  78583. var sampleSphere = [
  78584. 0.5381, 0.1856, -0.4319,
  78585. 0.1379, 0.2486, 0.4430,
  78586. 0.3371, 0.5679, -0.0057,
  78587. -0.6999, -0.0451, -0.0019,
  78588. 0.0689, -0.1598, -0.8547,
  78589. 0.0560, 0.0069, -0.1843,
  78590. -0.0146, 0.1402, 0.0762,
  78591. 0.0100, -0.1924, -0.0344,
  78592. -0.3577, -0.5301, -0.4358,
  78593. -0.3169, 0.1063, 0.0158,
  78594. 0.0103, -0.5869, 0.0046,
  78595. -0.0897, -0.4940, 0.3287,
  78596. 0.7119, -0.0154, -0.0918,
  78597. -0.0533, 0.0596, -0.5411,
  78598. 0.0352, -0.0631, 0.5460,
  78599. -0.4776, 0.2847, -0.0271
  78600. ];
  78601. var samplesFactor = 1.0 / numSamples;
  78602. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  78603. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  78604. "area", "fallOff", "base", "range", "viewport"
  78605. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  78606. this._ssaoPostProcess.onApply = function (effect) {
  78607. if (_this._firstUpdate) {
  78608. effect.setArray3("sampleSphere", sampleSphere);
  78609. effect.setFloat("samplesFactor", samplesFactor);
  78610. effect.setFloat("randTextureTiles", 4.0);
  78611. }
  78612. effect.setFloat("totalStrength", _this.totalStrength);
  78613. effect.setFloat("radius", _this.radius);
  78614. effect.setFloat("area", _this.area);
  78615. effect.setFloat("fallOff", _this.fallOff);
  78616. effect.setFloat("base", _this.base);
  78617. effect.setTexture("textureSampler", _this._depthTexture);
  78618. effect.setTexture("randomSampler", _this._randomTexture);
  78619. };
  78620. };
  78621. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  78622. var _this = this;
  78623. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78624. this._ssaoCombinePostProcess.onApply = function (effect) {
  78625. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  78626. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  78627. };
  78628. };
  78629. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  78630. var size = 512;
  78631. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78632. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78633. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78634. var context = this._randomTexture.getContext();
  78635. var rand = function (min, max) {
  78636. return Math.random() * (max - min) + min;
  78637. };
  78638. var randVector = BABYLON.Vector3.Zero();
  78639. for (var x = 0; x < size; x++) {
  78640. for (var y = 0; y < size; y++) {
  78641. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  78642. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  78643. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  78644. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  78645. context.fillRect(x, y, 1, 1);
  78646. }
  78647. }
  78648. this._randomTexture.update(false);
  78649. };
  78650. __decorate([
  78651. BABYLON.serialize()
  78652. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  78653. __decorate([
  78654. BABYLON.serialize()
  78655. ], SSAORenderingPipeline.prototype, "radius", void 0);
  78656. __decorate([
  78657. BABYLON.serialize()
  78658. ], SSAORenderingPipeline.prototype, "area", void 0);
  78659. __decorate([
  78660. BABYLON.serialize()
  78661. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  78662. __decorate([
  78663. BABYLON.serialize()
  78664. ], SSAORenderingPipeline.prototype, "base", void 0);
  78665. return SSAORenderingPipeline;
  78666. }(BABYLON.PostProcessRenderPipeline));
  78667. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  78668. })(BABYLON || (BABYLON = {}));
  78669. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  78670. var BABYLON;
  78671. (function (BABYLON) {
  78672. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  78673. __extends(SSAO2RenderingPipeline, _super);
  78674. /**
  78675. * @constructor
  78676. * @param {string} name - The rendering pipeline name
  78677. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78678. * @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 }
  78679. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78680. */
  78681. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  78682. var _this = _super.call(this, scene.getEngine(), name) || this;
  78683. // Members
  78684. /**
  78685. * The PassPostProcess id in the pipeline that contains the original scene color
  78686. */
  78687. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  78688. /**
  78689. * The SSAO PostProcess id in the pipeline
  78690. */
  78691. _this.SSAORenderEffect = "SSAORenderEffect";
  78692. /**
  78693. * The horizontal blur PostProcess id in the pipeline
  78694. */
  78695. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  78696. /**
  78697. * The vertical blur PostProcess id in the pipeline
  78698. */
  78699. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  78700. /**
  78701. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  78702. */
  78703. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  78704. /**
  78705. * The output strength of the SSAO post-process. Default value is 1.0.
  78706. */
  78707. _this.totalStrength = 1.0;
  78708. /**
  78709. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  78710. */
  78711. _this.maxZ = 100.0;
  78712. /**
  78713. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  78714. */
  78715. _this.minZAspect = 0.2;
  78716. _this._samples = 8;
  78717. _this._textureSamples = 1;
  78718. /**
  78719. * Are we using bilateral blur ?
  78720. */
  78721. _this._expensiveBlur = true;
  78722. /**
  78723. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  78724. */
  78725. _this.radius = 2.0;
  78726. /**
  78727. * The base color of the SSAO post-process
  78728. * The final result is "base + ssao" between [0, 1]
  78729. */
  78730. _this.base = 0;
  78731. _this._firstUpdate = true;
  78732. _this._bits = new Uint32Array(1);
  78733. _this._scene = scene;
  78734. _this._ratio = ratio;
  78735. if (!_this.isSupported) {
  78736. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  78737. return _this;
  78738. }
  78739. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  78740. var blurRatio = _this._ratio.blurRatio || ratio;
  78741. // Set up assets
  78742. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  78743. _this._createRandomTexture();
  78744. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  78745. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  78746. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  78747. _this._originalColorPostProcess.samples = _this.textureSamples;
  78748. _this._createSSAOPostProcess(1.0);
  78749. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  78750. _this._createSSAOCombinePostProcess(blurRatio);
  78751. // Set up pipeline
  78752. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  78753. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  78754. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  78755. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  78756. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  78757. // Finish
  78758. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78759. if (cameras)
  78760. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78761. return _this;
  78762. }
  78763. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  78764. get: function () {
  78765. return this._samples;
  78766. },
  78767. /**
  78768. * Number of samples used for the SSAO calculations. Default value is 8
  78769. */
  78770. set: function (n) {
  78771. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  78772. this._samples = n;
  78773. this._sampleSphere = this._generateHemisphere();
  78774. this._firstUpdate = true;
  78775. },
  78776. enumerable: true,
  78777. configurable: true
  78778. });
  78779. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  78780. get: function () {
  78781. return this._textureSamples;
  78782. },
  78783. /**
  78784. * Number of samples to use for antialiasing
  78785. */
  78786. set: function (n) {
  78787. this._textureSamples = n;
  78788. this._originalColorPostProcess.samples = n;
  78789. this._blurHPostProcess.samples = n;
  78790. this._blurVPostProcess.samples = n;
  78791. this._ssaoPostProcess.samples = n;
  78792. this._ssaoCombinePostProcess.samples = n;
  78793. },
  78794. enumerable: true,
  78795. configurable: true
  78796. });
  78797. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  78798. get: function () {
  78799. return this._expensiveBlur;
  78800. },
  78801. set: function (b) {
  78802. 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"]);
  78803. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  78804. this._expensiveBlur = b;
  78805. this._firstUpdate = true;
  78806. },
  78807. enumerable: true,
  78808. configurable: true
  78809. });
  78810. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  78811. /**
  78812. * Support test.
  78813. */
  78814. get: function () {
  78815. var engine = BABYLON.Engine.LastCreatedEngine;
  78816. if (!engine) {
  78817. return false;
  78818. }
  78819. return engine.getCaps().drawBuffersExtension;
  78820. },
  78821. enumerable: true,
  78822. configurable: true
  78823. });
  78824. // Public Methods
  78825. /**
  78826. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  78827. */
  78828. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  78829. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  78830. for (var i = 0; i < this._scene.cameras.length; i++) {
  78831. var camera = this._scene.cameras[i];
  78832. this._originalColorPostProcess.dispose(camera);
  78833. this._ssaoPostProcess.dispose(camera);
  78834. this._blurHPostProcess.dispose(camera);
  78835. this._blurVPostProcess.dispose(camera);
  78836. this._ssaoCombinePostProcess.dispose(camera);
  78837. }
  78838. this._randomTexture.dispose();
  78839. if (disableGeometryBufferRenderer)
  78840. this._scene.disableGeometryBufferRenderer();
  78841. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78842. _super.prototype.dispose.call(this);
  78843. };
  78844. // Private Methods
  78845. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  78846. var _this = this;
  78847. this._samplerOffsets = [];
  78848. var expensive = this.expensiveBlur;
  78849. for (var i = -8; i < 8; i++) {
  78850. this._samplerOffsets.push(i * 2 + 0.5);
  78851. }
  78852. 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");
  78853. this._blurHPostProcess.onApply = function (effect) {
  78854. if (!_this._scene.activeCamera) {
  78855. return;
  78856. }
  78857. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  78858. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78859. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78860. effect.setFloat("radius", _this.radius);
  78861. effect.setTexture("depthSampler", _this._depthTexture);
  78862. if (_this._firstUpdate) {
  78863. effect.setArray("samplerOffsets", _this._samplerOffsets);
  78864. }
  78865. };
  78866. 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");
  78867. this._blurVPostProcess.onApply = function (effect) {
  78868. if (!_this._scene.activeCamera) {
  78869. return;
  78870. }
  78871. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  78872. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78873. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78874. effect.setFloat("radius", _this.radius);
  78875. effect.setTexture("depthSampler", _this._depthTexture);
  78876. if (_this._firstUpdate) {
  78877. effect.setArray("samplerOffsets", _this._samplerOffsets);
  78878. _this._firstUpdate = false;
  78879. }
  78880. };
  78881. this._blurHPostProcess.samples = this.textureSamples;
  78882. this._blurVPostProcess.samples = this.textureSamples;
  78883. };
  78884. /** @hidden */
  78885. SSAO2RenderingPipeline.prototype._rebuild = function () {
  78886. this._firstUpdate = true;
  78887. _super.prototype._rebuild.call(this);
  78888. };
  78889. //Van der Corput radical inverse
  78890. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  78891. this._bits[0] = i;
  78892. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  78893. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  78894. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  78895. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  78896. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  78897. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  78898. };
  78899. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  78900. return [i / n, this._radicalInverse_VdC(i)];
  78901. };
  78902. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  78903. var phi = v * 2.0 * Math.PI;
  78904. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  78905. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  78906. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  78907. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  78908. };
  78909. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  78910. var numSamples = this.samples;
  78911. var result = [];
  78912. var vector;
  78913. var i = 0;
  78914. while (i < numSamples) {
  78915. if (numSamples < 16) {
  78916. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  78917. }
  78918. else {
  78919. var rand = this._hammersley(i, numSamples);
  78920. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  78921. }
  78922. result.push(vector.x, vector.y, vector.z);
  78923. i++;
  78924. }
  78925. return result;
  78926. };
  78927. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  78928. var _this = this;
  78929. var numSamples = this.samples;
  78930. this._sampleSphere = this._generateHemisphere();
  78931. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  78932. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  78933. "base", "range", "projection", "near", "far", "texelSize",
  78934. "xViewport", "yViewport", "maxZ", "minZAspect"
  78935. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  78936. this._ssaoPostProcess.onApply = function (effect) {
  78937. if (_this._firstUpdate) {
  78938. effect.setArray3("sampleSphere", _this._sampleSphere);
  78939. effect.setFloat("randTextureTiles", 32.0);
  78940. }
  78941. if (!_this._scene.activeCamera) {
  78942. return;
  78943. }
  78944. effect.setFloat("samplesFactor", 1 / _this.samples);
  78945. effect.setFloat("totalStrength", _this.totalStrength);
  78946. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  78947. effect.setFloat("radius", _this.radius);
  78948. effect.setFloat("maxZ", _this.maxZ);
  78949. effect.setFloat("minZAspect", _this.minZAspect);
  78950. effect.setFloat("base", _this.base);
  78951. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78952. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78953. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  78954. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  78955. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  78956. effect.setTexture("textureSampler", _this._depthTexture);
  78957. effect.setTexture("normalSampler", _this._normalTexture);
  78958. effect.setTexture("randomSampler", _this._randomTexture);
  78959. };
  78960. this._ssaoPostProcess.samples = this.textureSamples;
  78961. };
  78962. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  78963. var _this = this;
  78964. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78965. this._ssaoCombinePostProcess.onApply = function (effect) {
  78966. var viewport = _this._scene.activeCamera.viewport;
  78967. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  78968. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  78969. };
  78970. this._ssaoCombinePostProcess.samples = this.textureSamples;
  78971. };
  78972. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  78973. var size = 128;
  78974. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78975. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78976. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78977. var context = this._randomTexture.getContext();
  78978. var rand = function (min, max) {
  78979. return Math.random() * (max - min) + min;
  78980. };
  78981. var randVector = BABYLON.Vector3.Zero();
  78982. for (var x = 0; x < size; x++) {
  78983. for (var y = 0; y < size; y++) {
  78984. randVector.x = rand(0.0, 1.0);
  78985. randVector.y = rand(0.0, 1.0);
  78986. randVector.z = 0.0;
  78987. randVector.normalize();
  78988. randVector.scaleInPlace(255);
  78989. randVector.x = Math.floor(randVector.x);
  78990. randVector.y = Math.floor(randVector.y);
  78991. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  78992. context.fillRect(x, y, 1, 1);
  78993. }
  78994. }
  78995. this._randomTexture.update(false);
  78996. };
  78997. /**
  78998. * Serialize the rendering pipeline (Used when exporting)
  78999. * @returns the serialized object
  79000. */
  79001. SSAO2RenderingPipeline.prototype.serialize = function () {
  79002. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79003. serializationObject.customType = "SSAO2RenderingPipeline";
  79004. return serializationObject;
  79005. };
  79006. /**
  79007. * Parse the serialized pipeline
  79008. * @param source Source pipeline.
  79009. * @param scene The scene to load the pipeline to.
  79010. * @param rootUrl The URL of the serialized pipeline.
  79011. * @returns An instantiated pipeline from the serialized object.
  79012. */
  79013. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  79014. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  79015. };
  79016. __decorate([
  79017. BABYLON.serialize()
  79018. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  79019. __decorate([
  79020. BABYLON.serialize()
  79021. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  79022. __decorate([
  79023. BABYLON.serialize()
  79024. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  79025. __decorate([
  79026. BABYLON.serialize("samples")
  79027. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  79028. __decorate([
  79029. BABYLON.serialize("textureSamples")
  79030. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  79031. __decorate([
  79032. BABYLON.serialize()
  79033. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  79034. __decorate([
  79035. BABYLON.serialize("expensiveBlur")
  79036. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  79037. __decorate([
  79038. BABYLON.serialize()
  79039. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  79040. __decorate([
  79041. BABYLON.serialize()
  79042. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  79043. return SSAO2RenderingPipeline;
  79044. }(BABYLON.PostProcessRenderPipeline));
  79045. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  79046. })(BABYLON || (BABYLON = {}));
  79047. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  79048. // BABYLON.JS Chromatic Aberration GLSL Shader
  79049. // Author: Olivier Guyot
  79050. // Separates very slightly R, G and B colors on the edges of the screen
  79051. // Inspired by Francois Tarlier & Martins Upitis
  79052. var BABYLON;
  79053. (function (BABYLON) {
  79054. var LensRenderingPipeline = /** @class */ (function (_super) {
  79055. __extends(LensRenderingPipeline, _super);
  79056. /**
  79057. * @constructor
  79058. *
  79059. * Effect parameters are as follow:
  79060. * {
  79061. * chromatic_aberration: number; // from 0 to x (1 for realism)
  79062. * edge_blur: number; // from 0 to x (1 for realism)
  79063. * distortion: number; // from 0 to x (1 for realism)
  79064. * grain_amount: number; // from 0 to 1
  79065. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  79066. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  79067. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  79068. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  79069. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  79070. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  79071. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  79072. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  79073. * }
  79074. * Note: if an effect parameter is unset, effect is disabled
  79075. *
  79076. * @param {string} name - The rendering pipeline name
  79077. * @param {object} parameters - An object containing all parameters (see above)
  79078. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  79079. * @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)
  79080. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  79081. */
  79082. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  79083. if (ratio === void 0) { ratio = 1.0; }
  79084. var _this = _super.call(this, scene.getEngine(), name) || this;
  79085. // Lens effects can be of the following:
  79086. // - chromatic aberration (slight shift of RGB colors)
  79087. // - blur on the edge of the lens
  79088. // - lens distortion
  79089. // - depth-of-field blur & highlights enhancing
  79090. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  79091. // - grain effect (noise or custom texture)
  79092. // Two additional texture samplers are needed:
  79093. // - depth map (for depth-of-field)
  79094. // - grain texture
  79095. /**
  79096. * The chromatic aberration PostProcess id in the pipeline
  79097. */
  79098. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  79099. /**
  79100. * The highlights enhancing PostProcess id in the pipeline
  79101. */
  79102. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  79103. /**
  79104. * The depth-of-field PostProcess id in the pipeline
  79105. */
  79106. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  79107. _this._scene = scene;
  79108. // Fetch texture samplers
  79109. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  79110. if (parameters.grain_texture) {
  79111. _this._grainTexture = parameters.grain_texture;
  79112. }
  79113. else {
  79114. _this._createGrainTexture();
  79115. }
  79116. // save parameters
  79117. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  79118. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  79119. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  79120. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  79121. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  79122. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  79123. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  79124. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  79125. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  79126. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  79127. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  79128. // Create effects
  79129. _this._createChromaticAberrationPostProcess(ratio);
  79130. _this._createHighlightsPostProcess(ratio);
  79131. _this._createDepthOfFieldPostProcess(ratio / 4);
  79132. // Set up pipeline
  79133. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  79134. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  79135. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  79136. if (_this._highlightsGain === -1) {
  79137. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  79138. }
  79139. // Finish
  79140. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79141. if (cameras) {
  79142. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  79143. }
  79144. return _this;
  79145. }
  79146. // public methods (self explanatory)
  79147. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  79148. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  79149. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  79150. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  79151. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  79152. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  79153. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  79154. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  79155. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  79156. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  79157. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  79158. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  79159. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  79160. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  79161. };
  79162. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  79163. this._highlightsPostProcess.updateEffect();
  79164. };
  79165. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  79166. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  79167. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  79168. this._highlightsGain = amount;
  79169. };
  79170. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  79171. if (this._highlightsGain === -1) {
  79172. this._highlightsGain = 1.0;
  79173. }
  79174. this._highlightsThreshold = amount;
  79175. };
  79176. LensRenderingPipeline.prototype.disableHighlights = function () {
  79177. this._highlightsGain = -1;
  79178. };
  79179. /**
  79180. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  79181. */
  79182. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  79183. if (disableDepthRender === void 0) { disableDepthRender = false; }
  79184. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  79185. this._chromaticAberrationPostProcess = null;
  79186. this._highlightsPostProcess = null;
  79187. this._depthOfFieldPostProcess = null;
  79188. this._grainTexture.dispose();
  79189. if (disableDepthRender)
  79190. this._scene.disableDepthRenderer();
  79191. };
  79192. // colors shifting and distortion
  79193. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  79194. var _this = this;
  79195. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  79196. [], // samplers
  79197. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  79198. this._chromaticAberrationPostProcess.onApply = function (effect) {
  79199. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  79200. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  79201. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  79202. effect.setFloat('radialIntensity', 1);
  79203. effect.setFloat2('direction', 17, 17);
  79204. effect.setFloat2('centerPosition', 0.5, 0.5);
  79205. };
  79206. };
  79207. // highlights enhancing
  79208. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  79209. var _this = this;
  79210. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  79211. [], // samplers
  79212. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  79213. this._highlightsPostProcess.onApply = function (effect) {
  79214. effect.setFloat('gain', _this._highlightsGain);
  79215. effect.setFloat('threshold', _this._highlightsThreshold);
  79216. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  79217. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  79218. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  79219. };
  79220. };
  79221. // colors shifting and distortion
  79222. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  79223. var _this = this;
  79224. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  79225. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  79226. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  79227. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  79228. this._depthOfFieldPostProcess.onApply = function (effect) {
  79229. effect.setTexture("depthSampler", _this._depthTexture);
  79230. effect.setTexture("grainSampler", _this._grainTexture);
  79231. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  79232. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  79233. effect.setFloat('grain_amount', _this._grainAmount);
  79234. effect.setBool('blur_noise', _this._blurNoise);
  79235. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  79236. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  79237. effect.setFloat('distortion', _this._distortion);
  79238. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  79239. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  79240. effect.setFloat('aperture', _this._dofAperture);
  79241. effect.setFloat('darken', _this._dofDarken);
  79242. effect.setFloat('edge_blur', _this._edgeBlur);
  79243. effect.setBool('highlights', (_this._highlightsGain !== -1));
  79244. if (_this._scene.activeCamera) {
  79245. effect.setFloat('near', _this._scene.activeCamera.minZ);
  79246. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  79247. }
  79248. };
  79249. };
  79250. // creates a black and white random noise texture, 512x512
  79251. LensRenderingPipeline.prototype._createGrainTexture = function () {
  79252. var size = 512;
  79253. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79254. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  79255. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  79256. var context = this._grainTexture.getContext();
  79257. var rand = function (min, max) {
  79258. return Math.random() * (max - min) + min;
  79259. };
  79260. var value;
  79261. for (var x = 0; x < size; x++) {
  79262. for (var y = 0; y < size; y++) {
  79263. value = Math.floor(rand(0.42, 0.58) * 255);
  79264. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  79265. context.fillRect(x, y, 1, 1);
  79266. }
  79267. }
  79268. this._grainTexture.update(false);
  79269. };
  79270. return LensRenderingPipeline;
  79271. }(BABYLON.PostProcessRenderPipeline));
  79272. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  79273. })(BABYLON || (BABYLON = {}));
  79274. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  79275. var BABYLON;
  79276. (function (BABYLON) {
  79277. var StandardRenderingPipeline = /** @class */ (function (_super) {
  79278. __extends(StandardRenderingPipeline, _super);
  79279. /**
  79280. * @constructor
  79281. * @param {string} name - The rendering pipeline name
  79282. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  79283. * @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)
  79284. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  79285. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  79286. */
  79287. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  79288. if (originalPostProcess === void 0) { originalPostProcess = null; }
  79289. var _this = _super.call(this, scene.getEngine(), name) || this;
  79290. /**
  79291. * Post-process used to down scale an image x4
  79292. */
  79293. _this.downSampleX4PostProcess = null;
  79294. /**
  79295. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  79296. */
  79297. _this.brightPassPostProcess = null;
  79298. /**
  79299. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  79300. */
  79301. _this.blurHPostProcesses = [];
  79302. /**
  79303. * Post-process array storing all the vertical blur post-processes used by the pipeline
  79304. */
  79305. _this.blurVPostProcesses = [];
  79306. /**
  79307. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  79308. */
  79309. _this.textureAdderPostProcess = null;
  79310. /**
  79311. * Post-process used to create volumetric lighting effect
  79312. */
  79313. _this.volumetricLightPostProcess = null;
  79314. /**
  79315. * Post-process used to smooth the previous volumetric light post-process on the X axis
  79316. */
  79317. _this.volumetricLightSmoothXPostProcess = null;
  79318. /**
  79319. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  79320. */
  79321. _this.volumetricLightSmoothYPostProcess = null;
  79322. /**
  79323. * Post-process used to merge the volumetric light effect and the real scene color
  79324. */
  79325. _this.volumetricLightMergePostProces = null;
  79326. /**
  79327. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  79328. */
  79329. _this.volumetricLightFinalPostProcess = null;
  79330. /**
  79331. * Base post-process used to calculate the average luminance of the final image for HDR
  79332. */
  79333. _this.luminancePostProcess = null;
  79334. /**
  79335. * Post-processes used to create down sample post-processes in order to get
  79336. * the average luminance of the final image for HDR
  79337. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  79338. */
  79339. _this.luminanceDownSamplePostProcesses = [];
  79340. /**
  79341. * Post-process used to create a HDR effect (light adaptation)
  79342. */
  79343. _this.hdrPostProcess = null;
  79344. /**
  79345. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  79346. */
  79347. _this.textureAdderFinalPostProcess = null;
  79348. /**
  79349. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  79350. */
  79351. _this.lensFlareFinalPostProcess = null;
  79352. /**
  79353. * Post-process used to merge the final HDR post-process and the real scene color
  79354. */
  79355. _this.hdrFinalPostProcess = null;
  79356. /**
  79357. * Post-process used to create a lens flare effect
  79358. */
  79359. _this.lensFlarePostProcess = null;
  79360. /**
  79361. * Post-process that merges the result of the lens flare post-process and the real scene color
  79362. */
  79363. _this.lensFlareComposePostProcess = null;
  79364. /**
  79365. * Post-process used to create a motion blur effect
  79366. */
  79367. _this.motionBlurPostProcess = null;
  79368. /**
  79369. * Post-process used to create a depth of field effect
  79370. */
  79371. _this.depthOfFieldPostProcess = null;
  79372. /**
  79373. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  79374. */
  79375. _this.fxaaPostProcess = null;
  79376. // Values
  79377. /**
  79378. * Represents the brightness threshold in order to configure the illuminated surfaces
  79379. */
  79380. _this.brightThreshold = 1.0;
  79381. /**
  79382. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  79383. */
  79384. _this.blurWidth = 512.0;
  79385. /**
  79386. * Sets if the blur for highlighted surfaces must be only horizontal
  79387. */
  79388. _this.horizontalBlur = false;
  79389. /**
  79390. * Sets the overall exposure used by the pipeline
  79391. */
  79392. _this.exposure = 1.0;
  79393. /**
  79394. * Texture used typically to simulate "dirty" on camera lens
  79395. */
  79396. _this.lensTexture = null;
  79397. /**
  79398. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  79399. */
  79400. _this.volumetricLightCoefficient = 0.2;
  79401. /**
  79402. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  79403. */
  79404. _this.volumetricLightPower = 4.0;
  79405. /**
  79406. * Used the set the blur intensity to smooth the volumetric lights
  79407. */
  79408. _this.volumetricLightBlurScale = 64.0;
  79409. /**
  79410. * Light (spot or directional) used to generate the volumetric lights rays
  79411. * The source light must have a shadow generate so the pipeline can get its
  79412. * depth map
  79413. */
  79414. _this.sourceLight = null;
  79415. /**
  79416. * For eye adaptation, represents the minimum luminance the eye can see
  79417. */
  79418. _this.hdrMinimumLuminance = 1.0;
  79419. /**
  79420. * For eye adaptation, represents the decrease luminance speed
  79421. */
  79422. _this.hdrDecreaseRate = 0.5;
  79423. /**
  79424. * For eye adaptation, represents the increase luminance speed
  79425. */
  79426. _this.hdrIncreaseRate = 0.5;
  79427. /**
  79428. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  79429. */
  79430. _this.lensColorTexture = null;
  79431. /**
  79432. * The overall strengh for the lens flare effect
  79433. */
  79434. _this.lensFlareStrength = 20.0;
  79435. /**
  79436. * Dispersion coefficient for lens flare ghosts
  79437. */
  79438. _this.lensFlareGhostDispersal = 1.4;
  79439. /**
  79440. * Main lens flare halo width
  79441. */
  79442. _this.lensFlareHaloWidth = 0.7;
  79443. /**
  79444. * Based on the lens distortion effect, defines how much the lens flare result
  79445. * is distorted
  79446. */
  79447. _this.lensFlareDistortionStrength = 16.0;
  79448. /**
  79449. * Lens star texture must be used to simulate rays on the flares and is available
  79450. * in the documentation
  79451. */
  79452. _this.lensStarTexture = null;
  79453. /**
  79454. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  79455. * flare effect by taking account of the dirt texture
  79456. */
  79457. _this.lensFlareDirtTexture = null;
  79458. /**
  79459. * Represents the focal length for the depth of field effect
  79460. */
  79461. _this.depthOfFieldDistance = 10.0;
  79462. /**
  79463. * Represents the blur intensity for the blurred part of the depth of field effect
  79464. */
  79465. _this.depthOfFieldBlurWidth = 64.0;
  79466. /**
  79467. * For motion blur, defines how much the image is blurred by the movement
  79468. */
  79469. _this.motionStrength = 1.0;
  79470. /**
  79471. * List of animations for the pipeline (IAnimatable implementation)
  79472. */
  79473. _this.animations = [];
  79474. _this._currentDepthOfFieldSource = null;
  79475. _this._hdrCurrentLuminance = 1.0;
  79476. // Getters and setters
  79477. _this._bloomEnabled = false;
  79478. _this._depthOfFieldEnabled = false;
  79479. _this._vlsEnabled = false;
  79480. _this._lensFlareEnabled = false;
  79481. _this._hdrEnabled = false;
  79482. _this._motionBlurEnabled = false;
  79483. _this._fxaaEnabled = false;
  79484. _this._motionBlurSamples = 64.0;
  79485. _this._volumetricLightStepsCount = 50.0;
  79486. _this._samples = 1;
  79487. _this._cameras = cameras || [];
  79488. // Initialize
  79489. _this._scene = scene;
  79490. _this._basePostProcess = originalPostProcess;
  79491. _this._ratio = ratio;
  79492. // Misc
  79493. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79494. // Finish
  79495. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79496. _this._buildPipeline();
  79497. return _this;
  79498. }
  79499. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  79500. /**
  79501. * Specifies if the bloom pipeline is enabled
  79502. */
  79503. get: function () {
  79504. return this._bloomEnabled;
  79505. },
  79506. set: function (enabled) {
  79507. if (this._bloomEnabled === enabled) {
  79508. return;
  79509. }
  79510. this._bloomEnabled = enabled;
  79511. this._buildPipeline();
  79512. },
  79513. enumerable: true,
  79514. configurable: true
  79515. });
  79516. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  79517. /**
  79518. * Specifies if the depth of field pipeline is enabed
  79519. */
  79520. get: function () {
  79521. return this._depthOfFieldEnabled;
  79522. },
  79523. set: function (enabled) {
  79524. if (this._depthOfFieldEnabled === enabled) {
  79525. return;
  79526. }
  79527. this._depthOfFieldEnabled = enabled;
  79528. this._buildPipeline();
  79529. },
  79530. enumerable: true,
  79531. configurable: true
  79532. });
  79533. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  79534. /**
  79535. * Specifies if the lens flare pipeline is enabed
  79536. */
  79537. get: function () {
  79538. return this._lensFlareEnabled;
  79539. },
  79540. set: function (enabled) {
  79541. if (this._lensFlareEnabled === enabled) {
  79542. return;
  79543. }
  79544. this._lensFlareEnabled = enabled;
  79545. this._buildPipeline();
  79546. },
  79547. enumerable: true,
  79548. configurable: true
  79549. });
  79550. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  79551. /**
  79552. * Specifies if the HDR pipeline is enabled
  79553. */
  79554. get: function () {
  79555. return this._hdrEnabled;
  79556. },
  79557. set: function (enabled) {
  79558. if (this._hdrEnabled === enabled) {
  79559. return;
  79560. }
  79561. this._hdrEnabled = enabled;
  79562. this._buildPipeline();
  79563. },
  79564. enumerable: true,
  79565. configurable: true
  79566. });
  79567. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  79568. /**
  79569. * Specifies if the volumetric lights scattering effect is enabled
  79570. */
  79571. get: function () {
  79572. return this._vlsEnabled;
  79573. },
  79574. set: function (enabled) {
  79575. if (this._vlsEnabled === enabled) {
  79576. return;
  79577. }
  79578. if (enabled) {
  79579. var geometry = this._scene.enableGeometryBufferRenderer();
  79580. if (!geometry) {
  79581. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  79582. return;
  79583. }
  79584. }
  79585. this._vlsEnabled = enabled;
  79586. this._buildPipeline();
  79587. },
  79588. enumerable: true,
  79589. configurable: true
  79590. });
  79591. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  79592. /**
  79593. * Specifies if the motion blur effect is enabled
  79594. */
  79595. get: function () {
  79596. return this._motionBlurEnabled;
  79597. },
  79598. set: function (enabled) {
  79599. if (this._motionBlurEnabled === enabled) {
  79600. return;
  79601. }
  79602. this._motionBlurEnabled = enabled;
  79603. this._buildPipeline();
  79604. },
  79605. enumerable: true,
  79606. configurable: true
  79607. });
  79608. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  79609. /**
  79610. * Specifies if anti-aliasing is enabled
  79611. */
  79612. get: function () {
  79613. return this._fxaaEnabled;
  79614. },
  79615. set: function (enabled) {
  79616. if (this._fxaaEnabled === enabled) {
  79617. return;
  79618. }
  79619. this._fxaaEnabled = enabled;
  79620. this._buildPipeline();
  79621. },
  79622. enumerable: true,
  79623. configurable: true
  79624. });
  79625. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  79626. /**
  79627. * Specifies the number of steps used to calculate the volumetric lights
  79628. * Typically in interval [50, 200]
  79629. */
  79630. get: function () {
  79631. return this._volumetricLightStepsCount;
  79632. },
  79633. set: function (count) {
  79634. if (this.volumetricLightPostProcess) {
  79635. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  79636. }
  79637. this._volumetricLightStepsCount = count;
  79638. },
  79639. enumerable: true,
  79640. configurable: true
  79641. });
  79642. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  79643. /**
  79644. * Specifies the number of samples used for the motion blur effect
  79645. * Typically in interval [16, 64]
  79646. */
  79647. get: function () {
  79648. return this._motionBlurSamples;
  79649. },
  79650. set: function (samples) {
  79651. if (this.motionBlurPostProcess) {
  79652. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  79653. }
  79654. this._motionBlurSamples = samples;
  79655. },
  79656. enumerable: true,
  79657. configurable: true
  79658. });
  79659. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  79660. /**
  79661. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  79662. */
  79663. get: function () {
  79664. return this._samples;
  79665. },
  79666. set: function (sampleCount) {
  79667. if (this._samples === sampleCount) {
  79668. return;
  79669. }
  79670. this._samples = sampleCount;
  79671. this._buildPipeline();
  79672. },
  79673. enumerable: true,
  79674. configurable: true
  79675. });
  79676. StandardRenderingPipeline.prototype._buildPipeline = function () {
  79677. var _this = this;
  79678. var ratio = this._ratio;
  79679. var scene = this._scene;
  79680. this._disposePostProcesses();
  79681. this._reset();
  79682. // Create pass post-process
  79683. if (!this._basePostProcess) {
  79684. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  79685. this.originalPostProcess.onApply = function (effect) {
  79686. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  79687. };
  79688. }
  79689. else {
  79690. this.originalPostProcess = this._basePostProcess;
  79691. }
  79692. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  79693. this._currentDepthOfFieldSource = this.originalPostProcess;
  79694. if (this._bloomEnabled) {
  79695. // Create down sample X4 post-process
  79696. this._createDownSampleX4PostProcess(scene, ratio / 2);
  79697. // Create bright pass post-process
  79698. this._createBrightPassPostProcess(scene, ratio / 2);
  79699. // Create gaussian blur post-processes (down sampling blurs)
  79700. this._createBlurPostProcesses(scene, ratio / 4, 1);
  79701. // Create texture adder post-process
  79702. this._createTextureAdderPostProcess(scene, ratio);
  79703. // Create depth-of-field source post-process
  79704. 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);
  79705. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  79706. }
  79707. if (this._vlsEnabled) {
  79708. // Create volumetric light
  79709. this._createVolumetricLightPostProcess(scene, ratio);
  79710. // Create volumetric light final post-process
  79711. 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);
  79712. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  79713. }
  79714. if (this._lensFlareEnabled) {
  79715. // Create lens flare post-process
  79716. this._createLensFlarePostProcess(scene, ratio);
  79717. // Create depth-of-field source post-process post lens-flare and disable it now
  79718. 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);
  79719. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  79720. }
  79721. if (this._hdrEnabled) {
  79722. // Create luminance
  79723. this._createLuminancePostProcesses(scene, this._floatTextureType);
  79724. // Create HDR
  79725. this._createHdrPostProcess(scene, ratio);
  79726. // Create depth-of-field source post-process post hdr and disable it now
  79727. 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);
  79728. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  79729. }
  79730. if (this._depthOfFieldEnabled) {
  79731. // Create gaussian blur used by depth-of-field
  79732. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  79733. // Create depth-of-field post-process
  79734. this._createDepthOfFieldPostProcess(scene, ratio);
  79735. }
  79736. if (this._motionBlurEnabled) {
  79737. // Create motion blur post-process
  79738. this._createMotionBlurPostProcess(scene, ratio);
  79739. }
  79740. if (this._fxaaEnabled) {
  79741. // Create fxaa post-process
  79742. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  79743. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  79744. }
  79745. if (this._cameras !== null) {
  79746. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  79747. }
  79748. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  79749. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  79750. }
  79751. };
  79752. // Down Sample X4 Post-Processs
  79753. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  79754. var _this = this;
  79755. var downSampleX4Offsets = new Array(32);
  79756. 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);
  79757. this.downSampleX4PostProcess.onApply = function (effect) {
  79758. var id = 0;
  79759. var width = _this.downSampleX4PostProcess.width;
  79760. var height = _this.downSampleX4PostProcess.height;
  79761. for (var i = -2; i < 2; i++) {
  79762. for (var j = -2; j < 2; j++) {
  79763. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  79764. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  79765. id += 2;
  79766. }
  79767. }
  79768. effect.setArray2("dsOffsets", downSampleX4Offsets);
  79769. };
  79770. // Add to pipeline
  79771. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  79772. };
  79773. // Brightpass Post-Process
  79774. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  79775. var _this = this;
  79776. var brightOffsets = new Array(8);
  79777. 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);
  79778. this.brightPassPostProcess.onApply = function (effect) {
  79779. var sU = (1.0 / _this.brightPassPostProcess.width);
  79780. var sV = (1.0 / _this.brightPassPostProcess.height);
  79781. brightOffsets[0] = -0.5 * sU;
  79782. brightOffsets[1] = 0.5 * sV;
  79783. brightOffsets[2] = 0.5 * sU;
  79784. brightOffsets[3] = 0.5 * sV;
  79785. brightOffsets[4] = -0.5 * sU;
  79786. brightOffsets[5] = -0.5 * sV;
  79787. brightOffsets[6] = 0.5 * sU;
  79788. brightOffsets[7] = -0.5 * sV;
  79789. effect.setArray2("dsOffsets", brightOffsets);
  79790. effect.setFloat("brightThreshold", _this.brightThreshold);
  79791. };
  79792. // Add to pipeline
  79793. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  79794. };
  79795. // Create blur H&V post-processes
  79796. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  79797. var _this = this;
  79798. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  79799. var engine = scene.getEngine();
  79800. 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);
  79801. 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);
  79802. blurX.onActivateObservable.add(function () {
  79803. var dw = blurX.width / engine.getRenderWidth();
  79804. blurX.kernel = _this[blurWidthKey] * dw;
  79805. });
  79806. blurY.onActivateObservable.add(function () {
  79807. var dw = blurY.height / engine.getRenderHeight();
  79808. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  79809. });
  79810. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  79811. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  79812. this.blurHPostProcesses.push(blurX);
  79813. this.blurVPostProcesses.push(blurY);
  79814. };
  79815. // Create texture adder post-process
  79816. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  79817. var _this = this;
  79818. 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);
  79819. this.textureAdderPostProcess.onApply = function (effect) {
  79820. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  79821. effect.setTexture("lensSampler", _this.lensTexture);
  79822. effect.setFloat("exposure", _this.exposure);
  79823. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  79824. };
  79825. // Add to pipeline
  79826. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  79827. };
  79828. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  79829. var _this = this;
  79830. var geometryRenderer = scene.enableGeometryBufferRenderer();
  79831. geometryRenderer.enablePosition = true;
  79832. var geometry = geometryRenderer.getGBuffer();
  79833. // Base post-process
  79834. 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));
  79835. var depthValues = BABYLON.Vector2.Zero();
  79836. this.volumetricLightPostProcess.onApply = function (effect) {
  79837. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  79838. var generator = _this.sourceLight.getShadowGenerator();
  79839. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  79840. effect.setTexture("positionSampler", geometry.textures[2]);
  79841. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  79842. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  79843. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  79844. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  79845. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  79846. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  79847. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  79848. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  79849. effect.setVector2("depthValues", depthValues);
  79850. }
  79851. };
  79852. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  79853. // Smooth
  79854. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  79855. // Merge
  79856. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  79857. this.volumetricLightMergePostProces.onApply = function (effect) {
  79858. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  79859. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  79860. };
  79861. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  79862. };
  79863. // Create luminance
  79864. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  79865. var _this = this;
  79866. // Create luminance
  79867. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  79868. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  79869. var offsets = [];
  79870. this.luminancePostProcess.onApply = function (effect) {
  79871. var sU = (1.0 / _this.luminancePostProcess.width);
  79872. var sV = (1.0 / _this.luminancePostProcess.height);
  79873. offsets[0] = -0.5 * sU;
  79874. offsets[1] = 0.5 * sV;
  79875. offsets[2] = 0.5 * sU;
  79876. offsets[3] = 0.5 * sV;
  79877. offsets[4] = -0.5 * sU;
  79878. offsets[5] = -0.5 * sV;
  79879. offsets[6] = 0.5 * sU;
  79880. offsets[7] = -0.5 * sV;
  79881. effect.setArray2("lumOffsets", offsets);
  79882. };
  79883. // Add to pipeline
  79884. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  79885. // Create down sample luminance
  79886. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  79887. var size = Math.pow(3, i);
  79888. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  79889. if (i === 0) {
  79890. defines += "#define FINAL_DOWN_SAMPLER";
  79891. }
  79892. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  79893. this.luminanceDownSamplePostProcesses.push(postProcess);
  79894. }
  79895. // Create callbacks and add effects
  79896. var lastLuminance = this.luminancePostProcess;
  79897. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  79898. var downSampleOffsets = new Array(18);
  79899. pp.onApply = function (effect) {
  79900. if (!lastLuminance) {
  79901. return;
  79902. }
  79903. var id = 0;
  79904. for (var x = -1; x < 2; x++) {
  79905. for (var y = -1; y < 2; y++) {
  79906. downSampleOffsets[id] = x / lastLuminance.width;
  79907. downSampleOffsets[id + 1] = y / lastLuminance.height;
  79908. id += 2;
  79909. }
  79910. }
  79911. effect.setArray2("dsOffsets", downSampleOffsets);
  79912. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  79913. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  79914. lastLuminance = _this.luminancePostProcess;
  79915. }
  79916. else {
  79917. lastLuminance = pp;
  79918. }
  79919. };
  79920. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  79921. pp.onAfterRender = function (effect) {
  79922. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  79923. 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);
  79924. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  79925. };
  79926. }
  79927. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  79928. });
  79929. };
  79930. // Create HDR post-process
  79931. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  79932. var _this = this;
  79933. 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);
  79934. var outputLiminance = 1;
  79935. var time = 0;
  79936. var lastTime = 0;
  79937. this.hdrPostProcess.onApply = function (effect) {
  79938. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  79939. time += scene.getEngine().getDeltaTime();
  79940. if (outputLiminance < 0) {
  79941. outputLiminance = _this._hdrCurrentLuminance;
  79942. }
  79943. else {
  79944. var dt = (lastTime - time) / 1000.0;
  79945. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  79946. outputLiminance += _this.hdrDecreaseRate * dt;
  79947. }
  79948. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  79949. outputLiminance -= _this.hdrIncreaseRate * dt;
  79950. }
  79951. else {
  79952. outputLiminance = _this._hdrCurrentLuminance;
  79953. }
  79954. }
  79955. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  79956. effect.setFloat("averageLuminance", outputLiminance);
  79957. lastTime = time;
  79958. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  79959. };
  79960. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  79961. };
  79962. // Create lens flare post-process
  79963. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  79964. var _this = this;
  79965. 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);
  79966. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  79967. this._createBlurPostProcesses(scene, ratio / 4, 2);
  79968. 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);
  79969. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  79970. var resolution = new BABYLON.Vector2(0, 0);
  79971. // Lens flare
  79972. this.lensFlarePostProcess.onApply = function (effect) {
  79973. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  79974. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  79975. effect.setFloat("strength", _this.lensFlareStrength);
  79976. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  79977. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  79978. // Shift
  79979. resolution.x = _this.lensFlarePostProcess.width;
  79980. resolution.y = _this.lensFlarePostProcess.height;
  79981. effect.setVector2("resolution", resolution);
  79982. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  79983. };
  79984. // Compose
  79985. 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);
  79986. 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);
  79987. this.lensFlareComposePostProcess.onApply = function (effect) {
  79988. if (!_this._scene.activeCamera) {
  79989. return;
  79990. }
  79991. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  79992. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  79993. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  79994. // Lens start rotation matrix
  79995. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  79996. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  79997. 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));
  79998. camRot *= 4.0;
  79999. 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);
  80000. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  80001. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  80002. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  80003. };
  80004. };
  80005. // Create depth-of-field post-process
  80006. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  80007. var _this = this;
  80008. 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);
  80009. this.depthOfFieldPostProcess.onApply = function (effect) {
  80010. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  80011. effect.setTexture("depthSampler", _this._getDepthTexture());
  80012. effect.setFloat("distance", _this.depthOfFieldDistance);
  80013. };
  80014. // Add to pipeline
  80015. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  80016. };
  80017. // Create motion blur post-process
  80018. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  80019. var _this = this;
  80020. 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);
  80021. var motionScale = 0;
  80022. var prevViewProjection = BABYLON.Matrix.Identity();
  80023. var invViewProjection = BABYLON.Matrix.Identity();
  80024. var viewProjection = BABYLON.Matrix.Identity();
  80025. var screenSize = BABYLON.Vector2.Zero();
  80026. this.motionBlurPostProcess.onApply = function (effect) {
  80027. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  80028. viewProjection.invertToRef(invViewProjection);
  80029. effect.setMatrix("inverseViewProjection", invViewProjection);
  80030. effect.setMatrix("prevViewProjection", prevViewProjection);
  80031. prevViewProjection = viewProjection;
  80032. screenSize.x = _this.motionBlurPostProcess.width;
  80033. screenSize.y = _this.motionBlurPostProcess.height;
  80034. effect.setVector2("screenSize", screenSize);
  80035. motionScale = scene.getEngine().getFps() / 60.0;
  80036. effect.setFloat("motionScale", motionScale);
  80037. effect.setFloat("motionStrength", _this.motionStrength);
  80038. effect.setTexture("depthSampler", _this._getDepthTexture());
  80039. };
  80040. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  80041. };
  80042. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  80043. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  80044. var renderer = this._scene.enableGeometryBufferRenderer();
  80045. return renderer.getGBuffer().textures[0];
  80046. }
  80047. return this._scene.enableDepthRenderer().getDepthMap();
  80048. };
  80049. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  80050. for (var i = 0; i < this._cameras.length; i++) {
  80051. var camera = this._cameras[i];
  80052. if (this.originalPostProcess) {
  80053. this.originalPostProcess.dispose(camera);
  80054. }
  80055. if (this.downSampleX4PostProcess) {
  80056. this.downSampleX4PostProcess.dispose(camera);
  80057. }
  80058. if (this.brightPassPostProcess) {
  80059. this.brightPassPostProcess.dispose(camera);
  80060. }
  80061. if (this.textureAdderPostProcess) {
  80062. this.textureAdderPostProcess.dispose(camera);
  80063. }
  80064. if (this.textureAdderFinalPostProcess) {
  80065. this.textureAdderFinalPostProcess.dispose(camera);
  80066. }
  80067. if (this.volumetricLightPostProcess) {
  80068. this.volumetricLightPostProcess.dispose(camera);
  80069. }
  80070. if (this.volumetricLightSmoothXPostProcess) {
  80071. this.volumetricLightSmoothXPostProcess.dispose(camera);
  80072. }
  80073. if (this.volumetricLightSmoothYPostProcess) {
  80074. this.volumetricLightSmoothYPostProcess.dispose(camera);
  80075. }
  80076. if (this.volumetricLightMergePostProces) {
  80077. this.volumetricLightMergePostProces.dispose(camera);
  80078. }
  80079. if (this.volumetricLightFinalPostProcess) {
  80080. this.volumetricLightFinalPostProcess.dispose(camera);
  80081. }
  80082. if (this.lensFlarePostProcess) {
  80083. this.lensFlarePostProcess.dispose(camera);
  80084. }
  80085. if (this.lensFlareComposePostProcess) {
  80086. this.lensFlareComposePostProcess.dispose(camera);
  80087. }
  80088. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  80089. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  80090. }
  80091. if (this.luminancePostProcess) {
  80092. this.luminancePostProcess.dispose(camera);
  80093. }
  80094. if (this.hdrPostProcess) {
  80095. this.hdrPostProcess.dispose(camera);
  80096. }
  80097. if (this.hdrFinalPostProcess) {
  80098. this.hdrFinalPostProcess.dispose(camera);
  80099. }
  80100. if (this.depthOfFieldPostProcess) {
  80101. this.depthOfFieldPostProcess.dispose(camera);
  80102. }
  80103. if (this.motionBlurPostProcess) {
  80104. this.motionBlurPostProcess.dispose(camera);
  80105. }
  80106. if (this.fxaaPostProcess) {
  80107. this.fxaaPostProcess.dispose(camera);
  80108. }
  80109. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  80110. this.blurHPostProcesses[j].dispose(camera);
  80111. }
  80112. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  80113. this.blurVPostProcesses[j].dispose(camera);
  80114. }
  80115. }
  80116. this.originalPostProcess = null;
  80117. this.downSampleX4PostProcess = null;
  80118. this.brightPassPostProcess = null;
  80119. this.textureAdderPostProcess = null;
  80120. this.textureAdderFinalPostProcess = null;
  80121. this.volumetricLightPostProcess = null;
  80122. this.volumetricLightSmoothXPostProcess = null;
  80123. this.volumetricLightSmoothYPostProcess = null;
  80124. this.volumetricLightMergePostProces = null;
  80125. this.volumetricLightFinalPostProcess = null;
  80126. this.lensFlarePostProcess = null;
  80127. this.lensFlareComposePostProcess = null;
  80128. this.luminancePostProcess = null;
  80129. this.hdrPostProcess = null;
  80130. this.hdrFinalPostProcess = null;
  80131. this.depthOfFieldPostProcess = null;
  80132. this.motionBlurPostProcess = null;
  80133. this.fxaaPostProcess = null;
  80134. this.luminanceDownSamplePostProcesses = [];
  80135. this.blurHPostProcesses = [];
  80136. this.blurVPostProcesses = [];
  80137. };
  80138. /**
  80139. * Dispose of the pipeline and stop all post processes
  80140. */
  80141. StandardRenderingPipeline.prototype.dispose = function () {
  80142. this._disposePostProcesses();
  80143. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  80144. _super.prototype.dispose.call(this);
  80145. };
  80146. /**
  80147. * Serialize the rendering pipeline (Used when exporting)
  80148. * @returns the serialized object
  80149. */
  80150. StandardRenderingPipeline.prototype.serialize = function () {
  80151. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80152. if (this.sourceLight) {
  80153. serializationObject.sourceLightId = this.sourceLight.id;
  80154. }
  80155. serializationObject.customType = "StandardRenderingPipeline";
  80156. return serializationObject;
  80157. };
  80158. /**
  80159. * Parse the serialized pipeline
  80160. * @param source Source pipeline.
  80161. * @param scene The scene to load the pipeline to.
  80162. * @param rootUrl The URL of the serialized pipeline.
  80163. * @returns An instantiated pipeline from the serialized object.
  80164. */
  80165. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  80166. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  80167. if (source.sourceLightId) {
  80168. p.sourceLight = scene.getLightByID(source.sourceLightId);
  80169. }
  80170. return p;
  80171. };
  80172. // Luminance steps
  80173. StandardRenderingPipeline.LuminanceSteps = 6;
  80174. __decorate([
  80175. BABYLON.serialize()
  80176. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  80177. __decorate([
  80178. BABYLON.serialize()
  80179. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  80180. __decorate([
  80181. BABYLON.serialize()
  80182. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  80183. __decorate([
  80184. BABYLON.serialize()
  80185. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  80186. __decorate([
  80187. BABYLON.serializeAsTexture("lensTexture")
  80188. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  80189. __decorate([
  80190. BABYLON.serialize()
  80191. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  80192. __decorate([
  80193. BABYLON.serialize()
  80194. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  80195. __decorate([
  80196. BABYLON.serialize()
  80197. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  80198. __decorate([
  80199. BABYLON.serialize()
  80200. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  80201. __decorate([
  80202. BABYLON.serialize()
  80203. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  80204. __decorate([
  80205. BABYLON.serialize()
  80206. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  80207. __decorate([
  80208. BABYLON.serializeAsTexture("lensColorTexture")
  80209. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  80210. __decorate([
  80211. BABYLON.serialize()
  80212. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  80213. __decorate([
  80214. BABYLON.serialize()
  80215. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  80216. __decorate([
  80217. BABYLON.serialize()
  80218. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  80219. __decorate([
  80220. BABYLON.serialize()
  80221. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  80222. __decorate([
  80223. BABYLON.serializeAsTexture("lensStarTexture")
  80224. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  80225. __decorate([
  80226. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  80227. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  80228. __decorate([
  80229. BABYLON.serialize()
  80230. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  80231. __decorate([
  80232. BABYLON.serialize()
  80233. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  80234. __decorate([
  80235. BABYLON.serialize()
  80236. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  80237. __decorate([
  80238. BABYLON.serialize()
  80239. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  80240. __decorate([
  80241. BABYLON.serialize()
  80242. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  80243. __decorate([
  80244. BABYLON.serialize()
  80245. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  80246. __decorate([
  80247. BABYLON.serialize()
  80248. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  80249. __decorate([
  80250. BABYLON.serialize()
  80251. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  80252. __decorate([
  80253. BABYLON.serialize()
  80254. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  80255. __decorate([
  80256. BABYLON.serialize()
  80257. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  80258. __decorate([
  80259. BABYLON.serialize()
  80260. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  80261. __decorate([
  80262. BABYLON.serialize()
  80263. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  80264. __decorate([
  80265. BABYLON.serialize()
  80266. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  80267. __decorate([
  80268. BABYLON.serialize()
  80269. ], StandardRenderingPipeline.prototype, "samples", null);
  80270. return StandardRenderingPipeline;
  80271. }(BABYLON.PostProcessRenderPipeline));
  80272. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  80273. })(BABYLON || (BABYLON = {}));
  80274. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  80275. var BABYLON;
  80276. (function (BABYLON) {
  80277. var FxaaPostProcess = /** @class */ (function (_super) {
  80278. __extends(FxaaPostProcess, _super);
  80279. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  80280. if (camera === void 0) { camera = null; }
  80281. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80282. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  80283. var defines = _this._getDefines();
  80284. _this.updateEffect(defines);
  80285. _this.onApplyObservable.add(function (effect) {
  80286. var texelSize = _this.texelSize;
  80287. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  80288. });
  80289. return _this;
  80290. }
  80291. FxaaPostProcess.prototype._getDefines = function () {
  80292. var engine = this.getEngine();
  80293. if (!engine) {
  80294. return null;
  80295. }
  80296. var glInfo = engine.getGlInfo();
  80297. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  80298. return "#define MALI 1\n";
  80299. }
  80300. return null;
  80301. };
  80302. return FxaaPostProcess;
  80303. }(BABYLON.PostProcess));
  80304. BABYLON.FxaaPostProcess = FxaaPostProcess;
  80305. })(BABYLON || (BABYLON = {}));
  80306. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  80307. var BABYLON;
  80308. (function (BABYLON) {
  80309. /**
  80310. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  80311. */
  80312. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  80313. __extends(ChromaticAberrationPostProcess, _super);
  80314. /**
  80315. * Creates a new instance ChromaticAberrationPostProcess
  80316. * @param name The name of the effect.
  80317. * @param screenWidth The width of the screen to apply the effect on.
  80318. * @param screenHeight The height of the screen to apply the effect on.
  80319. * @param options The required width/height ratio to downsize to before computing the render pass.
  80320. * @param camera The camera to apply the render pass to.
  80321. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80322. * @param engine The engine which the post process will be applied. (default: current engine)
  80323. * @param reusable If the post process can be reused on the same frame. (default: false)
  80324. * @param textureType Type of textures used when performing the post process. (default: 0)
  80325. * @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)
  80326. */
  80327. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80328. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80329. if (blockCompilation === void 0) { blockCompilation = false; }
  80330. 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;
  80331. /**
  80332. * The amount of seperation of rgb channels (default: 30)
  80333. */
  80334. _this.aberrationAmount = 30;
  80335. /**
  80336. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  80337. */
  80338. _this.radialIntensity = 0;
  80339. /**
  80340. * 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))
  80341. */
  80342. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  80343. /**
  80344. * 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))
  80345. */
  80346. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  80347. _this.onApplyObservable.add(function (effect) {
  80348. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  80349. effect.setFloat('screen_width', screenWidth);
  80350. effect.setFloat('screen_height', screenHeight);
  80351. effect.setFloat('radialIntensity', _this.radialIntensity);
  80352. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  80353. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  80354. });
  80355. return _this;
  80356. }
  80357. return ChromaticAberrationPostProcess;
  80358. }(BABYLON.PostProcess));
  80359. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  80360. })(BABYLON || (BABYLON = {}));
  80361. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  80362. var BABYLON;
  80363. (function (BABYLON) {
  80364. /**
  80365. * The GrainPostProcess adds noise to the image at mid luminance levels
  80366. */
  80367. var GrainPostProcess = /** @class */ (function (_super) {
  80368. __extends(GrainPostProcess, _super);
  80369. /**
  80370. * Creates a new instance of @see GrainPostProcess
  80371. * @param name The name of the effect.
  80372. * @param options The required width/height ratio to downsize to before computing the render pass.
  80373. * @param camera The camera to apply the render pass to.
  80374. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80375. * @param engine The engine which the post process will be applied. (default: current engine)
  80376. * @param reusable If the post process can be reused on the same frame. (default: false)
  80377. * @param textureType Type of textures used when performing the post process. (default: 0)
  80378. * @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)
  80379. */
  80380. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80381. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80382. if (blockCompilation === void 0) { blockCompilation = false; }
  80383. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80384. /**
  80385. * The intensity of the grain added (default: 30)
  80386. */
  80387. _this.intensity = 30;
  80388. /**
  80389. * If the grain should be randomized on every frame
  80390. */
  80391. _this.animated = false;
  80392. _this.onApplyObservable.add(function (effect) {
  80393. effect.setFloat('intensity', _this.intensity);
  80394. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  80395. });
  80396. return _this;
  80397. }
  80398. return GrainPostProcess;
  80399. }(BABYLON.PostProcess));
  80400. BABYLON.GrainPostProcess = GrainPostProcess;
  80401. })(BABYLON || (BABYLON = {}));
  80402. //# sourceMappingURL=babylon.grainPostProcess.js.map
  80403. var BABYLON;
  80404. (function (BABYLON) {
  80405. /**
  80406. * The SharpenPostProcess applies a sharpen kernel to every pixel
  80407. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  80408. */
  80409. var SharpenPostProcess = /** @class */ (function (_super) {
  80410. __extends(SharpenPostProcess, _super);
  80411. /**
  80412. * Creates a new instance ConvolutionPostProcess
  80413. * @param name The name of the effect.
  80414. * @param options The required width/height ratio to downsize to before computing the render pass.
  80415. * @param camera The camera to apply the render pass to.
  80416. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80417. * @param engine The engine which the post process will be applied. (default: current engine)
  80418. * @param reusable If the post process can be reused on the same frame. (default: false)
  80419. * @param textureType Type of textures used when performing the post process. (default: 0)
  80420. * @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)
  80421. */
  80422. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80423. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80424. if (blockCompilation === void 0) { blockCompilation = false; }
  80425. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80426. /**
  80427. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  80428. */
  80429. _this.colorAmount = 1.0;
  80430. /**
  80431. * How much sharpness should be applied (default: 0.3)
  80432. */
  80433. _this.edgeAmount = 0.3;
  80434. _this.onApply = function (effect) {
  80435. effect.setFloat2("screenSize", _this.width, _this.height);
  80436. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  80437. };
  80438. return _this;
  80439. }
  80440. return SharpenPostProcess;
  80441. }(BABYLON.PostProcess));
  80442. BABYLON.SharpenPostProcess = SharpenPostProcess;
  80443. })(BABYLON || (BABYLON = {}));
  80444. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  80445. var BABYLON;
  80446. (function (BABYLON) {
  80447. /**
  80448. * The Blur Post Process which blurs an image based on a kernel and direction.
  80449. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  80450. */
  80451. var BlurPostProcess = /** @class */ (function (_super) {
  80452. __extends(BlurPostProcess, _super);
  80453. /**
  80454. * Creates a new instance BlurPostProcess
  80455. * @param name The name of the effect.
  80456. * @param direction The direction in which to blur the image.
  80457. * @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.
  80458. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  80459. * @param camera The camera to apply the render pass to.
  80460. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80461. * @param engine The engine which the post process will be applied. (default: current engine)
  80462. * @param reusable If the post process can be reused on the same frame. (default: false)
  80463. * @param textureType Type of textures used when performing the post process. (default: 0)
  80464. * @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)
  80465. */
  80466. function BlurPostProcess(name,
  80467. /** The direction in which to blur the image. */
  80468. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  80469. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80470. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80471. if (defines === void 0) { defines = ""; }
  80472. if (blockCompilation === void 0) { blockCompilation = false; }
  80473. 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;
  80474. _this.direction = direction;
  80475. _this.blockCompilation = blockCompilation;
  80476. _this._packedFloat = false;
  80477. _this._staticDefines = "";
  80478. _this._staticDefines = defines;
  80479. _this.onApplyObservable.add(function (effect) {
  80480. if (_this._outputTexture) {
  80481. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  80482. }
  80483. else {
  80484. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  80485. }
  80486. });
  80487. _this.kernel = kernel;
  80488. return _this;
  80489. }
  80490. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  80491. /**
  80492. * Gets the length in pixels of the blur sample region
  80493. */
  80494. get: function () {
  80495. return this._idealKernel;
  80496. },
  80497. /**
  80498. * Sets the length in pixels of the blur sample region
  80499. */
  80500. set: function (v) {
  80501. if (this._idealKernel === v) {
  80502. return;
  80503. }
  80504. v = Math.max(v, 1);
  80505. this._idealKernel = v;
  80506. this._kernel = this._nearestBestKernel(v);
  80507. if (!this.blockCompilation) {
  80508. this._updateParameters();
  80509. }
  80510. },
  80511. enumerable: true,
  80512. configurable: true
  80513. });
  80514. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  80515. /**
  80516. * Gets wether or not the blur is unpacking/repacking floats
  80517. */
  80518. get: function () {
  80519. return this._packedFloat;
  80520. },
  80521. /**
  80522. * Sets wether or not the blur needs to unpack/repack floats
  80523. */
  80524. set: function (v) {
  80525. if (this._packedFloat === v) {
  80526. return;
  80527. }
  80528. this._packedFloat = v;
  80529. if (!this.blockCompilation) {
  80530. this._updateParameters();
  80531. }
  80532. },
  80533. enumerable: true,
  80534. configurable: true
  80535. });
  80536. /**
  80537. * Updates the effect with the current post process compile time values and recompiles the shader.
  80538. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  80539. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  80540. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  80541. * @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
  80542. * @param onCompiled Called when the shader has been compiled.
  80543. * @param onError Called if there is an error when compiling a shader.
  80544. */
  80545. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  80546. if (defines === void 0) { defines = null; }
  80547. if (uniforms === void 0) { uniforms = null; }
  80548. if (samplers === void 0) { samplers = null; }
  80549. this._updateParameters(onCompiled, onError);
  80550. };
  80551. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  80552. // Generate sampling offsets and weights
  80553. var N = this._kernel;
  80554. var centerIndex = (N - 1) / 2;
  80555. // Generate Gaussian sampling weights over kernel
  80556. var offsets = [];
  80557. var weights = [];
  80558. var totalWeight = 0;
  80559. for (var i = 0; i < N; i++) {
  80560. var u = i / (N - 1);
  80561. var w = this._gaussianWeight(u * 2.0 - 1);
  80562. offsets[i] = (i - centerIndex);
  80563. weights[i] = w;
  80564. totalWeight += w;
  80565. }
  80566. // Normalize weights
  80567. for (var i = 0; i < weights.length; i++) {
  80568. weights[i] /= totalWeight;
  80569. }
  80570. // Optimize: combine samples to take advantage of hardware linear sampling
  80571. // Walk from left to center, combining pairs (symmetrically)
  80572. var linearSamplingWeights = [];
  80573. var linearSamplingOffsets = [];
  80574. var linearSamplingMap = [];
  80575. for (var i = 0; i <= centerIndex; i += 2) {
  80576. var j = Math.min(i + 1, Math.floor(centerIndex));
  80577. var singleCenterSample = i === j;
  80578. if (singleCenterSample) {
  80579. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  80580. }
  80581. else {
  80582. var sharedCell = j === centerIndex;
  80583. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  80584. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  80585. if (offsetLinear === 0) {
  80586. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  80587. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  80588. }
  80589. else {
  80590. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  80591. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  80592. }
  80593. }
  80594. }
  80595. for (var i = 0; i < linearSamplingMap.length; i++) {
  80596. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  80597. linearSamplingWeights[i] = linearSamplingMap[i].w;
  80598. }
  80599. // Replace with optimized
  80600. offsets = linearSamplingOffsets;
  80601. weights = linearSamplingWeights;
  80602. // Generate shaders
  80603. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  80604. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  80605. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  80606. var defines = "";
  80607. defines += this._staticDefines;
  80608. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  80609. if (this._staticDefines.indexOf("DOF") != -1) {
  80610. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  80611. varyingCount--;
  80612. }
  80613. for (var i = 0; i < varyingCount; i++) {
  80614. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  80615. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  80616. }
  80617. var depCount = 0;
  80618. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  80619. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  80620. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  80621. depCount++;
  80622. }
  80623. if (this.packedFloat) {
  80624. defines += "#define PACKEDFLOAT 1";
  80625. }
  80626. this.blockCompilation = false;
  80627. _super.prototype.updateEffect.call(this, defines, null, null, {
  80628. varyingCount: varyingCount,
  80629. depCount: depCount
  80630. }, onCompiled, onError);
  80631. };
  80632. /**
  80633. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  80634. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  80635. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  80636. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  80637. * The gaps between physical kernels are compensated for in the weighting of the samples
  80638. * @param idealKernel Ideal blur kernel.
  80639. * @return Nearest best kernel.
  80640. */
  80641. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  80642. var v = Math.round(idealKernel);
  80643. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  80644. var k = _a[_i];
  80645. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  80646. return Math.max(k, 3);
  80647. }
  80648. }
  80649. return Math.max(v, 3);
  80650. };
  80651. /**
  80652. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  80653. * @param x The point on the Gaussian distribution to sample.
  80654. * @return the value of the Gaussian function at x.
  80655. */
  80656. BlurPostProcess.prototype._gaussianWeight = function (x) {
  80657. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  80658. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  80659. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  80660. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  80661. // truncated at around 1.3% of peak strength.
  80662. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  80663. var sigma = (1 / 3);
  80664. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  80665. var exponent = -((x * x) / (2.0 * sigma * sigma));
  80666. var weight = (1.0 / denominator) * Math.exp(exponent);
  80667. return weight;
  80668. };
  80669. /**
  80670. * Generates a string that can be used as a floating point number in GLSL.
  80671. * @param x Value to print.
  80672. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  80673. * @return GLSL float string.
  80674. */
  80675. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  80676. if (decimalFigures === void 0) { decimalFigures = 8; }
  80677. return x.toFixed(decimalFigures).replace(/0+$/, '');
  80678. };
  80679. return BlurPostProcess;
  80680. }(BABYLON.PostProcess));
  80681. BABYLON.BlurPostProcess = BlurPostProcess;
  80682. })(BABYLON || (BABYLON = {}));
  80683. //# sourceMappingURL=babylon.blurPostProcess.js.map
  80684. var BABYLON;
  80685. (function (BABYLON) {
  80686. /**
  80687. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  80688. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  80689. * based on samples that have a large difference in distance than the center pixel.
  80690. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  80691. */
  80692. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  80693. __extends(DepthOfFieldBlurPostProcess, _super);
  80694. /**
  80695. * Creates a new instance CircleOfConfusionPostProcess
  80696. * @param name The name of the effect.
  80697. * @param scene The scene the effect belongs to.
  80698. * @param direction The direction the blur should be applied.
  80699. * @param kernel The size of the kernel used to blur.
  80700. * @param options The required width/height ratio to downsize to before computing the render pass.
  80701. * @param camera The camera to apply the render pass to.
  80702. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  80703. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  80704. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80705. * @param engine The engine which the post process will be applied. (default: current engine)
  80706. * @param reusable If the post process can be reused on the same frame. (default: false)
  80707. * @param textureType Type of textures used when performing the post process. (default: 0)
  80708. * @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)
  80709. */
  80710. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  80711. if (imageToBlur === void 0) { imageToBlur = null; }
  80712. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80713. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80714. if (blockCompilation === void 0) { blockCompilation = false; }
  80715. 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;
  80716. _this.direction = direction;
  80717. _this.onApplyObservable.add(function (effect) {
  80718. if (imageToBlur != null) {
  80719. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  80720. }
  80721. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  80722. if (scene.activeCamera) {
  80723. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  80724. }
  80725. });
  80726. return _this;
  80727. }
  80728. return DepthOfFieldBlurPostProcess;
  80729. }(BABYLON.BlurPostProcess));
  80730. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  80731. })(BABYLON || (BABYLON = {}));
  80732. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  80733. var BABYLON;
  80734. (function (BABYLON) {
  80735. /**
  80736. * Options to be set when merging outputs from the default pipeline.
  80737. */
  80738. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  80739. function DepthOfFieldMergePostProcessOptions() {
  80740. }
  80741. return DepthOfFieldMergePostProcessOptions;
  80742. }());
  80743. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  80744. /**
  80745. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  80746. */
  80747. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  80748. __extends(DepthOfFieldMergePostProcess, _super);
  80749. /**
  80750. * Creates a new instance of DepthOfFieldMergePostProcess
  80751. * @param name The name of the effect.
  80752. * @param originalFromInput Post process which's input will be used for the merge.
  80753. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  80754. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  80755. * @param options The required width/height ratio to downsize to before computing the render pass.
  80756. * @param camera The camera to apply the render pass to.
  80757. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80758. * @param engine The engine which the post process will be applied. (default: current engine)
  80759. * @param reusable If the post process can be reused on the same frame. (default: false)
  80760. * @param textureType Type of textures used when performing the post process. (default: 0)
  80761. * @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)
  80762. */
  80763. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80764. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80765. if (blockCompilation === void 0) { blockCompilation = false; }
  80766. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  80767. _this.blurSteps = blurSteps;
  80768. _this.onApplyObservable.add(function (effect) {
  80769. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  80770. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  80771. blurSteps.forEach(function (step, index) {
  80772. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  80773. });
  80774. });
  80775. if (!blockCompilation) {
  80776. _this.updateEffect();
  80777. }
  80778. return _this;
  80779. }
  80780. /**
  80781. * Updates the effect with the current post process compile time values and recompiles the shader.
  80782. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  80783. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  80784. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  80785. * @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
  80786. * @param onCompiled Called when the shader has been compiled.
  80787. * @param onError Called if there is an error when compiling a shader.
  80788. */
  80789. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  80790. if (defines === void 0) { defines = null; }
  80791. if (uniforms === void 0) { uniforms = null; }
  80792. if (samplers === void 0) { samplers = null; }
  80793. if (!defines) {
  80794. defines = "";
  80795. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  80796. }
  80797. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  80798. };
  80799. return DepthOfFieldMergePostProcess;
  80800. }(BABYLON.PostProcess));
  80801. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  80802. })(BABYLON || (BABYLON = {}));
  80803. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  80804. var BABYLON;
  80805. (function (BABYLON) {
  80806. /**
  80807. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  80808. */
  80809. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  80810. __extends(CircleOfConfusionPostProcess, _super);
  80811. /**
  80812. * Creates a new instance CircleOfConfusionPostProcess
  80813. * @param name The name of the effect.
  80814. * @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.
  80815. * @param options The required width/height ratio to downsize to before computing the render pass.
  80816. * @param camera The camera to apply the render pass to.
  80817. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80818. * @param engine The engine which the post process will be applied. (default: current engine)
  80819. * @param reusable If the post process can be reused on the same frame. (default: false)
  80820. * @param textureType Type of textures used when performing the post process. (default: 0)
  80821. * @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)
  80822. */
  80823. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80824. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80825. if (blockCompilation === void 0) { blockCompilation = false; }
  80826. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80827. /**
  80828. * 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.
  80829. */
  80830. _this.lensSize = 50;
  80831. /**
  80832. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  80833. */
  80834. _this.fStop = 1.4;
  80835. /**
  80836. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  80837. */
  80838. _this.focusDistance = 2000;
  80839. /**
  80840. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  80841. */
  80842. _this.focalLength = 50;
  80843. _this._depthTexture = null;
  80844. _this._depthTexture = depthTexture;
  80845. _this.onApplyObservable.add(function (effect) {
  80846. if (!_this._depthTexture) {
  80847. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  80848. return;
  80849. }
  80850. effect.setTexture("depthSampler", _this._depthTexture);
  80851. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  80852. var aperture = _this.lensSize / _this.fStop;
  80853. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  80854. effect.setFloat('focusDistance', _this.focusDistance);
  80855. effect.setFloat('cocPrecalculation', cocPrecalculation);
  80856. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  80857. });
  80858. return _this;
  80859. }
  80860. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  80861. /**
  80862. * 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.
  80863. */
  80864. set: function (value) {
  80865. this._depthTexture = value;
  80866. },
  80867. enumerable: true,
  80868. configurable: true
  80869. });
  80870. return CircleOfConfusionPostProcess;
  80871. }(BABYLON.PostProcess));
  80872. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  80873. })(BABYLON || (BABYLON = {}));
  80874. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  80875. var BABYLON;
  80876. (function (BABYLON) {
  80877. /**
  80878. * Specifies the level of max blur that should be applied when using the depth of field effect
  80879. */
  80880. var DepthOfFieldEffectBlurLevel;
  80881. (function (DepthOfFieldEffectBlurLevel) {
  80882. /**
  80883. * Subtle blur
  80884. */
  80885. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  80886. /**
  80887. * Medium blur
  80888. */
  80889. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  80890. /**
  80891. * Large blur
  80892. */
  80893. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  80894. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  80895. ;
  80896. /**
  80897. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  80898. */
  80899. var DepthOfFieldEffect = /** @class */ (function (_super) {
  80900. __extends(DepthOfFieldEffect, _super);
  80901. /**
  80902. * Creates a new instance DepthOfFieldEffect
  80903. * @param scene The scene the effect belongs to.
  80904. * @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.
  80905. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  80906. * @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)
  80907. */
  80908. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  80909. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  80910. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  80911. if (blockCompilation === void 0) { blockCompilation = false; }
  80912. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  80913. return _this._effects;
  80914. }, true) || this;
  80915. /**
  80916. * @hidden Internal post processes in depth of field effect
  80917. */
  80918. _this._effects = [];
  80919. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  80920. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80921. // 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)
  80922. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  80923. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  80924. _this._depthOfFieldBlurY = [];
  80925. _this._depthOfFieldBlurX = [];
  80926. var blurCount = 1;
  80927. var kernelSize = 15;
  80928. switch (blurLevel) {
  80929. case DepthOfFieldEffectBlurLevel.High: {
  80930. blurCount = 3;
  80931. kernelSize = 51;
  80932. break;
  80933. }
  80934. case DepthOfFieldEffectBlurLevel.Medium: {
  80935. blurCount = 2;
  80936. kernelSize = 31;
  80937. break;
  80938. }
  80939. default: {
  80940. kernelSize = 15;
  80941. blurCount = 1;
  80942. break;
  80943. }
  80944. }
  80945. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  80946. var ratio = 1.0;
  80947. for (var i = 0; i < blurCount; i++) {
  80948. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80949. blurY.autoClear = false;
  80950. ratio = 0.75 / Math.pow(2, i);
  80951. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80952. blurX.autoClear = false;
  80953. _this._depthOfFieldBlurY.push(blurY);
  80954. _this._depthOfFieldBlurX.push(blurX);
  80955. }
  80956. // Set all post processes on the effect.
  80957. _this._effects = [_this._circleOfConfusion];
  80958. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  80959. _this._effects.push(_this._depthOfFieldBlurY[i]);
  80960. _this._effects.push(_this._depthOfFieldBlurX[i]);
  80961. }
  80962. // Merge blurred images with original image based on circleOfConfusion
  80963. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80964. _this._dofMerge.autoClear = false;
  80965. _this._effects.push(_this._dofMerge);
  80966. return _this;
  80967. }
  80968. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  80969. get: function () {
  80970. return this._circleOfConfusion.focalLength;
  80971. },
  80972. /**
  80973. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  80974. */
  80975. set: function (value) {
  80976. this._circleOfConfusion.focalLength = value;
  80977. },
  80978. enumerable: true,
  80979. configurable: true
  80980. });
  80981. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  80982. get: function () {
  80983. return this._circleOfConfusion.fStop;
  80984. },
  80985. /**
  80986. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  80987. */
  80988. set: function (value) {
  80989. this._circleOfConfusion.fStop = value;
  80990. },
  80991. enumerable: true,
  80992. configurable: true
  80993. });
  80994. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  80995. get: function () {
  80996. return this._circleOfConfusion.focusDistance;
  80997. },
  80998. /**
  80999. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  81000. */
  81001. set: function (value) {
  81002. this._circleOfConfusion.focusDistance = value;
  81003. },
  81004. enumerable: true,
  81005. configurable: true
  81006. });
  81007. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  81008. get: function () {
  81009. return this._circleOfConfusion.lensSize;
  81010. },
  81011. /**
  81012. * 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.
  81013. */
  81014. set: function (value) {
  81015. this._circleOfConfusion.lensSize = value;
  81016. },
  81017. enumerable: true,
  81018. configurable: true
  81019. });
  81020. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  81021. /**
  81022. * 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.
  81023. */
  81024. set: function (value) {
  81025. this._circleOfConfusion.depthTexture = value;
  81026. },
  81027. enumerable: true,
  81028. configurable: true
  81029. });
  81030. /**
  81031. * Disposes each of the internal effects for a given camera.
  81032. * @param camera The camera to dispose the effect on.
  81033. */
  81034. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  81035. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81036. this._effects[effectIndex].dispose(camera);
  81037. }
  81038. };
  81039. /**
  81040. * @hidden Internal
  81041. */
  81042. DepthOfFieldEffect.prototype._updateEffects = function () {
  81043. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81044. this._effects[effectIndex].updateEffect();
  81045. }
  81046. };
  81047. /**
  81048. * Internal
  81049. * @returns if all the contained post processes are ready.
  81050. * @hidden
  81051. */
  81052. DepthOfFieldEffect.prototype._isReady = function () {
  81053. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81054. if (!this._effects[effectIndex].isReady()) {
  81055. return false;
  81056. }
  81057. }
  81058. return true;
  81059. };
  81060. return DepthOfFieldEffect;
  81061. }(BABYLON.PostProcessRenderEffect));
  81062. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  81063. })(BABYLON || (BABYLON = {}));
  81064. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  81065. var BABYLON;
  81066. (function (BABYLON) {
  81067. /**
  81068. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  81069. */
  81070. var BloomMergePostProcess = /** @class */ (function (_super) {
  81071. __extends(BloomMergePostProcess, _super);
  81072. /**
  81073. * Creates a new instance of @see BloomMergePostProcess
  81074. * @param name The name of the effect.
  81075. * @param originalFromInput Post process which's input will be used for the merge.
  81076. * @param blurred Blurred highlights post process which's output will be used.
  81077. * @param weight Weight of the bloom to be added to the original input.
  81078. * @param options The required width/height ratio to downsize to before computing the render pass.
  81079. * @param camera The camera to apply the render pass to.
  81080. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81081. * @param engine The engine which the post process will be applied. (default: current engine)
  81082. * @param reusable If the post process can be reused on the same frame. (default: false)
  81083. * @param textureType Type of textures used when performing the post process. (default: 0)
  81084. * @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)
  81085. */
  81086. function BloomMergePostProcess(name, originalFromInput, blurred,
  81087. /** Weight of the bloom to be added to the original input. */
  81088. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  81089. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81090. if (blockCompilation === void 0) { blockCompilation = false; }
  81091. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  81092. _this.weight = weight;
  81093. _this.onApplyObservable.add(function (effect) {
  81094. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  81095. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  81096. effect.setFloat("bloomWeight", _this.weight);
  81097. });
  81098. if (!blockCompilation) {
  81099. _this.updateEffect();
  81100. }
  81101. return _this;
  81102. }
  81103. return BloomMergePostProcess;
  81104. }(BABYLON.PostProcess));
  81105. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  81106. })(BABYLON || (BABYLON = {}));
  81107. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  81108. var BABYLON;
  81109. (function (BABYLON) {
  81110. /**
  81111. * 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.
  81112. */
  81113. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  81114. __extends(ExtractHighlightsPostProcess, _super);
  81115. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  81116. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81117. if (blockCompilation === void 0) { blockCompilation = false; }
  81118. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  81119. /**
  81120. * The luminance threshold, pixels below this value will be set to black.
  81121. */
  81122. _this.threshold = 0.9;
  81123. /** @hidden */
  81124. _this._exposure = 1;
  81125. /**
  81126. * Post process which has the input texture to be used when performing highlight extraction
  81127. * @hidden
  81128. */
  81129. _this._inputPostProcess = null;
  81130. _this.onApplyObservable.add(function (effect) {
  81131. if (_this._inputPostProcess) {
  81132. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  81133. }
  81134. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  81135. effect.setFloat('exposure', _this._exposure);
  81136. });
  81137. return _this;
  81138. }
  81139. return ExtractHighlightsPostProcess;
  81140. }(BABYLON.PostProcess));
  81141. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  81142. })(BABYLON || (BABYLON = {}));
  81143. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  81144. var BABYLON;
  81145. (function (BABYLON) {
  81146. /**
  81147. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  81148. */
  81149. var BloomEffect = /** @class */ (function (_super) {
  81150. __extends(BloomEffect, _super);
  81151. /**
  81152. * Creates a new instance of @see BloomEffect
  81153. * @param scene The scene the effect belongs to.
  81154. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  81155. * @param bloomKernel The size of the kernel to be used when applying the blur.
  81156. * @param bloomWeight The the strength of bloom.
  81157. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  81158. * @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)
  81159. */
  81160. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  81161. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  81162. if (blockCompilation === void 0) { blockCompilation = false; }
  81163. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  81164. return _this._effects;
  81165. }, true) || this;
  81166. _this.bloomScale = bloomScale;
  81167. /**
  81168. * @hidden Internal
  81169. */
  81170. _this._effects = [];
  81171. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  81172. _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);
  81173. _this._blurX.alwaysForcePOT = true;
  81174. _this._blurX.autoClear = false;
  81175. _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);
  81176. _this._blurY.alwaysForcePOT = true;
  81177. _this._blurY.autoClear = false;
  81178. _this.kernel = bloomKernel;
  81179. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  81180. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  81181. _this._merge.autoClear = false;
  81182. _this._effects.push(_this._merge);
  81183. return _this;
  81184. }
  81185. Object.defineProperty(BloomEffect.prototype, "threshold", {
  81186. /**
  81187. * The luminance threshold to find bright areas of the image to bloom.
  81188. */
  81189. get: function () {
  81190. return this._downscale.threshold;
  81191. },
  81192. set: function (value) {
  81193. this._downscale.threshold = value;
  81194. },
  81195. enumerable: true,
  81196. configurable: true
  81197. });
  81198. Object.defineProperty(BloomEffect.prototype, "weight", {
  81199. /**
  81200. * The strength of the bloom.
  81201. */
  81202. get: function () {
  81203. return this._merge.weight;
  81204. },
  81205. set: function (value) {
  81206. this._merge.weight = value;
  81207. },
  81208. enumerable: true,
  81209. configurable: true
  81210. });
  81211. Object.defineProperty(BloomEffect.prototype, "kernel", {
  81212. /**
  81213. * Specifies the size of the bloom blur kernel, relative to the final output size
  81214. */
  81215. get: function () {
  81216. return this._blurX.kernel / this.bloomScale;
  81217. },
  81218. set: function (value) {
  81219. this._blurX.kernel = value * this.bloomScale;
  81220. this._blurY.kernel = value * this.bloomScale;
  81221. },
  81222. enumerable: true,
  81223. configurable: true
  81224. });
  81225. /**
  81226. * Disposes each of the internal effects for a given camera.
  81227. * @param camera The camera to dispose the effect on.
  81228. */
  81229. BloomEffect.prototype.disposeEffects = function (camera) {
  81230. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81231. this._effects[effectIndex].dispose(camera);
  81232. }
  81233. };
  81234. /**
  81235. * @hidden Internal
  81236. */
  81237. BloomEffect.prototype._updateEffects = function () {
  81238. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81239. this._effects[effectIndex].updateEffect();
  81240. }
  81241. };
  81242. /**
  81243. * Internal
  81244. * @returns if all the contained post processes are ready.
  81245. * @hidden
  81246. */
  81247. BloomEffect.prototype._isReady = function () {
  81248. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81249. if (!this._effects[effectIndex].isReady()) {
  81250. return false;
  81251. }
  81252. }
  81253. return true;
  81254. };
  81255. return BloomEffect;
  81256. }(BABYLON.PostProcessRenderEffect));
  81257. BABYLON.BloomEffect = BloomEffect;
  81258. })(BABYLON || (BABYLON = {}));
  81259. //# sourceMappingURL=babylon.bloomEffect.js.map
  81260. var BABYLON;
  81261. (function (BABYLON) {
  81262. /**
  81263. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  81264. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  81265. */
  81266. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  81267. __extends(DefaultRenderingPipeline, _super);
  81268. /**
  81269. * @constructor
  81270. * @param {string} name - The rendering pipeline name (default: "")
  81271. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  81272. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  81273. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  81274. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  81275. */
  81276. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  81277. if (name === void 0) { name = ""; }
  81278. if (hdr === void 0) { hdr = true; }
  81279. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  81280. if (automaticBuild === void 0) { automaticBuild = true; }
  81281. var _this = _super.call(this, scene.getEngine(), name) || this;
  81282. _this._camerasToBeAttached = [];
  81283. /**
  81284. * ID of the sharpen post process,
  81285. */
  81286. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  81287. /**
  81288. * ID of the image processing post process;
  81289. */
  81290. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  81291. /**
  81292. * ID of the Fast Approximate Anti-Aliasing post process;
  81293. */
  81294. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  81295. /**
  81296. * ID of the chromatic aberration post process,
  81297. */
  81298. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  81299. /**
  81300. * ID of the grain post process
  81301. */
  81302. _this.GrainPostProcessId = "GrainPostProcessEffect";
  81303. /**
  81304. * Glow post process which adds a glow to emmisive areas of the image
  81305. */
  81306. _this._glowLayer = null;
  81307. /**
  81308. * Animations which can be used to tweak settings over a period of time
  81309. */
  81310. _this.animations = [];
  81311. _this._imageProcessingConfigurationObserver = null;
  81312. // Values
  81313. _this._sharpenEnabled = false;
  81314. _this._bloomEnabled = false;
  81315. _this._depthOfFieldEnabled = false;
  81316. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  81317. _this._fxaaEnabled = false;
  81318. _this._imageProcessingEnabled = true;
  81319. _this._bloomScale = 0.5;
  81320. _this._chromaticAberrationEnabled = false;
  81321. _this._grainEnabled = false;
  81322. _this._buildAllowed = true;
  81323. _this._resizeObserver = null;
  81324. _this._hardwareScaleLevel = 1.0;
  81325. _this._bloomKernel = 64;
  81326. /**
  81327. * Specifies the weight of the bloom in the final rendering
  81328. */
  81329. _this._bloomWeight = 0.15;
  81330. /**
  81331. * Specifies the luma threshold for the area that will be blurred by the bloom
  81332. */
  81333. _this._bloomThreshold = 0.9;
  81334. _this._samples = 1;
  81335. _this._hasCleared = false;
  81336. _this._prevPostProcess = null;
  81337. _this._prevPrevPostProcess = null;
  81338. _this._depthOfFieldSceneObserver = null;
  81339. _this._cameras = cameras || scene.cameras;
  81340. _this._cameras = _this._cameras.slice();
  81341. _this._camerasToBeAttached = _this._cameras.slice();
  81342. _this._buildAllowed = automaticBuild;
  81343. // Initialize
  81344. _this._scene = scene;
  81345. var caps = _this._scene.getEngine().getCaps();
  81346. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  81347. // Misc
  81348. if (_this._hdr) {
  81349. if (caps.textureHalfFloatRender) {
  81350. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81351. }
  81352. else if (caps.textureFloatRender) {
  81353. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81354. }
  81355. }
  81356. else {
  81357. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81358. }
  81359. // Attach
  81360. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81361. var engine = _this._scene.getEngine();
  81362. // Create post processes before hand so they can be modified before enabled.
  81363. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  81364. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81365. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  81366. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  81367. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  81368. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81369. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  81370. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81371. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  81372. _this._resizeObserver = engine.onResizeObservable.add(function () {
  81373. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  81374. _this.bloomKernel = _this.bloomKernel;
  81375. });
  81376. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  81377. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  81378. });
  81379. _this._buildPipeline();
  81380. return _this;
  81381. }
  81382. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  81383. get: function () {
  81384. return this._sharpenEnabled;
  81385. },
  81386. /**
  81387. * Enable or disable the sharpen process from the pipeline
  81388. */
  81389. set: function (enabled) {
  81390. if (this._sharpenEnabled === enabled) {
  81391. return;
  81392. }
  81393. this._sharpenEnabled = enabled;
  81394. this._buildPipeline();
  81395. },
  81396. enumerable: true,
  81397. configurable: true
  81398. });
  81399. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  81400. /**
  81401. * Specifies the size of the bloom blur kernel, relative to the final output size
  81402. */
  81403. get: function () {
  81404. return this._bloomKernel;
  81405. },
  81406. set: function (value) {
  81407. this._bloomKernel = value;
  81408. this.bloom.kernel = value / this._hardwareScaleLevel;
  81409. },
  81410. enumerable: true,
  81411. configurable: true
  81412. });
  81413. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  81414. get: function () {
  81415. return this._bloomWeight;
  81416. },
  81417. /**
  81418. * The strength of the bloom.
  81419. */
  81420. set: function (value) {
  81421. if (this._bloomWeight === value) {
  81422. return;
  81423. }
  81424. this.bloom.weight = value;
  81425. this._bloomWeight = value;
  81426. },
  81427. enumerable: true,
  81428. configurable: true
  81429. });
  81430. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  81431. get: function () {
  81432. return this._bloomThreshold;
  81433. },
  81434. /**
  81435. * The strength of the bloom.
  81436. */
  81437. set: function (value) {
  81438. if (this._bloomThreshold === value) {
  81439. return;
  81440. }
  81441. this.bloom.threshold = value;
  81442. this._bloomThreshold = value;
  81443. },
  81444. enumerable: true,
  81445. configurable: true
  81446. });
  81447. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  81448. get: function () {
  81449. return this._bloomScale;
  81450. },
  81451. /**
  81452. * The scale of the bloom, lower value will provide better performance.
  81453. */
  81454. set: function (value) {
  81455. if (this._bloomScale === value) {
  81456. return;
  81457. }
  81458. this._bloomScale = value;
  81459. // recreate bloom and dispose old as this setting is not dynamic
  81460. this._rebuildBloom();
  81461. this._buildPipeline();
  81462. },
  81463. enumerable: true,
  81464. configurable: true
  81465. });
  81466. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  81467. get: function () {
  81468. return this._bloomEnabled;
  81469. },
  81470. /**
  81471. * Enable or disable the bloom from the pipeline
  81472. */
  81473. set: function (enabled) {
  81474. if (this._bloomEnabled === enabled) {
  81475. return;
  81476. }
  81477. this._bloomEnabled = enabled;
  81478. this._buildPipeline();
  81479. },
  81480. enumerable: true,
  81481. configurable: true
  81482. });
  81483. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  81484. // recreate bloom and dispose old as this setting is not dynamic
  81485. var oldBloom = this.bloom;
  81486. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  81487. this.bloom.threshold = oldBloom.threshold;
  81488. for (var i = 0; i < this._cameras.length; i++) {
  81489. oldBloom.disposeEffects(this._cameras[i]);
  81490. }
  81491. };
  81492. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  81493. /**
  81494. * If the depth of field is enabled.
  81495. */
  81496. get: function () {
  81497. return this._depthOfFieldEnabled;
  81498. },
  81499. set: function (enabled) {
  81500. if (this._depthOfFieldEnabled === enabled) {
  81501. return;
  81502. }
  81503. this._depthOfFieldEnabled = enabled;
  81504. this._buildPipeline();
  81505. },
  81506. enumerable: true,
  81507. configurable: true
  81508. });
  81509. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  81510. /**
  81511. * Blur level of the depth of field effect. (Higher blur will effect performance)
  81512. */
  81513. get: function () {
  81514. return this._depthOfFieldBlurLevel;
  81515. },
  81516. set: function (value) {
  81517. if (this._depthOfFieldBlurLevel === value) {
  81518. return;
  81519. }
  81520. this._depthOfFieldBlurLevel = value;
  81521. // recreate dof and dispose old as this setting is not dynamic
  81522. var oldDof = this.depthOfField;
  81523. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  81524. this.depthOfField.focalLength = oldDof.focalLength;
  81525. this.depthOfField.focusDistance = oldDof.focusDistance;
  81526. this.depthOfField.fStop = oldDof.fStop;
  81527. this.depthOfField.lensSize = oldDof.lensSize;
  81528. for (var i = 0; i < this._cameras.length; i++) {
  81529. oldDof.disposeEffects(this._cameras[i]);
  81530. }
  81531. this._buildPipeline();
  81532. },
  81533. enumerable: true,
  81534. configurable: true
  81535. });
  81536. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  81537. get: function () {
  81538. return this._fxaaEnabled;
  81539. },
  81540. /**
  81541. * If the anti aliasing is enabled.
  81542. */
  81543. set: function (enabled) {
  81544. if (this._fxaaEnabled === enabled) {
  81545. return;
  81546. }
  81547. this._fxaaEnabled = enabled;
  81548. this._buildPipeline();
  81549. },
  81550. enumerable: true,
  81551. configurable: true
  81552. });
  81553. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  81554. get: function () {
  81555. return this._samples;
  81556. },
  81557. /**
  81558. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  81559. */
  81560. set: function (sampleCount) {
  81561. if (this._samples === sampleCount) {
  81562. return;
  81563. }
  81564. this._samples = sampleCount;
  81565. this._buildPipeline();
  81566. },
  81567. enumerable: true,
  81568. configurable: true
  81569. });
  81570. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  81571. get: function () {
  81572. return this._imageProcessingEnabled;
  81573. },
  81574. /**
  81575. * If image processing is enabled.
  81576. */
  81577. set: function (enabled) {
  81578. if (this._imageProcessingEnabled === enabled) {
  81579. return;
  81580. }
  81581. this._imageProcessingEnabled = enabled;
  81582. this._buildPipeline();
  81583. },
  81584. enumerable: true,
  81585. configurable: true
  81586. });
  81587. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  81588. get: function () {
  81589. return this._glowLayer == null;
  81590. },
  81591. /**
  81592. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  81593. */
  81594. set: function (enabled) {
  81595. if (enabled && !this._glowLayer) {
  81596. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  81597. }
  81598. else if (!enabled && this._glowLayer) {
  81599. this._glowLayer.dispose();
  81600. this._glowLayer = null;
  81601. }
  81602. },
  81603. enumerable: true,
  81604. configurable: true
  81605. });
  81606. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  81607. get: function () {
  81608. return this._chromaticAberrationEnabled;
  81609. },
  81610. /**
  81611. * Enable or disable the chromaticAberration process from the pipeline
  81612. */
  81613. set: function (enabled) {
  81614. if (this._chromaticAberrationEnabled === enabled) {
  81615. return;
  81616. }
  81617. this._chromaticAberrationEnabled = enabled;
  81618. this._buildPipeline();
  81619. },
  81620. enumerable: true,
  81621. configurable: true
  81622. });
  81623. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  81624. get: function () {
  81625. return this._grainEnabled;
  81626. },
  81627. /**
  81628. * Enable or disable the grain process from the pipeline
  81629. */
  81630. set: function (enabled) {
  81631. if (this._grainEnabled === enabled) {
  81632. return;
  81633. }
  81634. this._grainEnabled = enabled;
  81635. this._buildPipeline();
  81636. },
  81637. enumerable: true,
  81638. configurable: true
  81639. });
  81640. /**
  81641. * Force the compilation of the entire pipeline.
  81642. */
  81643. DefaultRenderingPipeline.prototype.prepare = function () {
  81644. var previousState = this._buildAllowed;
  81645. this._buildAllowed = true;
  81646. this._buildPipeline();
  81647. this._buildAllowed = previousState;
  81648. };
  81649. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  81650. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  81651. if (this._hasCleared) {
  81652. postProcess.autoClear = false;
  81653. }
  81654. else {
  81655. postProcess.autoClear = true;
  81656. this._scene.autoClear = false;
  81657. this._hasCleared = true;
  81658. }
  81659. if (!skipTextureSharing) {
  81660. if (this._prevPrevPostProcess) {
  81661. postProcess.shareOutputWith(this._prevPrevPostProcess);
  81662. }
  81663. else {
  81664. postProcess.useOwnOutput();
  81665. }
  81666. if (this._prevPostProcess) {
  81667. this._prevPrevPostProcess = this._prevPostProcess;
  81668. }
  81669. this._prevPostProcess = postProcess;
  81670. }
  81671. };
  81672. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  81673. var _this = this;
  81674. if (!this._buildAllowed) {
  81675. return;
  81676. }
  81677. this._scene.autoClear = true;
  81678. var engine = this._scene.getEngine();
  81679. this._disposePostProcesses();
  81680. if (this._cameras !== null) {
  81681. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81682. // get back cameras to be used to reattach pipeline
  81683. this._cameras = this._camerasToBeAttached.slice();
  81684. }
  81685. this._reset();
  81686. this._prevPostProcess = null;
  81687. this._prevPrevPostProcess = null;
  81688. this._hasCleared = false;
  81689. if (this.depthOfFieldEnabled) {
  81690. // Multi camera suport
  81691. if (this._cameras.length > 1) {
  81692. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  81693. var camera = _a[_i];
  81694. var depthRenderer = this._scene.enableDepthRenderer(camera);
  81695. depthRenderer.useOnlyInActiveCamera = true;
  81696. }
  81697. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  81698. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  81699. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  81700. }
  81701. });
  81702. }
  81703. else {
  81704. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81705. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  81706. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  81707. }
  81708. if (!this.depthOfField._isReady()) {
  81709. this.depthOfField._updateEffects();
  81710. }
  81711. this.addEffect(this.depthOfField);
  81712. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  81713. }
  81714. else {
  81715. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81716. }
  81717. if (this.bloomEnabled) {
  81718. if (!this.bloom._isReady()) {
  81719. this.bloom._updateEffects();
  81720. }
  81721. this.addEffect(this.bloom);
  81722. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  81723. }
  81724. if (this._imageProcessingEnabled) {
  81725. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  81726. if (this._hdr) {
  81727. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  81728. this._setAutoClearAndTextureSharing(this.imageProcessing);
  81729. }
  81730. else {
  81731. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  81732. }
  81733. }
  81734. if (this.sharpenEnabled) {
  81735. if (!this.sharpen.isReady()) {
  81736. this.sharpen.updateEffect();
  81737. }
  81738. this.addEffect(this._sharpenEffect);
  81739. this._setAutoClearAndTextureSharing(this.sharpen);
  81740. }
  81741. if (this.grainEnabled) {
  81742. if (!this.grain.isReady()) {
  81743. this.grain.updateEffect();
  81744. }
  81745. this.addEffect(this._grainEffect);
  81746. this._setAutoClearAndTextureSharing(this.grain);
  81747. }
  81748. if (this.chromaticAberrationEnabled) {
  81749. if (!this.chromaticAberration.isReady()) {
  81750. this.chromaticAberration.updateEffect();
  81751. }
  81752. this.addEffect(this._chromaticAberrationEffect);
  81753. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  81754. }
  81755. if (this.fxaaEnabled) {
  81756. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  81757. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  81758. this._setAutoClearAndTextureSharing(this.fxaa, true);
  81759. }
  81760. if (this._cameras !== null) {
  81761. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  81762. }
  81763. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  81764. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  81765. }
  81766. };
  81767. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  81768. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  81769. for (var i = 0; i < this._cameras.length; i++) {
  81770. var camera = this._cameras[i];
  81771. if (this.imageProcessing) {
  81772. this.imageProcessing.dispose(camera);
  81773. }
  81774. if (this.fxaa) {
  81775. this.fxaa.dispose(camera);
  81776. }
  81777. // These are created in the constructor and should not be disposed on every pipeline change
  81778. if (disposeNonRecreated) {
  81779. if (this.sharpen) {
  81780. this.sharpen.dispose(camera);
  81781. }
  81782. if (this.depthOfField) {
  81783. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81784. this.depthOfField.disposeEffects(camera);
  81785. }
  81786. if (this.bloom) {
  81787. this.bloom.disposeEffects(camera);
  81788. }
  81789. if (this.chromaticAberration) {
  81790. this.chromaticAberration.dispose(camera);
  81791. }
  81792. if (this.grain) {
  81793. this.grain.dispose(camera);
  81794. }
  81795. if (this._glowLayer) {
  81796. this._glowLayer.dispose();
  81797. }
  81798. }
  81799. }
  81800. this.imageProcessing = null;
  81801. this.fxaa = null;
  81802. if (disposeNonRecreated) {
  81803. this.sharpen = null;
  81804. this._sharpenEffect = null;
  81805. this.depthOfField = null;
  81806. this.bloom = null;
  81807. this.chromaticAberration = null;
  81808. this._chromaticAberrationEffect = null;
  81809. this.grain = null;
  81810. this._grainEffect = null;
  81811. this._glowLayer = null;
  81812. }
  81813. };
  81814. /**
  81815. * Adds a camera to the pipeline
  81816. * @param camera the camera to be added
  81817. */
  81818. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  81819. this._camerasToBeAttached.push(camera);
  81820. this._buildPipeline();
  81821. };
  81822. /**
  81823. * Removes a camera from the pipeline
  81824. * @param camera the camera to remove
  81825. */
  81826. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  81827. var index = this._camerasToBeAttached.indexOf(camera);
  81828. this._camerasToBeAttached.splice(index, 1);
  81829. this._buildPipeline();
  81830. };
  81831. /**
  81832. * Dispose of the pipeline and stop all post processes
  81833. */
  81834. DefaultRenderingPipeline.prototype.dispose = function () {
  81835. this._disposePostProcesses(true);
  81836. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81837. this._scene.autoClear = true;
  81838. if (this._resizeObserver) {
  81839. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  81840. this._resizeObserver = null;
  81841. }
  81842. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  81843. _super.prototype.dispose.call(this);
  81844. };
  81845. /**
  81846. * Serialize the rendering pipeline (Used when exporting)
  81847. * @returns the serialized object
  81848. */
  81849. DefaultRenderingPipeline.prototype.serialize = function () {
  81850. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81851. serializationObject.customType = "DefaultRenderingPipeline";
  81852. return serializationObject;
  81853. };
  81854. /**
  81855. * Parse the serialized pipeline
  81856. * @param source Source pipeline.
  81857. * @param scene The scene to load the pipeline to.
  81858. * @param rootUrl The URL of the serialized pipeline.
  81859. * @returns An instantiated pipeline from the serialized object.
  81860. */
  81861. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  81862. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  81863. };
  81864. __decorate([
  81865. BABYLON.serialize()
  81866. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  81867. __decorate([
  81868. BABYLON.serialize()
  81869. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  81870. __decorate([
  81871. BABYLON.serialize()
  81872. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  81873. __decorate([
  81874. BABYLON.serialize()
  81875. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  81876. __decorate([
  81877. BABYLON.serialize()
  81878. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  81879. __decorate([
  81880. BABYLON.serialize()
  81881. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  81882. __decorate([
  81883. BABYLON.serialize()
  81884. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  81885. __decorate([
  81886. BABYLON.serialize()
  81887. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  81888. __decorate([
  81889. BABYLON.serialize()
  81890. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  81891. __decorate([
  81892. BABYLON.serialize()
  81893. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  81894. __decorate([
  81895. BABYLON.serialize()
  81896. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  81897. __decorate([
  81898. BABYLON.serialize()
  81899. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  81900. __decorate([
  81901. BABYLON.serialize()
  81902. ], DefaultRenderingPipeline.prototype, "samples", null);
  81903. __decorate([
  81904. BABYLON.serialize()
  81905. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  81906. __decorate([
  81907. BABYLON.serialize()
  81908. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  81909. __decorate([
  81910. BABYLON.serialize()
  81911. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  81912. __decorate([
  81913. BABYLON.serialize()
  81914. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  81915. return DefaultRenderingPipeline;
  81916. }(BABYLON.PostProcessRenderPipeline));
  81917. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  81918. })(BABYLON || (BABYLON = {}));
  81919. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  81920. var BABYLON;
  81921. (function (BABYLON) {
  81922. /**
  81923. * @hidden
  81924. */
  81925. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  81926. __extends(ImageProcessingConfigurationDefines, _super);
  81927. function ImageProcessingConfigurationDefines() {
  81928. var _this = _super.call(this) || this;
  81929. _this.IMAGEPROCESSING = false;
  81930. _this.VIGNETTE = false;
  81931. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  81932. _this.VIGNETTEBLENDMODEOPAQUE = false;
  81933. _this.TONEMAPPING = false;
  81934. _this.TONEMAPPING_ACES = false;
  81935. _this.CONTRAST = false;
  81936. _this.COLORCURVES = false;
  81937. _this.COLORGRADING = false;
  81938. _this.COLORGRADING3D = false;
  81939. _this.SAMPLER3DGREENDEPTH = false;
  81940. _this.SAMPLER3DBGRMAP = false;
  81941. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  81942. _this.EXPOSURE = false;
  81943. _this.rebuild();
  81944. return _this;
  81945. }
  81946. return ImageProcessingConfigurationDefines;
  81947. }(BABYLON.MaterialDefines));
  81948. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  81949. /**
  81950. * This groups together the common properties used for image processing either in direct forward pass
  81951. * or through post processing effect depending on the use of the image processing pipeline in your scene
  81952. * or not.
  81953. */
  81954. var ImageProcessingConfiguration = /** @class */ (function () {
  81955. function ImageProcessingConfiguration() {
  81956. /**
  81957. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  81958. */
  81959. this.colorCurves = new BABYLON.ColorCurves();
  81960. this._colorCurvesEnabled = false;
  81961. this._colorGradingEnabled = false;
  81962. this._colorGradingWithGreenDepth = true;
  81963. this._colorGradingBGR = true;
  81964. /** @hidden */
  81965. this._exposure = 1.0;
  81966. this._toneMappingEnabled = false;
  81967. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  81968. this._contrast = 1.0;
  81969. /**
  81970. * Vignette stretch size.
  81971. */
  81972. this.vignetteStretch = 0;
  81973. /**
  81974. * Vignette centre X Offset.
  81975. */
  81976. this.vignetteCentreX = 0;
  81977. /**
  81978. * Vignette centre Y Offset.
  81979. */
  81980. this.vignetteCentreY = 0;
  81981. /**
  81982. * Vignette weight or intensity of the vignette effect.
  81983. */
  81984. this.vignetteWeight = 1.5;
  81985. /**
  81986. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  81987. * if vignetteEnabled is set to true.
  81988. */
  81989. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  81990. /**
  81991. * Camera field of view used by the Vignette effect.
  81992. */
  81993. this.vignetteCameraFov = 0.5;
  81994. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  81995. this._vignetteEnabled = false;
  81996. this._applyByPostProcess = false;
  81997. this._isEnabled = true;
  81998. /**
  81999. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  82000. */
  82001. this.onUpdateParameters = new BABYLON.Observable();
  82002. }
  82003. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  82004. /**
  82005. * Gets wether the color curves effect is enabled.
  82006. */
  82007. get: function () {
  82008. return this._colorCurvesEnabled;
  82009. },
  82010. /**
  82011. * Sets wether the color curves effect is enabled.
  82012. */
  82013. set: function (value) {
  82014. if (this._colorCurvesEnabled === value) {
  82015. return;
  82016. }
  82017. this._colorCurvesEnabled = value;
  82018. this._updateParameters();
  82019. },
  82020. enumerable: true,
  82021. configurable: true
  82022. });
  82023. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  82024. /**
  82025. * Gets wether the color grading effect is enabled.
  82026. */
  82027. get: function () {
  82028. return this._colorGradingEnabled;
  82029. },
  82030. /**
  82031. * Sets wether the color grading effect is enabled.
  82032. */
  82033. set: function (value) {
  82034. if (this._colorGradingEnabled === value) {
  82035. return;
  82036. }
  82037. this._colorGradingEnabled = value;
  82038. this._updateParameters();
  82039. },
  82040. enumerable: true,
  82041. configurable: true
  82042. });
  82043. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  82044. /**
  82045. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  82046. */
  82047. get: function () {
  82048. return this._colorGradingWithGreenDepth;
  82049. },
  82050. /**
  82051. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  82052. */
  82053. set: function (value) {
  82054. if (this._colorGradingWithGreenDepth === value) {
  82055. return;
  82056. }
  82057. this._colorGradingWithGreenDepth = value;
  82058. this._updateParameters();
  82059. },
  82060. enumerable: true,
  82061. configurable: true
  82062. });
  82063. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  82064. /**
  82065. * Gets wether the color grading texture contains BGR values.
  82066. */
  82067. get: function () {
  82068. return this._colorGradingBGR;
  82069. },
  82070. /**
  82071. * Sets wether the color grading texture contains BGR values.
  82072. */
  82073. set: function (value) {
  82074. if (this._colorGradingBGR === value) {
  82075. return;
  82076. }
  82077. this._colorGradingBGR = value;
  82078. this._updateParameters();
  82079. },
  82080. enumerable: true,
  82081. configurable: true
  82082. });
  82083. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  82084. /**
  82085. * Gets the Exposure used in the effect.
  82086. */
  82087. get: function () {
  82088. return this._exposure;
  82089. },
  82090. /**
  82091. * Sets the Exposure used in the effect.
  82092. */
  82093. set: function (value) {
  82094. if (this._exposure === value) {
  82095. return;
  82096. }
  82097. this._exposure = value;
  82098. this._updateParameters();
  82099. },
  82100. enumerable: true,
  82101. configurable: true
  82102. });
  82103. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  82104. /**
  82105. * Gets wether the tone mapping effect is enabled.
  82106. */
  82107. get: function () {
  82108. return this._toneMappingEnabled;
  82109. },
  82110. /**
  82111. * Sets wether the tone mapping effect is enabled.
  82112. */
  82113. set: function (value) {
  82114. if (this._toneMappingEnabled === value) {
  82115. return;
  82116. }
  82117. this._toneMappingEnabled = value;
  82118. this._updateParameters();
  82119. },
  82120. enumerable: true,
  82121. configurable: true
  82122. });
  82123. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  82124. /**
  82125. * Gets the type of tone mapping effect.
  82126. */
  82127. get: function () {
  82128. return this._toneMappingType;
  82129. },
  82130. /**
  82131. * Sets the type of tone mapping effect used in BabylonJS.
  82132. */
  82133. set: function (value) {
  82134. if (this._toneMappingType === value) {
  82135. return;
  82136. }
  82137. this._toneMappingType = value;
  82138. this._updateParameters();
  82139. },
  82140. enumerable: true,
  82141. configurable: true
  82142. });
  82143. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  82144. /**
  82145. * Gets the contrast used in the effect.
  82146. */
  82147. get: function () {
  82148. return this._contrast;
  82149. },
  82150. /**
  82151. * Sets the contrast used in the effect.
  82152. */
  82153. set: function (value) {
  82154. if (this._contrast === value) {
  82155. return;
  82156. }
  82157. this._contrast = value;
  82158. this._updateParameters();
  82159. },
  82160. enumerable: true,
  82161. configurable: true
  82162. });
  82163. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  82164. /**
  82165. * Gets the vignette blend mode allowing different kind of effect.
  82166. */
  82167. get: function () {
  82168. return this._vignetteBlendMode;
  82169. },
  82170. /**
  82171. * Sets the vignette blend mode allowing different kind of effect.
  82172. */
  82173. set: function (value) {
  82174. if (this._vignetteBlendMode === value) {
  82175. return;
  82176. }
  82177. this._vignetteBlendMode = value;
  82178. this._updateParameters();
  82179. },
  82180. enumerable: true,
  82181. configurable: true
  82182. });
  82183. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  82184. /**
  82185. * Gets wether the vignette effect is enabled.
  82186. */
  82187. get: function () {
  82188. return this._vignetteEnabled;
  82189. },
  82190. /**
  82191. * Sets wether the vignette effect is enabled.
  82192. */
  82193. set: function (value) {
  82194. if (this._vignetteEnabled === value) {
  82195. return;
  82196. }
  82197. this._vignetteEnabled = value;
  82198. this._updateParameters();
  82199. },
  82200. enumerable: true,
  82201. configurable: true
  82202. });
  82203. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  82204. /**
  82205. * Gets wether the image processing is applied through a post process or not.
  82206. */
  82207. get: function () {
  82208. return this._applyByPostProcess;
  82209. },
  82210. /**
  82211. * Sets wether the image processing is applied through a post process or not.
  82212. */
  82213. set: function (value) {
  82214. if (this._applyByPostProcess === value) {
  82215. return;
  82216. }
  82217. this._applyByPostProcess = value;
  82218. this._updateParameters();
  82219. },
  82220. enumerable: true,
  82221. configurable: true
  82222. });
  82223. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  82224. /**
  82225. * Gets wether the image processing is enabled or not.
  82226. */
  82227. get: function () {
  82228. return this._isEnabled;
  82229. },
  82230. /**
  82231. * Sets wether the image processing is enabled or not.
  82232. */
  82233. set: function (value) {
  82234. if (this._isEnabled === value) {
  82235. return;
  82236. }
  82237. this._isEnabled = value;
  82238. this._updateParameters();
  82239. },
  82240. enumerable: true,
  82241. configurable: true
  82242. });
  82243. /**
  82244. * Method called each time the image processing information changes requires to recompile the effect.
  82245. */
  82246. ImageProcessingConfiguration.prototype._updateParameters = function () {
  82247. this.onUpdateParameters.notifyObservers(this);
  82248. };
  82249. ImageProcessingConfiguration.prototype.getClassName = function () {
  82250. return "ImageProcessingConfiguration";
  82251. };
  82252. /**
  82253. * Prepare the list of uniforms associated with the Image Processing effects.
  82254. * @param uniformsList The list of uniforms used in the effect
  82255. * @param defines the list of defines currently in use
  82256. */
  82257. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  82258. if (defines.EXPOSURE) {
  82259. uniforms.push("exposureLinear");
  82260. }
  82261. if (defines.CONTRAST) {
  82262. uniforms.push("contrast");
  82263. }
  82264. if (defines.COLORGRADING) {
  82265. uniforms.push("colorTransformSettings");
  82266. }
  82267. if (defines.VIGNETTE) {
  82268. uniforms.push("vInverseScreenSize");
  82269. uniforms.push("vignetteSettings1");
  82270. uniforms.push("vignetteSettings2");
  82271. }
  82272. if (defines.COLORCURVES) {
  82273. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  82274. }
  82275. };
  82276. /**
  82277. * Prepare the list of samplers associated with the Image Processing effects.
  82278. * @param uniformsList The list of uniforms used in the effect
  82279. * @param defines the list of defines currently in use
  82280. */
  82281. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  82282. if (defines.COLORGRADING) {
  82283. samplersList.push("txColorTransform");
  82284. }
  82285. };
  82286. /**
  82287. * Prepare the list of defines associated to the shader.
  82288. * @param defines the list of defines to complete
  82289. */
  82290. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  82291. if (forPostProcess === void 0) { forPostProcess = false; }
  82292. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  82293. defines.VIGNETTE = false;
  82294. defines.TONEMAPPING = false;
  82295. defines.TONEMAPPING_ACES = false;
  82296. defines.CONTRAST = false;
  82297. defines.EXPOSURE = false;
  82298. defines.COLORCURVES = false;
  82299. defines.COLORGRADING = false;
  82300. defines.COLORGRADING3D = false;
  82301. defines.IMAGEPROCESSING = false;
  82302. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  82303. return;
  82304. }
  82305. defines.VIGNETTE = this.vignetteEnabled;
  82306. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  82307. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  82308. defines.TONEMAPPING = this.toneMappingEnabled;
  82309. switch (this._toneMappingType) {
  82310. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  82311. defines.TONEMAPPING_ACES = true;
  82312. break;
  82313. }
  82314. defines.CONTRAST = (this.contrast !== 1.0);
  82315. defines.EXPOSURE = (this.exposure !== 1.0);
  82316. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  82317. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  82318. if (defines.COLORGRADING) {
  82319. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  82320. }
  82321. else {
  82322. defines.COLORGRADING3D = false;
  82323. }
  82324. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  82325. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  82326. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  82327. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  82328. };
  82329. /**
  82330. * Returns true if all the image processing information are ready.
  82331. */
  82332. ImageProcessingConfiguration.prototype.isReady = function () {
  82333. // Color Grading texure can not be none blocking.
  82334. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  82335. };
  82336. /**
  82337. * Binds the image processing to the shader.
  82338. * @param effect The effect to bind to
  82339. */
  82340. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  82341. if (aspectRatio === void 0) { aspectRatio = 1; }
  82342. // Color Curves
  82343. if (this._colorCurvesEnabled && this.colorCurves) {
  82344. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  82345. }
  82346. // Vignette
  82347. if (this._vignetteEnabled) {
  82348. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  82349. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  82350. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  82351. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  82352. var vignetteScaleX = vignetteScaleY * aspectRatio;
  82353. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  82354. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  82355. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  82356. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  82357. var vignettePower = -2.0 * this.vignetteWeight;
  82358. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  82359. }
  82360. // Exposure
  82361. effect.setFloat("exposureLinear", this.exposure);
  82362. // Contrast
  82363. effect.setFloat("contrast", this.contrast);
  82364. // Color transform settings
  82365. if (this.colorGradingTexture) {
  82366. effect.setTexture("txColorTransform", this.colorGradingTexture);
  82367. var textureSize = this.colorGradingTexture.getSize().height;
  82368. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  82369. 0.5 / textureSize, // textureOffset
  82370. textureSize, // textureSize
  82371. this.colorGradingTexture.level // weight
  82372. );
  82373. }
  82374. };
  82375. /**
  82376. * Clones the current image processing instance.
  82377. * @return The cloned image processing
  82378. */
  82379. ImageProcessingConfiguration.prototype.clone = function () {
  82380. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  82381. };
  82382. /**
  82383. * Serializes the current image processing instance to a json representation.
  82384. * @return a JSON representation
  82385. */
  82386. ImageProcessingConfiguration.prototype.serialize = function () {
  82387. return BABYLON.SerializationHelper.Serialize(this);
  82388. };
  82389. /**
  82390. * Parses the image processing from a json representation.
  82391. * @param source the JSON source to parse
  82392. * @return The parsed image processing
  82393. */
  82394. ImageProcessingConfiguration.Parse = function (source) {
  82395. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  82396. };
  82397. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  82398. /**
  82399. * Used to apply the vignette as a mix with the pixel color.
  82400. */
  82401. get: function () {
  82402. return this._VIGNETTEMODE_MULTIPLY;
  82403. },
  82404. enumerable: true,
  82405. configurable: true
  82406. });
  82407. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  82408. /**
  82409. * Used to apply the vignette as a replacement of the pixel color.
  82410. */
  82411. get: function () {
  82412. return this._VIGNETTEMODE_OPAQUE;
  82413. },
  82414. enumerable: true,
  82415. configurable: true
  82416. });
  82417. /**
  82418. * Default tone mapping applied in BabylonJS.
  82419. */
  82420. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  82421. /**
  82422. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  82423. * to other engines rendering to increase portability.
  82424. */
  82425. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  82426. // Static constants associated to the image processing.
  82427. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  82428. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  82429. __decorate([
  82430. BABYLON.serializeAsColorCurves()
  82431. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  82432. __decorate([
  82433. BABYLON.serialize()
  82434. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  82435. __decorate([
  82436. BABYLON.serializeAsTexture()
  82437. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  82438. __decorate([
  82439. BABYLON.serialize()
  82440. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  82441. __decorate([
  82442. BABYLON.serialize()
  82443. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  82444. __decorate([
  82445. BABYLON.serialize()
  82446. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  82447. __decorate([
  82448. BABYLON.serialize()
  82449. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  82450. __decorate([
  82451. BABYLON.serialize()
  82452. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  82453. __decorate([
  82454. BABYLON.serialize()
  82455. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  82456. __decorate([
  82457. BABYLON.serialize()
  82458. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  82459. __decorate([
  82460. BABYLON.serialize()
  82461. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  82462. __decorate([
  82463. BABYLON.serialize()
  82464. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  82465. __decorate([
  82466. BABYLON.serialize()
  82467. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  82468. __decorate([
  82469. BABYLON.serialize()
  82470. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  82471. __decorate([
  82472. BABYLON.serializeAsColor4()
  82473. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  82474. __decorate([
  82475. BABYLON.serialize()
  82476. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  82477. __decorate([
  82478. BABYLON.serialize()
  82479. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  82480. __decorate([
  82481. BABYLON.serialize()
  82482. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  82483. __decorate([
  82484. BABYLON.serialize()
  82485. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  82486. __decorate([
  82487. BABYLON.serialize()
  82488. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  82489. return ImageProcessingConfiguration;
  82490. }());
  82491. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  82492. })(BABYLON || (BABYLON = {}));
  82493. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  82494. var BABYLON;
  82495. (function (BABYLON) {
  82496. /**
  82497. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  82498. * It can help converting any input color in a desired output one. This can then be used to create effects
  82499. * from sepia, black and white to sixties or futuristic rendering...
  82500. *
  82501. * The only supported format is currently 3dl.
  82502. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  82503. */
  82504. var ColorGradingTexture = /** @class */ (function (_super) {
  82505. __extends(ColorGradingTexture, _super);
  82506. /**
  82507. * Instantiates a ColorGradingTexture from the following parameters.
  82508. *
  82509. * @param url The location of the color gradind data (currently only supporting 3dl)
  82510. * @param scene The scene the texture will be used in
  82511. */
  82512. function ColorGradingTexture(url, scene) {
  82513. var _this = _super.call(this, scene) || this;
  82514. if (!url) {
  82515. return _this;
  82516. }
  82517. _this._engine = scene.getEngine();
  82518. _this._textureMatrix = BABYLON.Matrix.Identity();
  82519. _this.name = url;
  82520. _this.url = url;
  82521. _this.hasAlpha = false;
  82522. _this.isCube = false;
  82523. _this.is3D = _this._engine.webGLVersion > 1;
  82524. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82525. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82526. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82527. _this.anisotropicFilteringLevel = 1;
  82528. _this._texture = _this._getFromCache(url, true);
  82529. if (!_this._texture) {
  82530. if (!scene.useDelayedTextureLoading) {
  82531. _this.loadTexture();
  82532. }
  82533. else {
  82534. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82535. }
  82536. }
  82537. return _this;
  82538. }
  82539. /**
  82540. * Returns the texture matrix used in most of the material.
  82541. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  82542. */
  82543. ColorGradingTexture.prototype.getTextureMatrix = function () {
  82544. return this._textureMatrix;
  82545. };
  82546. /**
  82547. * Occurs when the file being loaded is a .3dl LUT file.
  82548. */
  82549. ColorGradingTexture.prototype.load3dlTexture = function () {
  82550. var engine = this._engine;
  82551. var texture;
  82552. if (engine.webGLVersion === 1) {
  82553. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82554. }
  82555. else {
  82556. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82557. }
  82558. this._texture = texture;
  82559. var callback = function (text) {
  82560. if (typeof text !== "string") {
  82561. return;
  82562. }
  82563. var data = null;
  82564. var tempData = null;
  82565. var line;
  82566. var lines = text.split('\n');
  82567. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  82568. var maxColor = 0;
  82569. for (var i = 0; i < lines.length; i++) {
  82570. line = lines[i];
  82571. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  82572. continue;
  82573. if (line.indexOf('#') === 0)
  82574. continue;
  82575. var words = line.split(" ");
  82576. if (size === 0) {
  82577. // Number of space + one
  82578. size = words.length;
  82579. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  82580. tempData = new Float32Array(size * size * size * 4);
  82581. continue;
  82582. }
  82583. if (size != 0) {
  82584. var r = Math.max(parseInt(words[0]), 0);
  82585. var g = Math.max(parseInt(words[1]), 0);
  82586. var b = Math.max(parseInt(words[2]), 0);
  82587. maxColor = Math.max(r, maxColor);
  82588. maxColor = Math.max(g, maxColor);
  82589. maxColor = Math.max(b, maxColor);
  82590. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  82591. if (tempData) {
  82592. tempData[pixelStorageIndex + 0] = r;
  82593. tempData[pixelStorageIndex + 1] = g;
  82594. tempData[pixelStorageIndex + 2] = b;
  82595. }
  82596. pixelIndexSlice++;
  82597. if (pixelIndexSlice % size == 0) {
  82598. pixelIndexH++;
  82599. pixelIndexSlice = 0;
  82600. if (pixelIndexH % size == 0) {
  82601. pixelIndexW++;
  82602. pixelIndexH = 0;
  82603. }
  82604. }
  82605. }
  82606. }
  82607. if (tempData && data) {
  82608. for (var i = 0; i < tempData.length; i++) {
  82609. if (i > 0 && (i + 1) % 4 === 0) {
  82610. data[i] = 255;
  82611. }
  82612. else {
  82613. var value = tempData[i];
  82614. data[i] = (value / maxColor * 255);
  82615. }
  82616. }
  82617. }
  82618. if (texture.is3D) {
  82619. texture.updateSize(size, size, size);
  82620. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  82621. }
  82622. else {
  82623. texture.updateSize(size * size, size);
  82624. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  82625. }
  82626. };
  82627. var scene = this.getScene();
  82628. if (scene) {
  82629. scene._loadFile(this.url, callback);
  82630. }
  82631. else {
  82632. this._engine._loadFile(this.url, callback);
  82633. }
  82634. return this._texture;
  82635. };
  82636. /**
  82637. * Starts the loading process of the texture.
  82638. */
  82639. ColorGradingTexture.prototype.loadTexture = function () {
  82640. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  82641. this.load3dlTexture();
  82642. }
  82643. };
  82644. /**
  82645. * Clones the color gradind texture.
  82646. */
  82647. ColorGradingTexture.prototype.clone = function () {
  82648. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  82649. // Base texture
  82650. newTexture.level = this.level;
  82651. return newTexture;
  82652. };
  82653. /**
  82654. * Called during delayed load for textures.
  82655. */
  82656. ColorGradingTexture.prototype.delayLoad = function () {
  82657. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82658. return;
  82659. }
  82660. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82661. this._texture = this._getFromCache(this.url, true);
  82662. if (!this._texture) {
  82663. this.loadTexture();
  82664. }
  82665. };
  82666. /**
  82667. * Parses a color grading texture serialized by Babylon.
  82668. * @param parsedTexture The texture information being parsedTexture
  82669. * @param scene The scene to load the texture in
  82670. * @param rootUrl The root url of the data assets to load
  82671. * @return A color gradind texture
  82672. */
  82673. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  82674. var texture = null;
  82675. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  82676. texture = new ColorGradingTexture(parsedTexture.name, scene);
  82677. texture.name = parsedTexture.name;
  82678. texture.level = parsedTexture.level;
  82679. }
  82680. return texture;
  82681. };
  82682. /**
  82683. * Serializes the LUT texture to json format.
  82684. */
  82685. ColorGradingTexture.prototype.serialize = function () {
  82686. if (!this.name) {
  82687. return null;
  82688. }
  82689. var serializationObject = {};
  82690. serializationObject.name = this.name;
  82691. serializationObject.level = this.level;
  82692. serializationObject.customType = "BABYLON.ColorGradingTexture";
  82693. return serializationObject;
  82694. };
  82695. /**
  82696. * Empty line regex stored for GC.
  82697. */
  82698. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  82699. return ColorGradingTexture;
  82700. }(BABYLON.BaseTexture));
  82701. BABYLON.ColorGradingTexture = ColorGradingTexture;
  82702. })(BABYLON || (BABYLON = {}));
  82703. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  82704. var BABYLON;
  82705. (function (BABYLON) {
  82706. /**
  82707. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  82708. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  82709. * 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;
  82710. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  82711. */
  82712. var ColorCurves = /** @class */ (function () {
  82713. function ColorCurves() {
  82714. this._dirty = true;
  82715. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  82716. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  82717. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  82718. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  82719. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  82720. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  82721. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  82722. this._globalHue = 30;
  82723. this._globalDensity = 0;
  82724. this._globalSaturation = 0;
  82725. this._globalExposure = 0;
  82726. this._highlightsHue = 30;
  82727. this._highlightsDensity = 0;
  82728. this._highlightsSaturation = 0;
  82729. this._highlightsExposure = 0;
  82730. this._midtonesHue = 30;
  82731. this._midtonesDensity = 0;
  82732. this._midtonesSaturation = 0;
  82733. this._midtonesExposure = 0;
  82734. this._shadowsHue = 30;
  82735. this._shadowsDensity = 0;
  82736. this._shadowsSaturation = 0;
  82737. this._shadowsExposure = 0;
  82738. }
  82739. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  82740. /**
  82741. * Gets the global Hue value.
  82742. * 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).
  82743. */
  82744. get: function () {
  82745. return this._globalHue;
  82746. },
  82747. /**
  82748. * Sets the global Hue value.
  82749. * 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).
  82750. */
  82751. set: function (value) {
  82752. this._globalHue = value;
  82753. this._dirty = true;
  82754. },
  82755. enumerable: true,
  82756. configurable: true
  82757. });
  82758. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  82759. /**
  82760. * Gets the global Density value.
  82761. * 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.
  82762. * Values less than zero provide a filter of opposite hue.
  82763. */
  82764. get: function () {
  82765. return this._globalDensity;
  82766. },
  82767. /**
  82768. * Sets the global Density value.
  82769. * 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.
  82770. * Values less than zero provide a filter of opposite hue.
  82771. */
  82772. set: function (value) {
  82773. this._globalDensity = value;
  82774. this._dirty = true;
  82775. },
  82776. enumerable: true,
  82777. configurable: true
  82778. });
  82779. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  82780. /**
  82781. * Gets the global Saturation value.
  82782. * 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.
  82783. */
  82784. get: function () {
  82785. return this._globalSaturation;
  82786. },
  82787. /**
  82788. * Sets the global Saturation value.
  82789. * 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.
  82790. */
  82791. set: function (value) {
  82792. this._globalSaturation = value;
  82793. this._dirty = true;
  82794. },
  82795. enumerable: true,
  82796. configurable: true
  82797. });
  82798. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  82799. /**
  82800. * Gets the global Exposure value.
  82801. * 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.
  82802. */
  82803. get: function () {
  82804. return this._globalExposure;
  82805. },
  82806. /**
  82807. * Sets the global Exposure value.
  82808. * 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.
  82809. */
  82810. set: function (value) {
  82811. this._globalExposure = value;
  82812. this._dirty = true;
  82813. },
  82814. enumerable: true,
  82815. configurable: true
  82816. });
  82817. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  82818. /**
  82819. * Gets the highlights Hue value.
  82820. * 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).
  82821. */
  82822. get: function () {
  82823. return this._highlightsHue;
  82824. },
  82825. /**
  82826. * Sets the highlights Hue value.
  82827. * 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).
  82828. */
  82829. set: function (value) {
  82830. this._highlightsHue = value;
  82831. this._dirty = true;
  82832. },
  82833. enumerable: true,
  82834. configurable: true
  82835. });
  82836. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  82837. /**
  82838. * Gets the highlights Density value.
  82839. * 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.
  82840. * Values less than zero provide a filter of opposite hue.
  82841. */
  82842. get: function () {
  82843. return this._highlightsDensity;
  82844. },
  82845. /**
  82846. * Sets the highlights Density value.
  82847. * 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.
  82848. * Values less than zero provide a filter of opposite hue.
  82849. */
  82850. set: function (value) {
  82851. this._highlightsDensity = value;
  82852. this._dirty = true;
  82853. },
  82854. enumerable: true,
  82855. configurable: true
  82856. });
  82857. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  82858. /**
  82859. * Gets the highlights Saturation value.
  82860. * 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.
  82861. */
  82862. get: function () {
  82863. return this._highlightsSaturation;
  82864. },
  82865. /**
  82866. * Sets the highlights Saturation value.
  82867. * 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.
  82868. */
  82869. set: function (value) {
  82870. this._highlightsSaturation = value;
  82871. this._dirty = true;
  82872. },
  82873. enumerable: true,
  82874. configurable: true
  82875. });
  82876. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  82877. /**
  82878. * Gets the highlights Exposure value.
  82879. * 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.
  82880. */
  82881. get: function () {
  82882. return this._highlightsExposure;
  82883. },
  82884. /**
  82885. * Sets the highlights Exposure value.
  82886. * 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.
  82887. */
  82888. set: function (value) {
  82889. this._highlightsExposure = value;
  82890. this._dirty = true;
  82891. },
  82892. enumerable: true,
  82893. configurable: true
  82894. });
  82895. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  82896. /**
  82897. * Gets the midtones Hue value.
  82898. * 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).
  82899. */
  82900. get: function () {
  82901. return this._midtonesHue;
  82902. },
  82903. /**
  82904. * Sets the midtones Hue value.
  82905. * 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).
  82906. */
  82907. set: function (value) {
  82908. this._midtonesHue = value;
  82909. this._dirty = true;
  82910. },
  82911. enumerable: true,
  82912. configurable: true
  82913. });
  82914. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  82915. /**
  82916. * Gets the midtones Density value.
  82917. * 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.
  82918. * Values less than zero provide a filter of opposite hue.
  82919. */
  82920. get: function () {
  82921. return this._midtonesDensity;
  82922. },
  82923. /**
  82924. * Sets the midtones Density value.
  82925. * 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.
  82926. * Values less than zero provide a filter of opposite hue.
  82927. */
  82928. set: function (value) {
  82929. this._midtonesDensity = value;
  82930. this._dirty = true;
  82931. },
  82932. enumerable: true,
  82933. configurable: true
  82934. });
  82935. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  82936. /**
  82937. * Gets the midtones Saturation value.
  82938. * 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.
  82939. */
  82940. get: function () {
  82941. return this._midtonesSaturation;
  82942. },
  82943. /**
  82944. * Sets the midtones Saturation value.
  82945. * 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.
  82946. */
  82947. set: function (value) {
  82948. this._midtonesSaturation = value;
  82949. this._dirty = true;
  82950. },
  82951. enumerable: true,
  82952. configurable: true
  82953. });
  82954. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  82955. /**
  82956. * Gets the midtones Exposure value.
  82957. * 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.
  82958. */
  82959. get: function () {
  82960. return this._midtonesExposure;
  82961. },
  82962. /**
  82963. * Sets the midtones Exposure value.
  82964. * 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.
  82965. */
  82966. set: function (value) {
  82967. this._midtonesExposure = value;
  82968. this._dirty = true;
  82969. },
  82970. enumerable: true,
  82971. configurable: true
  82972. });
  82973. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  82974. /**
  82975. * Gets the shadows Hue value.
  82976. * 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).
  82977. */
  82978. get: function () {
  82979. return this._shadowsHue;
  82980. },
  82981. /**
  82982. * Sets the shadows Hue value.
  82983. * 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).
  82984. */
  82985. set: function (value) {
  82986. this._shadowsHue = value;
  82987. this._dirty = true;
  82988. },
  82989. enumerable: true,
  82990. configurable: true
  82991. });
  82992. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  82993. /**
  82994. * Gets the shadows Density value.
  82995. * 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.
  82996. * Values less than zero provide a filter of opposite hue.
  82997. */
  82998. get: function () {
  82999. return this._shadowsDensity;
  83000. },
  83001. /**
  83002. * Sets the shadows Density value.
  83003. * 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.
  83004. * Values less than zero provide a filter of opposite hue.
  83005. */
  83006. set: function (value) {
  83007. this._shadowsDensity = value;
  83008. this._dirty = true;
  83009. },
  83010. enumerable: true,
  83011. configurable: true
  83012. });
  83013. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  83014. /**
  83015. * Gets the shadows Saturation value.
  83016. * 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.
  83017. */
  83018. get: function () {
  83019. return this._shadowsSaturation;
  83020. },
  83021. /**
  83022. * Sets the shadows Saturation value.
  83023. * 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.
  83024. */
  83025. set: function (value) {
  83026. this._shadowsSaturation = value;
  83027. this._dirty = true;
  83028. },
  83029. enumerable: true,
  83030. configurable: true
  83031. });
  83032. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  83033. /**
  83034. * Gets the shadows Exposure value.
  83035. * 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.
  83036. */
  83037. get: function () {
  83038. return this._shadowsExposure;
  83039. },
  83040. /**
  83041. * Sets the shadows Exposure value.
  83042. * 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.
  83043. */
  83044. set: function (value) {
  83045. this._shadowsExposure = value;
  83046. this._dirty = true;
  83047. },
  83048. enumerable: true,
  83049. configurable: true
  83050. });
  83051. ColorCurves.prototype.getClassName = function () {
  83052. return "ColorCurves";
  83053. };
  83054. /**
  83055. * Binds the color curves to the shader.
  83056. * @param colorCurves The color curve to bind
  83057. * @param effect The effect to bind to
  83058. */
  83059. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  83060. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  83061. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  83062. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  83063. if (colorCurves._dirty) {
  83064. colorCurves._dirty = false;
  83065. // Fill in global info.
  83066. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  83067. // Compute highlights info.
  83068. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  83069. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  83070. // Compute midtones info.
  83071. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  83072. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  83073. // Compute shadows info.
  83074. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  83075. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  83076. // Compute deltas (neutral is midtones).
  83077. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  83078. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  83079. }
  83080. if (effect) {
  83081. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  83082. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  83083. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  83084. }
  83085. };
  83086. /**
  83087. * Prepare the list of uniforms associated with the ColorCurves effects.
  83088. * @param uniformsList The list of uniforms used in the effect
  83089. */
  83090. ColorCurves.PrepareUniforms = function (uniformsList) {
  83091. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  83092. };
  83093. /**
  83094. * Returns color grading data based on a hue, density, saturation and exposure value.
  83095. * @param filterHue The hue of the color filter.
  83096. * @param filterDensity The density of the color filter.
  83097. * @param saturation The saturation.
  83098. * @param exposure The exposure.
  83099. * @param result The result data container.
  83100. */
  83101. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  83102. if (hue == null) {
  83103. return;
  83104. }
  83105. hue = ColorCurves.clamp(hue, 0, 360);
  83106. density = ColorCurves.clamp(density, -100, 100);
  83107. saturation = ColorCurves.clamp(saturation, -100, 100);
  83108. exposure = ColorCurves.clamp(exposure, -100, 100);
  83109. // Remap the slider/config filter density with non-linear mapping and also scale by half
  83110. // so that the maximum filter density is only 50% control. This provides fine control
  83111. // for small values and reasonable range.
  83112. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  83113. density *= 0.5;
  83114. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  83115. if (density < 0) {
  83116. density *= -1;
  83117. hue = (hue + 180) % 360;
  83118. }
  83119. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  83120. result.scaleToRef(2, result);
  83121. result.a = 1 + 0.01 * saturation;
  83122. };
  83123. /**
  83124. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  83125. * @param value The input slider value in range [-100,100].
  83126. * @returns Adjusted value.
  83127. */
  83128. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  83129. value /= 100;
  83130. var x = Math.abs(value);
  83131. x = Math.pow(x, 2);
  83132. if (value < 0) {
  83133. x *= -1;
  83134. }
  83135. x *= 100;
  83136. return x;
  83137. };
  83138. /**
  83139. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  83140. * @param hue The hue (H) input.
  83141. * @param saturation The saturation (S) input.
  83142. * @param brightness The brightness (B) input.
  83143. * @result An RGBA color represented as Vector4.
  83144. */
  83145. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  83146. var h = ColorCurves.clamp(hue, 0, 360);
  83147. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  83148. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  83149. if (s === 0) {
  83150. result.r = v;
  83151. result.g = v;
  83152. result.b = v;
  83153. }
  83154. else {
  83155. // sector 0 to 5
  83156. h /= 60;
  83157. var i = Math.floor(h);
  83158. // fractional part of h
  83159. var f = h - i;
  83160. var p = v * (1 - s);
  83161. var q = v * (1 - s * f);
  83162. var t = v * (1 - s * (1 - f));
  83163. switch (i) {
  83164. case 0:
  83165. result.r = v;
  83166. result.g = t;
  83167. result.b = p;
  83168. break;
  83169. case 1:
  83170. result.r = q;
  83171. result.g = v;
  83172. result.b = p;
  83173. break;
  83174. case 2:
  83175. result.r = p;
  83176. result.g = v;
  83177. result.b = t;
  83178. break;
  83179. case 3:
  83180. result.r = p;
  83181. result.g = q;
  83182. result.b = v;
  83183. break;
  83184. case 4:
  83185. result.r = t;
  83186. result.g = p;
  83187. result.b = v;
  83188. break;
  83189. default: // case 5:
  83190. result.r = v;
  83191. result.g = p;
  83192. result.b = q;
  83193. break;
  83194. }
  83195. }
  83196. result.a = 1;
  83197. };
  83198. /**
  83199. * Returns a value clamped between min and max
  83200. * @param value The value to clamp
  83201. * @param min The minimum of value
  83202. * @param max The maximum of value
  83203. * @returns The clamped value.
  83204. */
  83205. ColorCurves.clamp = function (value, min, max) {
  83206. return Math.min(Math.max(value, min), max);
  83207. };
  83208. /**
  83209. * Clones the current color curve instance.
  83210. * @return The cloned curves
  83211. */
  83212. ColorCurves.prototype.clone = function () {
  83213. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  83214. };
  83215. /**
  83216. * Serializes the current color curve instance to a json representation.
  83217. * @return a JSON representation
  83218. */
  83219. ColorCurves.prototype.serialize = function () {
  83220. return BABYLON.SerializationHelper.Serialize(this);
  83221. };
  83222. /**
  83223. * Parses the color curve from a json representation.
  83224. * @param source the JSON source to parse
  83225. * @return The parsed curves
  83226. */
  83227. ColorCurves.Parse = function (source) {
  83228. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  83229. };
  83230. __decorate([
  83231. BABYLON.serialize()
  83232. ], ColorCurves.prototype, "_globalHue", void 0);
  83233. __decorate([
  83234. BABYLON.serialize()
  83235. ], ColorCurves.prototype, "_globalDensity", void 0);
  83236. __decorate([
  83237. BABYLON.serialize()
  83238. ], ColorCurves.prototype, "_globalSaturation", void 0);
  83239. __decorate([
  83240. BABYLON.serialize()
  83241. ], ColorCurves.prototype, "_globalExposure", void 0);
  83242. __decorate([
  83243. BABYLON.serialize()
  83244. ], ColorCurves.prototype, "_highlightsHue", void 0);
  83245. __decorate([
  83246. BABYLON.serialize()
  83247. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  83248. __decorate([
  83249. BABYLON.serialize()
  83250. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  83251. __decorate([
  83252. BABYLON.serialize()
  83253. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  83254. __decorate([
  83255. BABYLON.serialize()
  83256. ], ColorCurves.prototype, "_midtonesHue", void 0);
  83257. __decorate([
  83258. BABYLON.serialize()
  83259. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  83260. __decorate([
  83261. BABYLON.serialize()
  83262. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  83263. __decorate([
  83264. BABYLON.serialize()
  83265. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  83266. return ColorCurves;
  83267. }());
  83268. BABYLON.ColorCurves = ColorCurves;
  83269. })(BABYLON || (BABYLON = {}));
  83270. //# sourceMappingURL=babylon.colorCurves.js.map
  83271. var BABYLON;
  83272. (function (BABYLON) {
  83273. var RefractionPostProcess = /** @class */ (function (_super) {
  83274. __extends(RefractionPostProcess, _super);
  83275. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  83276. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  83277. _this.color = color;
  83278. _this.depth = depth;
  83279. _this.colorLevel = colorLevel;
  83280. _this._ownRefractionTexture = true;
  83281. _this.onActivateObservable.add(function (cam) {
  83282. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  83283. });
  83284. _this.onApplyObservable.add(function (effect) {
  83285. effect.setColor3("baseColor", _this.color);
  83286. effect.setFloat("depth", _this.depth);
  83287. effect.setFloat("colorLevel", _this.colorLevel);
  83288. effect.setTexture("refractionSampler", _this._refTexture);
  83289. });
  83290. return _this;
  83291. }
  83292. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  83293. /**
  83294. * Gets or sets the refraction texture
  83295. * Please note that you are responsible for disposing the texture if you set it manually
  83296. */
  83297. get: function () {
  83298. return this._refTexture;
  83299. },
  83300. set: function (value) {
  83301. if (this._refTexture && this._ownRefractionTexture) {
  83302. this._refTexture.dispose();
  83303. }
  83304. this._refTexture = value;
  83305. this._ownRefractionTexture = false;
  83306. },
  83307. enumerable: true,
  83308. configurable: true
  83309. });
  83310. // Methods
  83311. RefractionPostProcess.prototype.dispose = function (camera) {
  83312. if (this._refTexture && this._ownRefractionTexture) {
  83313. this._refTexture.dispose();
  83314. this._refTexture = null;
  83315. }
  83316. _super.prototype.dispose.call(this, camera);
  83317. };
  83318. return RefractionPostProcess;
  83319. }(BABYLON.PostProcess));
  83320. BABYLON.RefractionPostProcess = RefractionPostProcess;
  83321. })(BABYLON || (BABYLON = {}));
  83322. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  83323. var BABYLON;
  83324. (function (BABYLON) {
  83325. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  83326. __extends(BlackAndWhitePostProcess, _super);
  83327. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  83328. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  83329. _this.degree = 1;
  83330. _this.onApplyObservable.add(function (effect) {
  83331. effect.setFloat("degree", _this.degree);
  83332. });
  83333. return _this;
  83334. }
  83335. return BlackAndWhitePostProcess;
  83336. }(BABYLON.PostProcess));
  83337. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  83338. })(BABYLON || (BABYLON = {}));
  83339. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  83340. var BABYLON;
  83341. (function (BABYLON) {
  83342. /**
  83343. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  83344. * input texture to perform effects such as edge detection or sharpening
  83345. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  83346. */
  83347. var ConvolutionPostProcess = /** @class */ (function (_super) {
  83348. __extends(ConvolutionPostProcess, _super);
  83349. /**
  83350. * Creates a new instance ConvolutionPostProcess
  83351. * @param name The name of the effect.
  83352. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  83353. * @param options The required width/height ratio to downsize to before computing the render pass.
  83354. * @param camera The camera to apply the render pass to.
  83355. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83356. * @param engine The engine which the post process will be applied. (default: current engine)
  83357. * @param reusable If the post process can be reused on the same frame. (default: false)
  83358. * @param textureType Type of textures used when performing the post process. (default: 0)
  83359. */
  83360. function ConvolutionPostProcess(name,
  83361. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  83362. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  83363. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83364. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  83365. _this.kernel = kernel;
  83366. _this.onApply = function (effect) {
  83367. effect.setFloat2("screenSize", _this.width, _this.height);
  83368. effect.setArray("kernel", _this.kernel);
  83369. };
  83370. return _this;
  83371. }
  83372. // Statics
  83373. /**
  83374. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83375. */
  83376. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  83377. /**
  83378. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83379. */
  83380. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  83381. /**
  83382. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83383. */
  83384. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  83385. /**
  83386. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83387. */
  83388. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  83389. /**
  83390. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83391. */
  83392. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  83393. /**
  83394. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83395. */
  83396. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  83397. return ConvolutionPostProcess;
  83398. }(BABYLON.PostProcess));
  83399. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  83400. })(BABYLON || (BABYLON = {}));
  83401. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  83402. var BABYLON;
  83403. (function (BABYLON) {
  83404. var FilterPostProcess = /** @class */ (function (_super) {
  83405. __extends(FilterPostProcess, _super);
  83406. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  83407. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  83408. _this.kernelMatrix = kernelMatrix;
  83409. _this.onApply = function (effect) {
  83410. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  83411. };
  83412. return _this;
  83413. }
  83414. return FilterPostProcess;
  83415. }(BABYLON.PostProcess));
  83416. BABYLON.FilterPostProcess = FilterPostProcess;
  83417. })(BABYLON || (BABYLON = {}));
  83418. //# sourceMappingURL=babylon.filterPostProcess.js.map
  83419. var BABYLON;
  83420. (function (BABYLON) {
  83421. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  83422. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  83423. __extends(VolumetricLightScatteringPostProcess, _super);
  83424. /**
  83425. * @constructor
  83426. * @param {string} name - The post-process name
  83427. * @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)
  83428. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  83429. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  83430. * @param {number} samples - The post-process quality, default 100
  83431. * @param {number} samplingMode - The post-process filtering mode
  83432. * @param {BABYLON.Engine} engine - The babylon engine
  83433. * @param {boolean} reusable - If the post-process is reusable
  83434. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  83435. */
  83436. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  83437. if (samples === void 0) { samples = 100; }
  83438. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83439. 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;
  83440. _this._screenCoordinates = BABYLON.Vector2.Zero();
  83441. /**
  83442. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  83443. */
  83444. _this.customMeshPosition = BABYLON.Vector3.Zero();
  83445. /**
  83446. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  83447. */
  83448. _this.useCustomMeshPosition = false;
  83449. /**
  83450. * If the post-process should inverse the light scattering direction
  83451. */
  83452. _this.invert = true;
  83453. /**
  83454. * Array containing the excluded meshes not rendered in the internal pass
  83455. */
  83456. _this.excludedMeshes = new Array();
  83457. /**
  83458. * Controls the overall intensity of the post-process
  83459. */
  83460. _this.exposure = 0.3;
  83461. /**
  83462. * Dissipates each sample's contribution in range [0, 1]
  83463. */
  83464. _this.decay = 0.96815;
  83465. /**
  83466. * Controls the overall intensity of each sample
  83467. */
  83468. _this.weight = 0.58767;
  83469. /**
  83470. * Controls the density of each sample
  83471. */
  83472. _this.density = 0.926;
  83473. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  83474. engine = scene.getEngine();
  83475. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  83476. // Configure mesh
  83477. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  83478. // Configure
  83479. _this._createPass(scene, ratio.passRatio || ratio);
  83480. _this.onActivate = function (camera) {
  83481. if (!_this.isSupported) {
  83482. _this.dispose(camera);
  83483. }
  83484. _this.onActivate = null;
  83485. };
  83486. _this.onApplyObservable.add(function (effect) {
  83487. _this._updateMeshScreenCoordinates(scene);
  83488. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  83489. effect.setFloat("exposure", _this.exposure);
  83490. effect.setFloat("decay", _this.decay);
  83491. effect.setFloat("weight", _this.weight);
  83492. effect.setFloat("density", _this.density);
  83493. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  83494. });
  83495. return _this;
  83496. }
  83497. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  83498. get: function () {
  83499. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  83500. return false;
  83501. },
  83502. set: function (useDiffuseColor) {
  83503. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  83504. },
  83505. enumerable: true,
  83506. configurable: true
  83507. });
  83508. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  83509. return "VolumetricLightScatteringPostProcess";
  83510. };
  83511. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  83512. var mesh = subMesh.getMesh();
  83513. // Render this.mesh as default
  83514. if (mesh === this.mesh && mesh.material) {
  83515. return mesh.material.isReady(mesh);
  83516. }
  83517. var defines = [];
  83518. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83519. var material = subMesh.getMaterial();
  83520. // Alpha test
  83521. if (material) {
  83522. if (material.needAlphaTesting()) {
  83523. defines.push("#define ALPHATEST");
  83524. }
  83525. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83526. attribs.push(BABYLON.VertexBuffer.UVKind);
  83527. defines.push("#define UV1");
  83528. }
  83529. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83530. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83531. defines.push("#define UV2");
  83532. }
  83533. }
  83534. // Bones
  83535. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83536. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83537. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83538. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83539. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  83540. }
  83541. else {
  83542. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83543. }
  83544. // Instances
  83545. if (useInstances) {
  83546. defines.push("#define INSTANCES");
  83547. attribs.push("world0");
  83548. attribs.push("world1");
  83549. attribs.push("world2");
  83550. attribs.push("world3");
  83551. }
  83552. // Get correct effect
  83553. var join = defines.join("\n");
  83554. if (this._cachedDefines !== join) {
  83555. this._cachedDefines = join;
  83556. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  83557. }
  83558. return this._volumetricLightScatteringPass.isReady();
  83559. };
  83560. /**
  83561. * Sets the new light position for light scattering effect
  83562. * @param {BABYLON.Vector3} The new custom light position
  83563. */
  83564. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  83565. this.customMeshPosition = position;
  83566. };
  83567. /**
  83568. * Returns the light position for light scattering effect
  83569. * @return {BABYLON.Vector3} The custom light position
  83570. */
  83571. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  83572. return this.customMeshPosition;
  83573. };
  83574. /**
  83575. * Disposes the internal assets and detaches the post-process from the camera
  83576. */
  83577. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  83578. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  83579. if (rttIndex !== -1) {
  83580. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  83581. }
  83582. this._volumetricLightScatteringRTT.dispose();
  83583. _super.prototype.dispose.call(this, camera);
  83584. };
  83585. /**
  83586. * Returns the render target texture used by the post-process
  83587. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  83588. */
  83589. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  83590. return this._volumetricLightScatteringRTT;
  83591. };
  83592. // Private methods
  83593. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  83594. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  83595. return true;
  83596. }
  83597. return false;
  83598. };
  83599. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  83600. var _this = this;
  83601. var engine = scene.getEngine();
  83602. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83603. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83604. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83605. this._volumetricLightScatteringRTT.renderList = null;
  83606. this._volumetricLightScatteringRTT.renderParticles = false;
  83607. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  83608. var camera = this.getCamera();
  83609. if (camera) {
  83610. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  83611. }
  83612. else {
  83613. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  83614. }
  83615. // Custom render function for submeshes
  83616. var renderSubMesh = function (subMesh) {
  83617. var mesh = subMesh.getRenderingMesh();
  83618. if (_this._meshExcluded(mesh)) {
  83619. return;
  83620. }
  83621. var material = subMesh.getMaterial();
  83622. if (!material) {
  83623. return;
  83624. }
  83625. var scene = mesh.getScene();
  83626. var engine = scene.getEngine();
  83627. // Culling
  83628. engine.setState(material.backFaceCulling);
  83629. // Managing instances
  83630. var batch = mesh._getInstancesRenderList(subMesh._id);
  83631. if (batch.mustReturn) {
  83632. return;
  83633. }
  83634. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83635. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  83636. var effect = _this._volumetricLightScatteringPass;
  83637. if (mesh === _this.mesh) {
  83638. if (subMesh.effect) {
  83639. effect = subMesh.effect;
  83640. }
  83641. else {
  83642. effect = material.getEffect();
  83643. }
  83644. }
  83645. engine.enableEffect(effect);
  83646. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  83647. if (mesh === _this.mesh) {
  83648. material.bind(mesh.getWorldMatrix(), mesh);
  83649. }
  83650. else {
  83651. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  83652. // Alpha test
  83653. if (material && material.needAlphaTesting()) {
  83654. var alphaTexture = material.getAlphaTestTexture();
  83655. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  83656. if (alphaTexture) {
  83657. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83658. }
  83659. }
  83660. // Bones
  83661. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83662. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83663. }
  83664. }
  83665. // Draw
  83666. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  83667. }
  83668. };
  83669. // Render target texture callbacks
  83670. var savedSceneClearColor;
  83671. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  83672. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  83673. savedSceneClearColor = scene.clearColor;
  83674. scene.clearColor = sceneClearColor;
  83675. });
  83676. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  83677. scene.clearColor = savedSceneClearColor;
  83678. });
  83679. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83680. var engine = scene.getEngine();
  83681. var index;
  83682. if (depthOnlySubMeshes.length) {
  83683. engine.setColorWrite(false);
  83684. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83685. renderSubMesh(depthOnlySubMeshes.data[index]);
  83686. }
  83687. engine.setColorWrite(true);
  83688. }
  83689. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83690. renderSubMesh(opaqueSubMeshes.data[index]);
  83691. }
  83692. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83693. renderSubMesh(alphaTestSubMeshes.data[index]);
  83694. }
  83695. if (transparentSubMeshes.length) {
  83696. // Sort sub meshes
  83697. for (index = 0; index < transparentSubMeshes.length; index++) {
  83698. var submesh = transparentSubMeshes.data[index];
  83699. var boundingInfo = submesh.getBoundingInfo();
  83700. if (boundingInfo && scene.activeCamera) {
  83701. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  83702. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  83703. }
  83704. }
  83705. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  83706. sortedArray.sort(function (a, b) {
  83707. // Alpha index first
  83708. if (a._alphaIndex > b._alphaIndex) {
  83709. return 1;
  83710. }
  83711. if (a._alphaIndex < b._alphaIndex) {
  83712. return -1;
  83713. }
  83714. // Then distance to camera
  83715. if (a._distanceToCamera < b._distanceToCamera) {
  83716. return 1;
  83717. }
  83718. if (a._distanceToCamera > b._distanceToCamera) {
  83719. return -1;
  83720. }
  83721. return 0;
  83722. });
  83723. // Render sub meshes
  83724. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  83725. for (index = 0; index < sortedArray.length; index++) {
  83726. renderSubMesh(sortedArray[index]);
  83727. }
  83728. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  83729. }
  83730. };
  83731. };
  83732. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  83733. var transform = scene.getTransformMatrix();
  83734. var meshPosition;
  83735. if (this.useCustomMeshPosition) {
  83736. meshPosition = this.customMeshPosition;
  83737. }
  83738. else if (this.attachedNode) {
  83739. meshPosition = this.attachedNode.position;
  83740. }
  83741. else {
  83742. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  83743. }
  83744. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  83745. this._screenCoordinates.x = pos.x / this._viewPort.width;
  83746. this._screenCoordinates.y = pos.y / this._viewPort.height;
  83747. if (this.invert)
  83748. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  83749. };
  83750. // Static methods
  83751. /**
  83752. * Creates a default mesh for the Volumeric Light Scattering post-process
  83753. * @param {string} The mesh name
  83754. * @param {BABYLON.Scene} The scene where to create the mesh
  83755. * @return {BABYLON.Mesh} the default mesh
  83756. */
  83757. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  83758. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  83759. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  83760. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  83761. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  83762. mesh.material = material;
  83763. return mesh;
  83764. };
  83765. __decorate([
  83766. BABYLON.serializeAsVector3()
  83767. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  83768. __decorate([
  83769. BABYLON.serialize()
  83770. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  83771. __decorate([
  83772. BABYLON.serialize()
  83773. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  83774. __decorate([
  83775. BABYLON.serializeAsMeshReference()
  83776. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  83777. __decorate([
  83778. BABYLON.serialize()
  83779. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  83780. __decorate([
  83781. BABYLON.serialize()
  83782. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  83783. __decorate([
  83784. BABYLON.serialize()
  83785. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  83786. __decorate([
  83787. BABYLON.serialize()
  83788. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  83789. __decorate([
  83790. BABYLON.serialize()
  83791. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  83792. return VolumetricLightScatteringPostProcess;
  83793. }(BABYLON.PostProcess));
  83794. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  83795. })(BABYLON || (BABYLON = {}));
  83796. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  83797. //
  83798. // This post-process allows the modification of rendered colors by using
  83799. // a 'look-up table' (LUT). This effect is also called Color Grading.
  83800. //
  83801. // The object needs to be provided an url to a texture containing the color
  83802. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  83803. // Use an image editing software to tweak the LUT to match your needs.
  83804. //
  83805. // For an example of a color LUT, see here:
  83806. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  83807. // For explanations on color grading, see here:
  83808. // http://udn.epicgames.com/Three/ColorGrading.html
  83809. //
  83810. var BABYLON;
  83811. (function (BABYLON) {
  83812. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  83813. __extends(ColorCorrectionPostProcess, _super);
  83814. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  83815. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  83816. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83817. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  83818. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83819. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83820. _this.onApply = function (effect) {
  83821. effect.setTexture("colorTable", _this._colorTableTexture);
  83822. };
  83823. return _this;
  83824. }
  83825. return ColorCorrectionPostProcess;
  83826. }(BABYLON.PostProcess));
  83827. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  83828. })(BABYLON || (BABYLON = {}));
  83829. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  83830. var BABYLON;
  83831. (function (BABYLON) {
  83832. /** Defines operator used for tonemapping */
  83833. var TonemappingOperator;
  83834. (function (TonemappingOperator) {
  83835. /** Hable */
  83836. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  83837. /** Reinhard */
  83838. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  83839. /** HejiDawson */
  83840. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  83841. /** Photographic */
  83842. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  83843. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  83844. ;
  83845. /**
  83846. * Defines a post process to apply tone mapping
  83847. */
  83848. var TonemapPostProcess = /** @class */ (function (_super) {
  83849. __extends(TonemapPostProcess, _super);
  83850. /**
  83851. * Creates a new TonemapPostProcess
  83852. * @param name defines the name of the postprocess
  83853. * @param _operator defines the operator to use
  83854. * @param exposureAdjustment defines the required exposure adjustement
  83855. * @param camera defines the camera to use (can be null)
  83856. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  83857. * @param engine defines the hosting engine (can be ignore if camera is set)
  83858. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  83859. */
  83860. function TonemapPostProcess(name, _operator,
  83861. /** Defines the required exposure adjustement */
  83862. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  83863. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83864. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83865. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  83866. _this._operator = _operator;
  83867. _this.exposureAdjustment = exposureAdjustment;
  83868. var defines = "#define ";
  83869. if (_this._operator === TonemappingOperator.Hable)
  83870. defines += "HABLE_TONEMAPPING";
  83871. else if (_this._operator === TonemappingOperator.Reinhard)
  83872. defines += "REINHARD_TONEMAPPING";
  83873. else if (_this._operator === TonemappingOperator.HejiDawson)
  83874. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  83875. else if (_this._operator === TonemappingOperator.Photographic)
  83876. defines += "PHOTOGRAPHIC_TONEMAPPING";
  83877. //sadly a second call to create the effect.
  83878. _this.updateEffect(defines);
  83879. _this.onApply = function (effect) {
  83880. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  83881. };
  83882. return _this;
  83883. }
  83884. return TonemapPostProcess;
  83885. }(BABYLON.PostProcess));
  83886. BABYLON.TonemapPostProcess = TonemapPostProcess;
  83887. })(BABYLON || (BABYLON = {}));
  83888. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  83889. var BABYLON;
  83890. (function (BABYLON) {
  83891. var DisplayPassPostProcess = /** @class */ (function (_super) {
  83892. __extends(DisplayPassPostProcess, _super);
  83893. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  83894. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  83895. }
  83896. return DisplayPassPostProcess;
  83897. }(BABYLON.PostProcess));
  83898. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  83899. })(BABYLON || (BABYLON = {}));
  83900. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  83901. var BABYLON;
  83902. (function (BABYLON) {
  83903. var HighlightsPostProcess = /** @class */ (function (_super) {
  83904. __extends(HighlightsPostProcess, _super);
  83905. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  83906. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83907. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  83908. }
  83909. return HighlightsPostProcess;
  83910. }(BABYLON.PostProcess));
  83911. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  83912. })(BABYLON || (BABYLON = {}));
  83913. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  83914. var BABYLON;
  83915. (function (BABYLON) {
  83916. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  83917. __extends(ImageProcessingPostProcess, _super);
  83918. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  83919. if (camera === void 0) { camera = null; }
  83920. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83921. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  83922. _this._fromLinearSpace = true;
  83923. /**
  83924. * Defines cache preventing GC.
  83925. */
  83926. _this._defines = {
  83927. IMAGEPROCESSING: false,
  83928. VIGNETTE: false,
  83929. VIGNETTEBLENDMODEMULTIPLY: false,
  83930. VIGNETTEBLENDMODEOPAQUE: false,
  83931. TONEMAPPING: false,
  83932. TONEMAPPING_ACES: false,
  83933. CONTRAST: false,
  83934. COLORCURVES: false,
  83935. COLORGRADING: false,
  83936. COLORGRADING3D: false,
  83937. FROMLINEARSPACE: false,
  83938. SAMPLER3DGREENDEPTH: false,
  83939. SAMPLER3DBGRMAP: false,
  83940. IMAGEPROCESSINGPOSTPROCESS: false,
  83941. EXPOSURE: false,
  83942. };
  83943. // Setup the configuration as forced by the constructor. This would then not force the
  83944. // scene materials output in linear space and let untouched the default forward pass.
  83945. if (imageProcessingConfiguration) {
  83946. imageProcessingConfiguration.applyByPostProcess = true;
  83947. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  83948. // This will cause the shader to be compiled
  83949. _this.fromLinearSpace = false;
  83950. }
  83951. // Setup the default processing configuration to the scene.
  83952. else {
  83953. _this._attachImageProcessingConfiguration(null, true);
  83954. _this.imageProcessingConfiguration.applyByPostProcess = true;
  83955. }
  83956. _this.onApply = function (effect) {
  83957. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  83958. };
  83959. return _this;
  83960. }
  83961. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  83962. /**
  83963. * Gets the image processing configuration used either in this material.
  83964. */
  83965. get: function () {
  83966. return this._imageProcessingConfiguration;
  83967. },
  83968. /**
  83969. * Sets the Default image processing configuration used either in the this material.
  83970. *
  83971. * If sets to null, the scene one is in use.
  83972. */
  83973. set: function (value) {
  83974. this._attachImageProcessingConfiguration(value);
  83975. },
  83976. enumerable: true,
  83977. configurable: true
  83978. });
  83979. /**
  83980. * Attaches a new image processing configuration to the PBR Material.
  83981. * @param configuration
  83982. */
  83983. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  83984. var _this = this;
  83985. if (doNotBuild === void 0) { doNotBuild = false; }
  83986. if (configuration === this._imageProcessingConfiguration) {
  83987. return;
  83988. }
  83989. // Detaches observer.
  83990. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83991. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83992. }
  83993. // Pick the scene configuration if needed.
  83994. if (!configuration) {
  83995. var scene = null;
  83996. var engine = this.getEngine();
  83997. var camera = this.getCamera();
  83998. if (camera) {
  83999. scene = camera.getScene();
  84000. }
  84001. else if (engine && engine.scenes) {
  84002. var scenes = engine.scenes;
  84003. scene = scenes[scenes.length - 1];
  84004. }
  84005. else {
  84006. scene = BABYLON.Engine.LastCreatedScene;
  84007. }
  84008. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  84009. }
  84010. else {
  84011. this._imageProcessingConfiguration = configuration;
  84012. }
  84013. // Attaches observer.
  84014. if (this._imageProcessingConfiguration) {
  84015. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  84016. _this._updateParameters();
  84017. });
  84018. }
  84019. // Ensure the effect will be rebuilt.
  84020. if (!doNotBuild) {
  84021. this._updateParameters();
  84022. }
  84023. };
  84024. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  84025. /**
  84026. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  84027. */
  84028. get: function () {
  84029. return this.imageProcessingConfiguration.colorCurves;
  84030. },
  84031. /**
  84032. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  84033. */
  84034. set: function (value) {
  84035. this.imageProcessingConfiguration.colorCurves = value;
  84036. },
  84037. enumerable: true,
  84038. configurable: true
  84039. });
  84040. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  84041. /**
  84042. * Gets wether the color curves effect is enabled.
  84043. */
  84044. get: function () {
  84045. return this.imageProcessingConfiguration.colorCurvesEnabled;
  84046. },
  84047. /**
  84048. * Sets wether the color curves effect is enabled.
  84049. */
  84050. set: function (value) {
  84051. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  84052. },
  84053. enumerable: true,
  84054. configurable: true
  84055. });
  84056. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  84057. /**
  84058. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  84059. */
  84060. get: function () {
  84061. return this.imageProcessingConfiguration.colorGradingTexture;
  84062. },
  84063. /**
  84064. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  84065. */
  84066. set: function (value) {
  84067. this.imageProcessingConfiguration.colorGradingTexture = value;
  84068. },
  84069. enumerable: true,
  84070. configurable: true
  84071. });
  84072. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  84073. /**
  84074. * Gets wether the color grading effect is enabled.
  84075. */
  84076. get: function () {
  84077. return this.imageProcessingConfiguration.colorGradingEnabled;
  84078. },
  84079. /**
  84080. * Gets wether the color grading effect is enabled.
  84081. */
  84082. set: function (value) {
  84083. this.imageProcessingConfiguration.colorGradingEnabled = value;
  84084. },
  84085. enumerable: true,
  84086. configurable: true
  84087. });
  84088. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  84089. /**
  84090. * Gets exposure used in the effect.
  84091. */
  84092. get: function () {
  84093. return this.imageProcessingConfiguration.exposure;
  84094. },
  84095. /**
  84096. * Sets exposure used in the effect.
  84097. */
  84098. set: function (value) {
  84099. this.imageProcessingConfiguration.exposure = value;
  84100. },
  84101. enumerable: true,
  84102. configurable: true
  84103. });
  84104. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  84105. /**
  84106. * Gets wether tonemapping is enabled or not.
  84107. */
  84108. get: function () {
  84109. return this._imageProcessingConfiguration.toneMappingEnabled;
  84110. },
  84111. /**
  84112. * Sets wether tonemapping is enabled or not
  84113. */
  84114. set: function (value) {
  84115. this._imageProcessingConfiguration.toneMappingEnabled = value;
  84116. },
  84117. enumerable: true,
  84118. configurable: true
  84119. });
  84120. ;
  84121. ;
  84122. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  84123. /**
  84124. * Gets contrast used in the effect.
  84125. */
  84126. get: function () {
  84127. return this.imageProcessingConfiguration.contrast;
  84128. },
  84129. /**
  84130. * Sets contrast used in the effect.
  84131. */
  84132. set: function (value) {
  84133. this.imageProcessingConfiguration.contrast = value;
  84134. },
  84135. enumerable: true,
  84136. configurable: true
  84137. });
  84138. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  84139. /**
  84140. * Gets Vignette stretch size.
  84141. */
  84142. get: function () {
  84143. return this.imageProcessingConfiguration.vignetteStretch;
  84144. },
  84145. /**
  84146. * Sets Vignette stretch size.
  84147. */
  84148. set: function (value) {
  84149. this.imageProcessingConfiguration.vignetteStretch = value;
  84150. },
  84151. enumerable: true,
  84152. configurable: true
  84153. });
  84154. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  84155. /**
  84156. * Gets Vignette centre X Offset.
  84157. */
  84158. get: function () {
  84159. return this.imageProcessingConfiguration.vignetteCentreX;
  84160. },
  84161. /**
  84162. * Sets Vignette centre X Offset.
  84163. */
  84164. set: function (value) {
  84165. this.imageProcessingConfiguration.vignetteCentreX = value;
  84166. },
  84167. enumerable: true,
  84168. configurable: true
  84169. });
  84170. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  84171. /**
  84172. * Gets Vignette centre Y Offset.
  84173. */
  84174. get: function () {
  84175. return this.imageProcessingConfiguration.vignetteCentreY;
  84176. },
  84177. /**
  84178. * Sets Vignette centre Y Offset.
  84179. */
  84180. set: function (value) {
  84181. this.imageProcessingConfiguration.vignetteCentreY = value;
  84182. },
  84183. enumerable: true,
  84184. configurable: true
  84185. });
  84186. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  84187. /**
  84188. * Gets Vignette weight or intensity of the vignette effect.
  84189. */
  84190. get: function () {
  84191. return this.imageProcessingConfiguration.vignetteWeight;
  84192. },
  84193. /**
  84194. * Sets Vignette weight or intensity of the vignette effect.
  84195. */
  84196. set: function (value) {
  84197. this.imageProcessingConfiguration.vignetteWeight = value;
  84198. },
  84199. enumerable: true,
  84200. configurable: true
  84201. });
  84202. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  84203. /**
  84204. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  84205. * if vignetteEnabled is set to true.
  84206. */
  84207. get: function () {
  84208. return this.imageProcessingConfiguration.vignetteColor;
  84209. },
  84210. /**
  84211. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  84212. * if vignetteEnabled is set to true.
  84213. */
  84214. set: function (value) {
  84215. this.imageProcessingConfiguration.vignetteColor = value;
  84216. },
  84217. enumerable: true,
  84218. configurable: true
  84219. });
  84220. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  84221. /**
  84222. * Gets Camera field of view used by the Vignette effect.
  84223. */
  84224. get: function () {
  84225. return this.imageProcessingConfiguration.vignetteCameraFov;
  84226. },
  84227. /**
  84228. * Sets Camera field of view used by the Vignette effect.
  84229. */
  84230. set: function (value) {
  84231. this.imageProcessingConfiguration.vignetteCameraFov = value;
  84232. },
  84233. enumerable: true,
  84234. configurable: true
  84235. });
  84236. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  84237. /**
  84238. * Gets the vignette blend mode allowing different kind of effect.
  84239. */
  84240. get: function () {
  84241. return this.imageProcessingConfiguration.vignetteBlendMode;
  84242. },
  84243. /**
  84244. * Sets the vignette blend mode allowing different kind of effect.
  84245. */
  84246. set: function (value) {
  84247. this.imageProcessingConfiguration.vignetteBlendMode = value;
  84248. },
  84249. enumerable: true,
  84250. configurable: true
  84251. });
  84252. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  84253. /**
  84254. * Gets wether the vignette effect is enabled.
  84255. */
  84256. get: function () {
  84257. return this.imageProcessingConfiguration.vignetteEnabled;
  84258. },
  84259. /**
  84260. * Sets wether the vignette effect is enabled.
  84261. */
  84262. set: function (value) {
  84263. this.imageProcessingConfiguration.vignetteEnabled = value;
  84264. },
  84265. enumerable: true,
  84266. configurable: true
  84267. });
  84268. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  84269. /**
  84270. * Gets wether the input of the processing is in Gamma or Linear Space.
  84271. */
  84272. get: function () {
  84273. return this._fromLinearSpace;
  84274. },
  84275. /**
  84276. * Sets wether the input of the processing is in Gamma or Linear Space.
  84277. */
  84278. set: function (value) {
  84279. if (this._fromLinearSpace === value) {
  84280. return;
  84281. }
  84282. this._fromLinearSpace = value;
  84283. this._updateParameters();
  84284. },
  84285. enumerable: true,
  84286. configurable: true
  84287. });
  84288. ImageProcessingPostProcess.prototype.getClassName = function () {
  84289. return "ImageProcessingPostProcess";
  84290. };
  84291. ImageProcessingPostProcess.prototype._updateParameters = function () {
  84292. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  84293. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  84294. var defines = "";
  84295. for (var define in this._defines) {
  84296. if (this._defines[define]) {
  84297. defines += "#define " + define + ";\r\n";
  84298. }
  84299. }
  84300. var samplers = ["textureSampler"];
  84301. var uniforms = ["scale"];
  84302. if (BABYLON.ImageProcessingConfiguration) {
  84303. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  84304. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  84305. }
  84306. this.updateEffect(defines, uniforms, samplers);
  84307. };
  84308. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  84309. _super.prototype.dispose.call(this, camera);
  84310. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84311. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84312. }
  84313. if (this._imageProcessingConfiguration) {
  84314. this.imageProcessingConfiguration.applyByPostProcess = false;
  84315. }
  84316. };
  84317. __decorate([
  84318. BABYLON.serialize()
  84319. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  84320. return ImageProcessingPostProcess;
  84321. }(BABYLON.PostProcess));
  84322. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  84323. })(BABYLON || (BABYLON = {}));
  84324. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  84325. var BABYLON;
  84326. (function (BABYLON) {
  84327. /**
  84328. * Class used to store bone information
  84329. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  84330. */
  84331. var Bone = /** @class */ (function (_super) {
  84332. __extends(Bone, _super);
  84333. /**
  84334. * Create a new bone
  84335. * @param name defines the bone name
  84336. * @param skeleton defines the parent skeleton
  84337. * @param parentBone defines the parent (can be null if the bone is the root)
  84338. * @param localMatrix defines the local matrix
  84339. * @param restPose defines the rest pose matrix
  84340. * @param baseMatrix defines the base matrix
  84341. * @param index defines index of the bone in the hiearchy
  84342. */
  84343. function Bone(
  84344. /**
  84345. * defines the bone name
  84346. */
  84347. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  84348. if (parentBone === void 0) { parentBone = null; }
  84349. if (localMatrix === void 0) { localMatrix = null; }
  84350. if (restPose === void 0) { restPose = null; }
  84351. if (baseMatrix === void 0) { baseMatrix = null; }
  84352. if (index === void 0) { index = null; }
  84353. var _this = _super.call(this, name, skeleton.getScene()) || this;
  84354. _this.name = name;
  84355. /**
  84356. * Gets the list of child bones
  84357. */
  84358. _this.children = new Array();
  84359. /** Gets the animations associated with this bone */
  84360. _this.animations = new Array();
  84361. /**
  84362. * @hidden Internal only
  84363. * Set this value to map this bone to a different index in the transform matrices
  84364. * Set this value to -1 to exclude the bone from the transform matrices
  84365. */
  84366. _this._index = null;
  84367. _this._absoluteTransform = new BABYLON.Matrix();
  84368. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  84369. _this._scalingDeterminant = 1;
  84370. _this._worldTransform = new BABYLON.Matrix();
  84371. _this._needToDecompose = true;
  84372. _this._needToCompose = false;
  84373. _this._skeleton = skeleton;
  84374. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  84375. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  84376. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  84377. _this._index = index;
  84378. skeleton.bones.push(_this);
  84379. _this.setParent(parentBone, false);
  84380. if (baseMatrix || localMatrix) {
  84381. _this._updateDifferenceMatrix();
  84382. }
  84383. return _this;
  84384. }
  84385. Object.defineProperty(Bone.prototype, "_matrix", {
  84386. /** @hidden */
  84387. get: function () {
  84388. this._compose();
  84389. return this._localMatrix;
  84390. },
  84391. /** @hidden */
  84392. set: function (value) {
  84393. this._localMatrix.copyFrom(value);
  84394. this._needToDecompose = true;
  84395. },
  84396. enumerable: true,
  84397. configurable: true
  84398. });
  84399. // Members
  84400. /**
  84401. * Gets the parent skeleton
  84402. * @returns a skeleton
  84403. */
  84404. Bone.prototype.getSkeleton = function () {
  84405. return this._skeleton;
  84406. };
  84407. /**
  84408. * Gets parent bone
  84409. * @returns a bone or null if the bone is the root of the bone hierarchy
  84410. */
  84411. Bone.prototype.getParent = function () {
  84412. return this._parent;
  84413. };
  84414. /**
  84415. * Sets the parent bone
  84416. * @param parent defines the parent (can be null if the bone is the root)
  84417. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  84418. */
  84419. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  84420. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  84421. if (this._parent === parent) {
  84422. return;
  84423. }
  84424. if (this._parent) {
  84425. var index = this._parent.children.indexOf(this);
  84426. if (index !== -1) {
  84427. this._parent.children.splice(index, 1);
  84428. }
  84429. }
  84430. this._parent = parent;
  84431. if (this._parent) {
  84432. this._parent.children.push(this);
  84433. }
  84434. if (updateDifferenceMatrix) {
  84435. this._updateDifferenceMatrix();
  84436. }
  84437. this.markAsDirty();
  84438. };
  84439. /**
  84440. * Gets the local matrix
  84441. * @returns a matrix
  84442. */
  84443. Bone.prototype.getLocalMatrix = function () {
  84444. this._compose();
  84445. return this._localMatrix;
  84446. };
  84447. /**
  84448. * Gets the base matrix (initial matrix which remains unchanged)
  84449. * @returns a matrix
  84450. */
  84451. Bone.prototype.getBaseMatrix = function () {
  84452. return this._baseMatrix;
  84453. };
  84454. /**
  84455. * Gets the rest pose matrix
  84456. * @returns a matrix
  84457. */
  84458. Bone.prototype.getRestPose = function () {
  84459. return this._restPose;
  84460. };
  84461. /**
  84462. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  84463. */
  84464. Bone.prototype.getWorldMatrix = function () {
  84465. return this._worldTransform;
  84466. };
  84467. /**
  84468. * Sets the local matrix to rest pose matrix
  84469. */
  84470. Bone.prototype.returnToRest = function () {
  84471. this.updateMatrix(this._restPose.clone());
  84472. };
  84473. /**
  84474. * Gets the inverse of the absolute transform matrix.
  84475. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  84476. * @returns a matrix
  84477. */
  84478. Bone.prototype.getInvertedAbsoluteTransform = function () {
  84479. return this._invertedAbsoluteTransform;
  84480. };
  84481. /**
  84482. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  84483. * @returns a matrix
  84484. */
  84485. Bone.prototype.getAbsoluteTransform = function () {
  84486. return this._absoluteTransform;
  84487. };
  84488. Object.defineProperty(Bone.prototype, "position", {
  84489. // Properties (matches AbstractMesh properties)
  84490. /** Gets or sets current position (in local space) */
  84491. get: function () {
  84492. this._decompose();
  84493. return this._localPosition;
  84494. },
  84495. set: function (newPosition) {
  84496. this._decompose();
  84497. this._localPosition.copyFrom(newPosition);
  84498. this._markAsDirtyAndCompose();
  84499. },
  84500. enumerable: true,
  84501. configurable: true
  84502. });
  84503. Object.defineProperty(Bone.prototype, "rotation", {
  84504. /** Gets or sets current rotation (in local space) */
  84505. get: function () {
  84506. return this.getRotation();
  84507. },
  84508. set: function (newRotation) {
  84509. this.setRotation(newRotation);
  84510. },
  84511. enumerable: true,
  84512. configurable: true
  84513. });
  84514. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  84515. /** Gets or sets current rotation quaternion (in local space) */
  84516. get: function () {
  84517. this._decompose();
  84518. return this._localRotation;
  84519. },
  84520. set: function (newRotation) {
  84521. this.setRotationQuaternion(newRotation);
  84522. },
  84523. enumerable: true,
  84524. configurable: true
  84525. });
  84526. Object.defineProperty(Bone.prototype, "scaling", {
  84527. /** Gets or sets current scaling (in local space) */
  84528. get: function () {
  84529. return this.getScale();
  84530. },
  84531. set: function (newScaling) {
  84532. this.setScale(newScaling);
  84533. },
  84534. enumerable: true,
  84535. configurable: true
  84536. });
  84537. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  84538. /**
  84539. * Gets the animation properties override
  84540. */
  84541. get: function () {
  84542. return this._skeleton.animationPropertiesOverride;
  84543. },
  84544. enumerable: true,
  84545. configurable: true
  84546. });
  84547. // Methods
  84548. Bone.prototype._decompose = function () {
  84549. if (!this._needToDecompose) {
  84550. return;
  84551. }
  84552. this._needToDecompose = false;
  84553. if (!this._localScaling) {
  84554. this._localScaling = BABYLON.Vector3.Zero();
  84555. this._localRotation = BABYLON.Quaternion.Zero();
  84556. this._localPosition = BABYLON.Vector3.Zero();
  84557. }
  84558. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  84559. };
  84560. Bone.prototype._compose = function () {
  84561. if (!this._needToCompose) {
  84562. return;
  84563. }
  84564. this._needToCompose = false;
  84565. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  84566. };
  84567. /**
  84568. * Update the base and local matrices
  84569. * @param matrix defines the new base or local matrix
  84570. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  84571. * @param updateLocalMatrix defines if the local matrix should be updated
  84572. */
  84573. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  84574. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  84575. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  84576. this._baseMatrix.copyFrom(matrix);
  84577. if (updateDifferenceMatrix) {
  84578. this._updateDifferenceMatrix();
  84579. }
  84580. if (updateLocalMatrix) {
  84581. this._localMatrix.copyFrom(matrix);
  84582. this._markAsDirtyAndDecompose();
  84583. }
  84584. else {
  84585. this.markAsDirty();
  84586. }
  84587. };
  84588. /** @hidden */
  84589. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  84590. if (updateChildren === void 0) { updateChildren = true; }
  84591. if (!rootMatrix) {
  84592. rootMatrix = this._baseMatrix;
  84593. }
  84594. if (this._parent) {
  84595. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  84596. }
  84597. else {
  84598. this._absoluteTransform.copyFrom(rootMatrix);
  84599. }
  84600. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  84601. if (updateChildren) {
  84602. for (var index = 0; index < this.children.length; index++) {
  84603. this.children[index]._updateDifferenceMatrix();
  84604. }
  84605. }
  84606. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  84607. };
  84608. /**
  84609. * Flag the bone as dirty (Forcing it to update everything)
  84610. */
  84611. Bone.prototype.markAsDirty = function () {
  84612. this._currentRenderId++;
  84613. this._childRenderId++;
  84614. this._skeleton._markAsDirty();
  84615. };
  84616. Bone.prototype._markAsDirtyAndCompose = function () {
  84617. this.markAsDirty();
  84618. this._needToCompose = true;
  84619. };
  84620. Bone.prototype._markAsDirtyAndDecompose = function () {
  84621. this.markAsDirty();
  84622. this._needToDecompose = true;
  84623. };
  84624. /**
  84625. * Copy an animation range from another bone
  84626. * @param source defines the source bone
  84627. * @param rangeName defines the range name to copy
  84628. * @param frameOffset defines the frame offset
  84629. * @param rescaleAsRequired defines if rescaling must be applied if required
  84630. * @param skelDimensionsRatio defines the scaling ratio
  84631. * @returns true if operation was successful
  84632. */
  84633. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  84634. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  84635. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  84636. // all animation may be coming from a library skeleton, so may need to create animation
  84637. if (this.animations.length === 0) {
  84638. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  84639. this.animations[0].setKeys([]);
  84640. }
  84641. // get animation info / verify there is such a range from the source bone
  84642. var sourceRange = source.animations[0].getRange(rangeName);
  84643. if (!sourceRange) {
  84644. return false;
  84645. }
  84646. var from = sourceRange.from;
  84647. var to = sourceRange.to;
  84648. var sourceKeys = source.animations[0].getKeys();
  84649. // rescaling prep
  84650. var sourceBoneLength = source.length;
  84651. var sourceParent = source.getParent();
  84652. var parent = this.getParent();
  84653. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  84654. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  84655. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  84656. var destKeys = this.animations[0].getKeys();
  84657. // loop vars declaration
  84658. var orig;
  84659. var origTranslation;
  84660. var mat;
  84661. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  84662. orig = sourceKeys[key];
  84663. if (orig.frame >= from && orig.frame <= to) {
  84664. if (rescaleAsRequired) {
  84665. mat = orig.value.clone();
  84666. // scale based on parent ratio, when bone has parent
  84667. if (parentScalingReqd) {
  84668. origTranslation = mat.getTranslation();
  84669. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  84670. // scale based on skeleton dimension ratio when root bone, and value is passed
  84671. }
  84672. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  84673. origTranslation = mat.getTranslation();
  84674. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  84675. // use original when root bone, and no data for skelDimensionsRatio
  84676. }
  84677. else {
  84678. mat = orig.value;
  84679. }
  84680. }
  84681. else {
  84682. mat = orig.value;
  84683. }
  84684. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  84685. }
  84686. }
  84687. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  84688. return true;
  84689. };
  84690. /**
  84691. * Translate the bone in local or world space
  84692. * @param vec The amount to translate the bone
  84693. * @param space The space that the translation is in
  84694. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84695. */
  84696. Bone.prototype.translate = function (vec, space, mesh) {
  84697. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84698. var lm = this.getLocalMatrix();
  84699. if (space == BABYLON.Space.LOCAL) {
  84700. lm.m[12] += vec.x;
  84701. lm.m[13] += vec.y;
  84702. lm.m[14] += vec.z;
  84703. }
  84704. else {
  84705. var wm = null;
  84706. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84707. if (mesh) {
  84708. wm = mesh.getWorldMatrix();
  84709. }
  84710. this._skeleton.computeAbsoluteTransforms();
  84711. var tmat = Bone._tmpMats[0];
  84712. var tvec = Bone._tmpVecs[0];
  84713. if (this._parent) {
  84714. if (mesh && wm) {
  84715. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84716. tmat.multiplyToRef(wm, tmat);
  84717. }
  84718. else {
  84719. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84720. }
  84721. }
  84722. tmat.m[12] = 0;
  84723. tmat.m[13] = 0;
  84724. tmat.m[14] = 0;
  84725. tmat.invert();
  84726. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  84727. lm.m[12] += tvec.x;
  84728. lm.m[13] += tvec.y;
  84729. lm.m[14] += tvec.z;
  84730. }
  84731. this._markAsDirtyAndDecompose();
  84732. };
  84733. /**
  84734. * Set the postion of the bone in local or world space
  84735. * @param position The position to set the bone
  84736. * @param space The space that the position is in
  84737. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84738. */
  84739. Bone.prototype.setPosition = function (position, space, mesh) {
  84740. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84741. var lm = this.getLocalMatrix();
  84742. if (space == BABYLON.Space.LOCAL) {
  84743. lm.m[12] = position.x;
  84744. lm.m[13] = position.y;
  84745. lm.m[14] = position.z;
  84746. }
  84747. else {
  84748. var wm = null;
  84749. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84750. if (mesh) {
  84751. wm = mesh.getWorldMatrix();
  84752. }
  84753. this._skeleton.computeAbsoluteTransforms();
  84754. var tmat = Bone._tmpMats[0];
  84755. var vec = Bone._tmpVecs[0];
  84756. if (this._parent) {
  84757. if (mesh && wm) {
  84758. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84759. tmat.multiplyToRef(wm, tmat);
  84760. }
  84761. else {
  84762. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84763. }
  84764. }
  84765. tmat.invert();
  84766. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  84767. lm.m[12] = vec.x;
  84768. lm.m[13] = vec.y;
  84769. lm.m[14] = vec.z;
  84770. }
  84771. this._markAsDirtyAndDecompose();
  84772. };
  84773. /**
  84774. * Set the absolute position of the bone (world space)
  84775. * @param position The position to set the bone
  84776. * @param mesh The mesh that this bone is attached to
  84777. */
  84778. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  84779. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  84780. };
  84781. /**
  84782. * Scale the bone on the x, y and z axes (in local space)
  84783. * @param x The amount to scale the bone on the x axis
  84784. * @param y The amount to scale the bone on the y axis
  84785. * @param z The amount to scale the bone on the z axis
  84786. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  84787. */
  84788. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  84789. if (scaleChildren === void 0) { scaleChildren = false; }
  84790. var locMat = this.getLocalMatrix();
  84791. // Apply new scaling on top of current local matrix
  84792. var scaleMat = Bone._tmpMats[0];
  84793. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  84794. scaleMat.multiplyToRef(locMat, locMat);
  84795. // Invert scaling matrix and apply the inverse to all children
  84796. scaleMat.invert();
  84797. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  84798. var child = _a[_i];
  84799. var cm = child.getLocalMatrix();
  84800. cm.multiplyToRef(scaleMat, cm);
  84801. cm.m[12] *= x;
  84802. cm.m[13] *= y;
  84803. cm.m[14] *= z;
  84804. child._markAsDirtyAndDecompose();
  84805. }
  84806. this._markAsDirtyAndDecompose();
  84807. if (scaleChildren) {
  84808. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  84809. var child = _c[_b];
  84810. child.scale(x, y, z, scaleChildren);
  84811. }
  84812. }
  84813. };
  84814. /**
  84815. * Set the bone scaling in local space
  84816. * @param scale defines the scaling vector
  84817. */
  84818. Bone.prototype.setScale = function (scale) {
  84819. this._decompose();
  84820. this._localScaling.copyFrom(scale);
  84821. this._markAsDirtyAndCompose();
  84822. };
  84823. /**
  84824. * Gets the current scaling in local space
  84825. * @returns the current scaling vector
  84826. */
  84827. Bone.prototype.getScale = function () {
  84828. this._decompose();
  84829. return this._localScaling;
  84830. };
  84831. /**
  84832. * Gets the current scaling in local space and stores it in a target vector
  84833. * @param result defines the target vector
  84834. */
  84835. Bone.prototype.getScaleToRef = function (result) {
  84836. this._decompose();
  84837. result.copyFrom(this._localScaling);
  84838. };
  84839. /**
  84840. * Set the yaw, pitch, and roll of the bone in local or world space
  84841. * @param yaw The rotation of the bone on the y axis
  84842. * @param pitch The rotation of the bone on the x axis
  84843. * @param roll The rotation of the bone on the z axis
  84844. * @param space The space that the axes of rotation are in
  84845. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84846. */
  84847. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  84848. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84849. if (space === BABYLON.Space.LOCAL) {
  84850. var quat = Bone._tmpQuat;
  84851. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  84852. this.setRotationQuaternion(quat, space, mesh);
  84853. return;
  84854. }
  84855. var rotMatInv = Bone._tmpMats[0];
  84856. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84857. return;
  84858. }
  84859. var rotMat = Bone._tmpMats[1];
  84860. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  84861. rotMatInv.multiplyToRef(rotMat, rotMat);
  84862. this._rotateWithMatrix(rotMat, space, mesh);
  84863. };
  84864. /**
  84865. * Add a rotation to the bone on an axis in local or world space
  84866. * @param axis The axis to rotate the bone on
  84867. * @param amount The amount to rotate the bone
  84868. * @param space The space that the axis is in
  84869. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84870. */
  84871. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  84872. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84873. var rmat = Bone._tmpMats[0];
  84874. rmat.m[12] = 0;
  84875. rmat.m[13] = 0;
  84876. rmat.m[14] = 0;
  84877. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  84878. this._rotateWithMatrix(rmat, space, mesh);
  84879. };
  84880. /**
  84881. * Set the rotation of the bone to a particular axis angle in local or world space
  84882. * @param axis The axis to rotate the bone on
  84883. * @param angle The angle that the bone should be rotated to
  84884. * @param space The space that the axis is in
  84885. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84886. */
  84887. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  84888. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84889. if (space === BABYLON.Space.LOCAL) {
  84890. var quat = Bone._tmpQuat;
  84891. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  84892. this.setRotationQuaternion(quat, space, mesh);
  84893. return;
  84894. }
  84895. var rotMatInv = Bone._tmpMats[0];
  84896. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84897. return;
  84898. }
  84899. var rotMat = Bone._tmpMats[1];
  84900. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  84901. rotMatInv.multiplyToRef(rotMat, rotMat);
  84902. this._rotateWithMatrix(rotMat, space, mesh);
  84903. };
  84904. /**
  84905. * Set the euler rotation of the bone in local of world space
  84906. * @param rotation The euler rotation that the bone should be set to
  84907. * @param space The space that the rotation is in
  84908. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84909. */
  84910. Bone.prototype.setRotation = function (rotation, space, mesh) {
  84911. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84912. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  84913. };
  84914. /**
  84915. * Set the quaternion rotation of the bone in local of world space
  84916. * @param quat The quaternion rotation that the bone should be set to
  84917. * @param space The space that the rotation is in
  84918. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84919. */
  84920. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  84921. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84922. if (space === BABYLON.Space.LOCAL) {
  84923. this._decompose();
  84924. this._localRotation.copyFrom(quat);
  84925. this._markAsDirtyAndCompose();
  84926. return;
  84927. }
  84928. var rotMatInv = Bone._tmpMats[0];
  84929. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84930. return;
  84931. }
  84932. var rotMat = Bone._tmpMats[1];
  84933. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  84934. rotMatInv.multiplyToRef(rotMat, rotMat);
  84935. this._rotateWithMatrix(rotMat, space, mesh);
  84936. };
  84937. /**
  84938. * Set the rotation matrix of the bone in local of world space
  84939. * @param rotMat The rotation matrix that the bone should be set to
  84940. * @param space The space that the rotation is in
  84941. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84942. */
  84943. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  84944. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84945. if (space === BABYLON.Space.LOCAL) {
  84946. var quat = Bone._tmpQuat;
  84947. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  84948. this.setRotationQuaternion(quat, space, mesh);
  84949. return;
  84950. }
  84951. var rotMatInv = Bone._tmpMats[0];
  84952. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84953. return;
  84954. }
  84955. var rotMat2 = Bone._tmpMats[1];
  84956. rotMat2.copyFrom(rotMat);
  84957. rotMatInv.multiplyToRef(rotMat, rotMat2);
  84958. this._rotateWithMatrix(rotMat2, space, mesh);
  84959. };
  84960. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  84961. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84962. var lmat = this.getLocalMatrix();
  84963. var lx = lmat.m[12];
  84964. var ly = lmat.m[13];
  84965. var lz = lmat.m[14];
  84966. var parent = this.getParent();
  84967. var parentScale = Bone._tmpMats[3];
  84968. var parentScaleInv = Bone._tmpMats[4];
  84969. if (parent && space == BABYLON.Space.WORLD) {
  84970. if (mesh) {
  84971. parentScale.copyFrom(mesh.getWorldMatrix());
  84972. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  84973. }
  84974. else {
  84975. parentScale.copyFrom(parent.getAbsoluteTransform());
  84976. }
  84977. parentScaleInv.copyFrom(parentScale);
  84978. parentScaleInv.invert();
  84979. lmat.multiplyToRef(parentScale, lmat);
  84980. lmat.multiplyToRef(rmat, lmat);
  84981. lmat.multiplyToRef(parentScaleInv, lmat);
  84982. }
  84983. else {
  84984. if (space == BABYLON.Space.WORLD && mesh) {
  84985. parentScale.copyFrom(mesh.getWorldMatrix());
  84986. parentScaleInv.copyFrom(parentScale);
  84987. parentScaleInv.invert();
  84988. lmat.multiplyToRef(parentScale, lmat);
  84989. lmat.multiplyToRef(rmat, lmat);
  84990. lmat.multiplyToRef(parentScaleInv, lmat);
  84991. }
  84992. else {
  84993. lmat.multiplyToRef(rmat, lmat);
  84994. }
  84995. }
  84996. lmat.m[12] = lx;
  84997. lmat.m[13] = ly;
  84998. lmat.m[14] = lz;
  84999. this.computeAbsoluteTransforms();
  85000. this._markAsDirtyAndDecompose();
  85001. };
  85002. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  85003. var scaleMatrix = Bone._tmpMats[2];
  85004. rotMatInv.copyFrom(this.getAbsoluteTransform());
  85005. if (mesh) {
  85006. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  85007. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  85008. }
  85009. rotMatInv.invert();
  85010. if (isNaN(rotMatInv.m[0])) {
  85011. // Matrix failed to invert.
  85012. // This can happen if scale is zero for example.
  85013. return false;
  85014. }
  85015. scaleMatrix.m[0] *= this._scalingDeterminant;
  85016. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  85017. return true;
  85018. };
  85019. /**
  85020. * Get the position of the bone in local or world space
  85021. * @param space The space that the returned position is in
  85022. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85023. * @returns The position of the bone
  85024. */
  85025. Bone.prototype.getPosition = function (space, mesh) {
  85026. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85027. if (mesh === void 0) { mesh = null; }
  85028. var pos = BABYLON.Vector3.Zero();
  85029. this.getPositionToRef(space, mesh, pos);
  85030. return pos;
  85031. };
  85032. /**
  85033. * Copy the position of the bone to a vector3 in local or world space
  85034. * @param space The space that the returned position is in
  85035. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85036. * @param result The vector3 to copy the position to
  85037. */
  85038. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  85039. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85040. if (space == BABYLON.Space.LOCAL) {
  85041. var lm = this.getLocalMatrix();
  85042. result.x = lm.m[12];
  85043. result.y = lm.m[13];
  85044. result.z = lm.m[14];
  85045. }
  85046. else {
  85047. var wm = null;
  85048. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85049. if (mesh) {
  85050. wm = mesh.getWorldMatrix();
  85051. }
  85052. this._skeleton.computeAbsoluteTransforms();
  85053. var tmat = Bone._tmpMats[0];
  85054. if (mesh && wm) {
  85055. tmat.copyFrom(this.getAbsoluteTransform());
  85056. tmat.multiplyToRef(wm, tmat);
  85057. }
  85058. else {
  85059. tmat = this.getAbsoluteTransform();
  85060. }
  85061. result.x = tmat.m[12];
  85062. result.y = tmat.m[13];
  85063. result.z = tmat.m[14];
  85064. }
  85065. };
  85066. /**
  85067. * Get the absolute position of the bone (world space)
  85068. * @param mesh The mesh that this bone is attached to
  85069. * @returns The absolute position of the bone
  85070. */
  85071. Bone.prototype.getAbsolutePosition = function (mesh) {
  85072. if (mesh === void 0) { mesh = null; }
  85073. var pos = BABYLON.Vector3.Zero();
  85074. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  85075. return pos;
  85076. };
  85077. /**
  85078. * Copy the absolute position of the bone (world space) to the result param
  85079. * @param mesh The mesh that this bone is attached to
  85080. * @param result The vector3 to copy the absolute position to
  85081. */
  85082. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  85083. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  85084. };
  85085. /**
  85086. * Compute the absolute transforms of this bone and its children
  85087. */
  85088. Bone.prototype.computeAbsoluteTransforms = function () {
  85089. this._compose();
  85090. if (this._parent) {
  85091. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  85092. }
  85093. else {
  85094. this._absoluteTransform.copyFrom(this._localMatrix);
  85095. var poseMatrix = this._skeleton.getPoseMatrix();
  85096. if (poseMatrix) {
  85097. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  85098. }
  85099. }
  85100. var children = this.children;
  85101. var len = children.length;
  85102. for (var i = 0; i < len; i++) {
  85103. children[i].computeAbsoluteTransforms();
  85104. }
  85105. };
  85106. /**
  85107. * Get the world direction from an axis that is in the local space of the bone
  85108. * @param localAxis The local direction that is used to compute the world direction
  85109. * @param mesh The mesh that this bone is attached to
  85110. * @returns The world direction
  85111. */
  85112. Bone.prototype.getDirection = function (localAxis, mesh) {
  85113. if (mesh === void 0) { mesh = null; }
  85114. var result = BABYLON.Vector3.Zero();
  85115. this.getDirectionToRef(localAxis, mesh, result);
  85116. return result;
  85117. };
  85118. /**
  85119. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  85120. * @param localAxis The local direction that is used to compute the world direction
  85121. * @param mesh The mesh that this bone is attached to
  85122. * @param result The vector3 that the world direction will be copied to
  85123. */
  85124. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  85125. if (mesh === void 0) { mesh = null; }
  85126. var wm = null;
  85127. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85128. if (mesh) {
  85129. wm = mesh.getWorldMatrix();
  85130. }
  85131. this._skeleton.computeAbsoluteTransforms();
  85132. var mat = Bone._tmpMats[0];
  85133. mat.copyFrom(this.getAbsoluteTransform());
  85134. if (mesh && wm) {
  85135. mat.multiplyToRef(wm, mat);
  85136. }
  85137. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  85138. result.normalize();
  85139. };
  85140. /**
  85141. * Get the euler rotation of the bone in local or world space
  85142. * @param space The space that the rotation should be in
  85143. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85144. * @returns The euler rotation
  85145. */
  85146. Bone.prototype.getRotation = function (space, mesh) {
  85147. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85148. if (mesh === void 0) { mesh = null; }
  85149. var result = BABYLON.Vector3.Zero();
  85150. this.getRotationToRef(space, mesh, result);
  85151. return result;
  85152. };
  85153. /**
  85154. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  85155. * @param space The space that the rotation should be in
  85156. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85157. * @param result The vector3 that the rotation should be copied to
  85158. */
  85159. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  85160. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85161. if (mesh === void 0) { mesh = null; }
  85162. var quat = Bone._tmpQuat;
  85163. this.getRotationQuaternionToRef(space, mesh, quat);
  85164. quat.toEulerAnglesToRef(result);
  85165. };
  85166. /**
  85167. * Get the quaternion rotation of the bone in either local or world space
  85168. * @param space The space that the rotation should be in
  85169. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85170. * @returns The quaternion rotation
  85171. */
  85172. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  85173. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85174. if (mesh === void 0) { mesh = null; }
  85175. var result = BABYLON.Quaternion.Identity();
  85176. this.getRotationQuaternionToRef(space, mesh, result);
  85177. return result;
  85178. };
  85179. /**
  85180. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  85181. * @param space The space that the rotation should be in
  85182. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85183. * @param result The quaternion that the rotation should be copied to
  85184. */
  85185. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  85186. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85187. if (mesh === void 0) { mesh = null; }
  85188. if (space == BABYLON.Space.LOCAL) {
  85189. this._decompose();
  85190. result.copyFrom(this._localRotation);
  85191. }
  85192. else {
  85193. var mat = Bone._tmpMats[0];
  85194. var amat = this.getAbsoluteTransform();
  85195. if (mesh) {
  85196. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  85197. }
  85198. else {
  85199. mat.copyFrom(amat);
  85200. }
  85201. mat.m[0] *= this._scalingDeterminant;
  85202. mat.m[1] *= this._scalingDeterminant;
  85203. mat.m[2] *= this._scalingDeterminant;
  85204. mat.decompose(undefined, result, undefined);
  85205. }
  85206. };
  85207. /**
  85208. * Get the rotation matrix of the bone in local or world space
  85209. * @param space The space that the rotation should be in
  85210. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85211. * @returns The rotation matrix
  85212. */
  85213. Bone.prototype.getRotationMatrix = function (space, mesh) {
  85214. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85215. var result = BABYLON.Matrix.Identity();
  85216. this.getRotationMatrixToRef(space, mesh, result);
  85217. return result;
  85218. };
  85219. /**
  85220. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  85221. * @param space The space that the rotation should be in
  85222. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85223. * @param result The quaternion that the rotation should be copied to
  85224. */
  85225. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  85226. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85227. if (space == BABYLON.Space.LOCAL) {
  85228. this.getLocalMatrix().getRotationMatrixToRef(result);
  85229. }
  85230. else {
  85231. var mat = Bone._tmpMats[0];
  85232. var amat = this.getAbsoluteTransform();
  85233. if (mesh) {
  85234. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  85235. }
  85236. else {
  85237. mat.copyFrom(amat);
  85238. }
  85239. mat.m[0] *= this._scalingDeterminant;
  85240. mat.m[1] *= this._scalingDeterminant;
  85241. mat.m[2] *= this._scalingDeterminant;
  85242. mat.getRotationMatrixToRef(result);
  85243. }
  85244. };
  85245. /**
  85246. * Get the world position of a point that is in the local space of the bone
  85247. * @param position The local position
  85248. * @param mesh The mesh that this bone is attached to
  85249. * @returns The world position
  85250. */
  85251. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  85252. if (mesh === void 0) { mesh = null; }
  85253. var result = BABYLON.Vector3.Zero();
  85254. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  85255. return result;
  85256. };
  85257. /**
  85258. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  85259. * @param position The local position
  85260. * @param mesh The mesh that this bone is attached to
  85261. * @param result The vector3 that the world position should be copied to
  85262. */
  85263. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  85264. if (mesh === void 0) { mesh = null; }
  85265. var wm = null;
  85266. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85267. if (mesh) {
  85268. wm = mesh.getWorldMatrix();
  85269. }
  85270. this._skeleton.computeAbsoluteTransforms();
  85271. var tmat = Bone._tmpMats[0];
  85272. if (mesh && wm) {
  85273. tmat.copyFrom(this.getAbsoluteTransform());
  85274. tmat.multiplyToRef(wm, tmat);
  85275. }
  85276. else {
  85277. tmat = this.getAbsoluteTransform();
  85278. }
  85279. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  85280. };
  85281. /**
  85282. * Get the local position of a point that is in world space
  85283. * @param position The world position
  85284. * @param mesh The mesh that this bone is attached to
  85285. * @returns The local position
  85286. */
  85287. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  85288. if (mesh === void 0) { mesh = null; }
  85289. var result = BABYLON.Vector3.Zero();
  85290. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  85291. return result;
  85292. };
  85293. /**
  85294. * Get the local position of a point that is in world space and copy it to the result param
  85295. * @param position The world position
  85296. * @param mesh The mesh that this bone is attached to
  85297. * @param result The vector3 that the local position should be copied to
  85298. */
  85299. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  85300. if (mesh === void 0) { mesh = null; }
  85301. var wm = null;
  85302. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85303. if (mesh) {
  85304. wm = mesh.getWorldMatrix();
  85305. }
  85306. this._skeleton.computeAbsoluteTransforms();
  85307. var tmat = Bone._tmpMats[0];
  85308. tmat.copyFrom(this.getAbsoluteTransform());
  85309. if (mesh && wm) {
  85310. tmat.multiplyToRef(wm, tmat);
  85311. }
  85312. tmat.invert();
  85313. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  85314. };
  85315. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85316. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  85317. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85318. return Bone;
  85319. }(BABYLON.Node));
  85320. BABYLON.Bone = Bone;
  85321. })(BABYLON || (BABYLON = {}));
  85322. //# sourceMappingURL=babylon.bone.js.map
  85323. var BABYLON;
  85324. (function (BABYLON) {
  85325. /**
  85326. * Class used to apply inverse kinematics to bones
  85327. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  85328. */
  85329. var BoneIKController = /** @class */ (function () {
  85330. /**
  85331. * Creates a new BoneIKController
  85332. * @param mesh defines the mesh to control
  85333. * @param bone defines the bone to control
  85334. * @param options defines options to set up the controller
  85335. */
  85336. function BoneIKController(mesh, bone, options) {
  85337. /**
  85338. * Gets or sets the target position
  85339. */
  85340. this.targetPosition = BABYLON.Vector3.Zero();
  85341. /**
  85342. * Gets or sets the pole target position
  85343. */
  85344. this.poleTargetPosition = BABYLON.Vector3.Zero();
  85345. /**
  85346. * Gets or sets the pole target local offset
  85347. */
  85348. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  85349. /**
  85350. * Gets or sets the pole angle
  85351. */
  85352. this.poleAngle = 0;
  85353. /**
  85354. * 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)
  85355. */
  85356. this.slerpAmount = 1;
  85357. this._bone1Quat = BABYLON.Quaternion.Identity();
  85358. this._bone1Mat = BABYLON.Matrix.Identity();
  85359. this._bone2Ang = Math.PI;
  85360. this._maxAngle = Math.PI;
  85361. this._rightHandedSystem = false;
  85362. this._bendAxis = BABYLON.Vector3.Right();
  85363. this._slerping = false;
  85364. this._adjustRoll = 0;
  85365. this._bone2 = bone;
  85366. this._bone1 = bone.getParent();
  85367. if (!this._bone1) {
  85368. return;
  85369. }
  85370. this.mesh = mesh;
  85371. var bonePos = bone.getPosition();
  85372. if (bone.getAbsoluteTransform().determinant() > 0) {
  85373. this._rightHandedSystem = true;
  85374. this._bendAxis.x = 0;
  85375. this._bendAxis.y = 0;
  85376. this._bendAxis.z = -1;
  85377. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  85378. this._adjustRoll = Math.PI * .5;
  85379. this._bendAxis.z = 1;
  85380. }
  85381. }
  85382. if (this._bone1.length) {
  85383. var boneScale1 = this._bone1.getScale();
  85384. var boneScale2 = this._bone2.getScale();
  85385. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  85386. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  85387. }
  85388. else if (this._bone1.children[0]) {
  85389. mesh.computeWorldMatrix(true);
  85390. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  85391. var pos2 = this._bone2.getAbsolutePosition(mesh);
  85392. var pos3 = this._bone1.getAbsolutePosition(mesh);
  85393. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  85394. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  85395. }
  85396. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  85397. this.maxAngle = Math.PI;
  85398. if (options) {
  85399. if (options.targetMesh) {
  85400. this.targetMesh = options.targetMesh;
  85401. this.targetMesh.computeWorldMatrix(true);
  85402. }
  85403. if (options.poleTargetMesh) {
  85404. this.poleTargetMesh = options.poleTargetMesh;
  85405. this.poleTargetMesh.computeWorldMatrix(true);
  85406. }
  85407. else if (options.poleTargetBone) {
  85408. this.poleTargetBone = options.poleTargetBone;
  85409. }
  85410. else if (this._bone1.getParent()) {
  85411. this.poleTargetBone = this._bone1.getParent();
  85412. }
  85413. if (options.poleTargetLocalOffset) {
  85414. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  85415. }
  85416. if (options.poleAngle) {
  85417. this.poleAngle = options.poleAngle;
  85418. }
  85419. if (options.bendAxis) {
  85420. this._bendAxis.copyFrom(options.bendAxis);
  85421. }
  85422. if (options.maxAngle) {
  85423. this.maxAngle = options.maxAngle;
  85424. }
  85425. if (options.slerpAmount) {
  85426. this.slerpAmount = options.slerpAmount;
  85427. }
  85428. }
  85429. }
  85430. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  85431. /**
  85432. * Gets or sets maximum allowed angle
  85433. */
  85434. get: function () {
  85435. return this._maxAngle;
  85436. },
  85437. set: function (value) {
  85438. this._setMaxAngle(value);
  85439. },
  85440. enumerable: true,
  85441. configurable: true
  85442. });
  85443. BoneIKController.prototype._setMaxAngle = function (ang) {
  85444. if (ang < 0) {
  85445. ang = 0;
  85446. }
  85447. if (ang > Math.PI || ang == undefined) {
  85448. ang = Math.PI;
  85449. }
  85450. this._maxAngle = ang;
  85451. var a = this._bone1Length;
  85452. var b = this._bone2Length;
  85453. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  85454. };
  85455. /**
  85456. * Force the controller to update the bones
  85457. */
  85458. BoneIKController.prototype.update = function () {
  85459. var bone1 = this._bone1;
  85460. if (!bone1) {
  85461. return;
  85462. }
  85463. var target = this.targetPosition;
  85464. var poleTarget = this.poleTargetPosition;
  85465. var mat1 = BoneIKController._tmpMats[0];
  85466. var mat2 = BoneIKController._tmpMats[1];
  85467. if (this.targetMesh) {
  85468. target.copyFrom(this.targetMesh.getAbsolutePosition());
  85469. }
  85470. if (this.poleTargetBone) {
  85471. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  85472. }
  85473. else if (this.poleTargetMesh) {
  85474. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  85475. }
  85476. var bonePos = BoneIKController._tmpVecs[0];
  85477. var zaxis = BoneIKController._tmpVecs[1];
  85478. var xaxis = BoneIKController._tmpVecs[2];
  85479. var yaxis = BoneIKController._tmpVecs[3];
  85480. var upAxis = BoneIKController._tmpVecs[4];
  85481. var _tmpQuat = BoneIKController._tmpQuat;
  85482. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  85483. poleTarget.subtractToRef(bonePos, upAxis);
  85484. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  85485. upAxis.y = 1;
  85486. }
  85487. else {
  85488. upAxis.normalize();
  85489. }
  85490. target.subtractToRef(bonePos, yaxis);
  85491. yaxis.normalize();
  85492. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  85493. zaxis.normalize();
  85494. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  85495. xaxis.normalize();
  85496. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  85497. var a = this._bone1Length;
  85498. var b = this._bone2Length;
  85499. var c = BABYLON.Vector3.Distance(bonePos, target);
  85500. if (this._maxReach > 0) {
  85501. c = Math.min(this._maxReach, c);
  85502. }
  85503. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  85504. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  85505. if (acosa > 1) {
  85506. acosa = 1;
  85507. }
  85508. if (acosb > 1) {
  85509. acosb = 1;
  85510. }
  85511. if (acosa < -1) {
  85512. acosa = -1;
  85513. }
  85514. if (acosb < -1) {
  85515. acosb = -1;
  85516. }
  85517. var angA = Math.acos(acosa);
  85518. var angB = Math.acos(acosb);
  85519. var angC = -angA - angB;
  85520. if (this._rightHandedSystem) {
  85521. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  85522. mat2.multiplyToRef(mat1, mat1);
  85523. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  85524. mat2.multiplyToRef(mat1, mat1);
  85525. }
  85526. else {
  85527. var _tmpVec = BoneIKController._tmpVecs[5];
  85528. _tmpVec.copyFrom(this._bendAxis);
  85529. _tmpVec.x *= -1;
  85530. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  85531. mat2.multiplyToRef(mat1, mat1);
  85532. }
  85533. if (this.poleAngle) {
  85534. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  85535. mat1.multiplyToRef(mat2, mat1);
  85536. }
  85537. if (this._bone1) {
  85538. if (this.slerpAmount < 1) {
  85539. if (!this._slerping) {
  85540. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  85541. }
  85542. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  85543. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  85544. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  85545. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  85546. this._slerping = true;
  85547. }
  85548. else {
  85549. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  85550. this._bone1Mat.copyFrom(mat1);
  85551. this._slerping = false;
  85552. }
  85553. }
  85554. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  85555. this._bone2Ang = angC;
  85556. };
  85557. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85558. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  85559. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85560. return BoneIKController;
  85561. }());
  85562. BABYLON.BoneIKController = BoneIKController;
  85563. })(BABYLON || (BABYLON = {}));
  85564. //# sourceMappingURL=babylon.boneIKController.js.map
  85565. var BABYLON;
  85566. (function (BABYLON) {
  85567. /**
  85568. * Class used to make a bone look toward a point in space
  85569. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  85570. */
  85571. var BoneLookController = /** @class */ (function () {
  85572. /**
  85573. * Create a BoneLookController
  85574. * @param mesh the mesh that the bone belongs to
  85575. * @param bone the bone that will be looking to the target
  85576. * @param target the target Vector3 to look at
  85577. * @param settings optional settings:
  85578. * * maxYaw: the maximum angle the bone will yaw to
  85579. * * minYaw: the minimum angle the bone will yaw to
  85580. * * maxPitch: the maximum angle the bone will pitch to
  85581. * * minPitch: the minimum angle the bone will yaw to
  85582. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  85583. * * upAxis: the up axis of the coordinate system
  85584. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  85585. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  85586. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  85587. * * adjustYaw: used to make an adjustment to the yaw of the bone
  85588. * * adjustPitch: used to make an adjustment to the pitch of the bone
  85589. * * adjustRoll: used to make an adjustment to the roll of the bone
  85590. **/
  85591. function BoneLookController(mesh, bone, target, options) {
  85592. /**
  85593. * The up axis of the coordinate system that is used when the bone is rotated
  85594. */
  85595. this.upAxis = BABYLON.Vector3.Up();
  85596. /**
  85597. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  85598. */
  85599. this.upAxisSpace = BABYLON.Space.LOCAL;
  85600. /**
  85601. * Used to make an adjustment to the yaw of the bone
  85602. */
  85603. this.adjustYaw = 0;
  85604. /**
  85605. * Used to make an adjustment to the pitch of the bone
  85606. */
  85607. this.adjustPitch = 0;
  85608. /**
  85609. * Used to make an adjustment to the roll of the bone
  85610. */
  85611. this.adjustRoll = 0;
  85612. /**
  85613. * 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)
  85614. */
  85615. this.slerpAmount = 1;
  85616. this._boneQuat = BABYLON.Quaternion.Identity();
  85617. this._slerping = false;
  85618. this._firstFrameSkipped = false;
  85619. this._fowardAxis = BABYLON.Vector3.Forward();
  85620. this.mesh = mesh;
  85621. this.bone = bone;
  85622. this.target = target;
  85623. if (options) {
  85624. if (options.adjustYaw) {
  85625. this.adjustYaw = options.adjustYaw;
  85626. }
  85627. if (options.adjustPitch) {
  85628. this.adjustPitch = options.adjustPitch;
  85629. }
  85630. if (options.adjustRoll) {
  85631. this.adjustRoll = options.adjustRoll;
  85632. }
  85633. if (options.maxYaw != null) {
  85634. this.maxYaw = options.maxYaw;
  85635. }
  85636. else {
  85637. this.maxYaw = Math.PI;
  85638. }
  85639. if (options.minYaw != null) {
  85640. this.minYaw = options.minYaw;
  85641. }
  85642. else {
  85643. this.minYaw = -Math.PI;
  85644. }
  85645. if (options.maxPitch != null) {
  85646. this.maxPitch = options.maxPitch;
  85647. }
  85648. else {
  85649. this.maxPitch = Math.PI;
  85650. }
  85651. if (options.minPitch != null) {
  85652. this.minPitch = options.minPitch;
  85653. }
  85654. else {
  85655. this.minPitch = -Math.PI;
  85656. }
  85657. if (options.slerpAmount != null) {
  85658. this.slerpAmount = options.slerpAmount;
  85659. }
  85660. if (options.upAxis != null) {
  85661. this.upAxis = options.upAxis;
  85662. }
  85663. if (options.upAxisSpace != null) {
  85664. this.upAxisSpace = options.upAxisSpace;
  85665. }
  85666. if (options.yawAxis != null || options.pitchAxis != null) {
  85667. var newYawAxis = BABYLON.Axis.Y;
  85668. var newPitchAxis = BABYLON.Axis.X;
  85669. if (options.yawAxis != null) {
  85670. newYawAxis = options.yawAxis.clone();
  85671. newYawAxis.normalize();
  85672. }
  85673. if (options.pitchAxis != null) {
  85674. newPitchAxis = options.pitchAxis.clone();
  85675. newPitchAxis.normalize();
  85676. }
  85677. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  85678. this._transformYawPitch = BABYLON.Matrix.Identity();
  85679. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  85680. this._transformYawPitchInv = this._transformYawPitch.clone();
  85681. this._transformYawPitch.invert();
  85682. }
  85683. }
  85684. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  85685. this.upAxisSpace = BABYLON.Space.LOCAL;
  85686. }
  85687. }
  85688. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  85689. /**
  85690. * Gets or sets the minimum yaw angle that the bone can look to
  85691. */
  85692. get: function () {
  85693. return this._minYaw;
  85694. },
  85695. set: function (value) {
  85696. this._minYaw = value;
  85697. this._minYawSin = Math.sin(value);
  85698. this._minYawCos = Math.cos(value);
  85699. if (this._maxYaw != null) {
  85700. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  85701. this._yawRange = this._maxYaw - this._minYaw;
  85702. }
  85703. },
  85704. enumerable: true,
  85705. configurable: true
  85706. });
  85707. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  85708. /**
  85709. * Gets or sets the maximum yaw angle that the bone can look to
  85710. */
  85711. get: function () {
  85712. return this._maxYaw;
  85713. },
  85714. set: function (value) {
  85715. this._maxYaw = value;
  85716. this._maxYawSin = Math.sin(value);
  85717. this._maxYawCos = Math.cos(value);
  85718. if (this._minYaw != null) {
  85719. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  85720. this._yawRange = this._maxYaw - this._minYaw;
  85721. }
  85722. },
  85723. enumerable: true,
  85724. configurable: true
  85725. });
  85726. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  85727. /**
  85728. * Gets or sets the minimum pitch angle that the bone can look to
  85729. */
  85730. get: function () {
  85731. return this._minPitch;
  85732. },
  85733. set: function (value) {
  85734. this._minPitch = value;
  85735. this._minPitchTan = Math.tan(value);
  85736. },
  85737. enumerable: true,
  85738. configurable: true
  85739. });
  85740. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  85741. /**
  85742. * Gets or sets the maximum pitch angle that the bone can look to
  85743. */
  85744. get: function () {
  85745. return this._maxPitch;
  85746. },
  85747. set: function (value) {
  85748. this._maxPitch = value;
  85749. this._maxPitchTan = Math.tan(value);
  85750. },
  85751. enumerable: true,
  85752. configurable: true
  85753. });
  85754. /**
  85755. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  85756. */
  85757. BoneLookController.prototype.update = function () {
  85758. //skip the first frame when slerping so that the mesh rotation is correct
  85759. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  85760. this._firstFrameSkipped = true;
  85761. return;
  85762. }
  85763. var bone = this.bone;
  85764. var bonePos = BoneLookController._tmpVecs[0];
  85765. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  85766. var target = this.target;
  85767. var _tmpMat1 = BoneLookController._tmpMats[0];
  85768. var _tmpMat2 = BoneLookController._tmpMats[1];
  85769. var mesh = this.mesh;
  85770. var parentBone = bone.getParent();
  85771. var upAxis = BoneLookController._tmpVecs[1];
  85772. upAxis.copyFrom(this.upAxis);
  85773. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  85774. if (this._transformYawPitch) {
  85775. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  85776. }
  85777. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  85778. }
  85779. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  85780. mesh.getDirectionToRef(upAxis, upAxis);
  85781. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  85782. upAxis.normalize();
  85783. }
  85784. }
  85785. var checkYaw = false;
  85786. var checkPitch = false;
  85787. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  85788. checkYaw = true;
  85789. }
  85790. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  85791. checkPitch = true;
  85792. }
  85793. if (checkYaw || checkPitch) {
  85794. var spaceMat = BoneLookController._tmpMats[2];
  85795. var spaceMatInv = BoneLookController._tmpMats[3];
  85796. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  85797. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  85798. }
  85799. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  85800. spaceMat.copyFrom(mesh.getWorldMatrix());
  85801. }
  85802. else {
  85803. var forwardAxis = BoneLookController._tmpVecs[2];
  85804. forwardAxis.copyFrom(this._fowardAxis);
  85805. if (this._transformYawPitch) {
  85806. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  85807. }
  85808. if (parentBone) {
  85809. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  85810. }
  85811. else {
  85812. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  85813. }
  85814. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  85815. rightAxis.normalize();
  85816. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  85817. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  85818. }
  85819. spaceMat.invertToRef(spaceMatInv);
  85820. var xzlen = null;
  85821. if (checkPitch) {
  85822. var localTarget = BoneLookController._tmpVecs[3];
  85823. target.subtractToRef(bonePos, localTarget);
  85824. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  85825. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85826. var pitch = Math.atan2(localTarget.y, xzlen);
  85827. var newPitch = pitch;
  85828. if (pitch > this._maxPitch) {
  85829. localTarget.y = this._maxPitchTan * xzlen;
  85830. newPitch = this._maxPitch;
  85831. }
  85832. else if (pitch < this._minPitch) {
  85833. localTarget.y = this._minPitchTan * xzlen;
  85834. newPitch = this._minPitch;
  85835. }
  85836. if (pitch != newPitch) {
  85837. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  85838. localTarget.addInPlace(bonePos);
  85839. target = localTarget;
  85840. }
  85841. }
  85842. if (checkYaw) {
  85843. var localTarget = BoneLookController._tmpVecs[4];
  85844. target.subtractToRef(bonePos, localTarget);
  85845. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  85846. var yaw = Math.atan2(localTarget.x, localTarget.z);
  85847. var newYaw = yaw;
  85848. if (yaw > this._maxYaw || yaw < this._minYaw) {
  85849. if (xzlen == null) {
  85850. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85851. }
  85852. if (this._yawRange > Math.PI) {
  85853. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  85854. localTarget.z = this._maxYawCos * xzlen;
  85855. localTarget.x = this._maxYawSin * xzlen;
  85856. newYaw = this._maxYaw;
  85857. }
  85858. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  85859. localTarget.z = this._minYawCos * xzlen;
  85860. localTarget.x = this._minYawSin * xzlen;
  85861. newYaw = this._minYaw;
  85862. }
  85863. }
  85864. else {
  85865. if (yaw > this._maxYaw) {
  85866. localTarget.z = this._maxYawCos * xzlen;
  85867. localTarget.x = this._maxYawSin * xzlen;
  85868. newYaw = this._maxYaw;
  85869. }
  85870. else if (yaw < this._minYaw) {
  85871. localTarget.z = this._minYawCos * xzlen;
  85872. localTarget.x = this._minYawSin * xzlen;
  85873. newYaw = this._minYaw;
  85874. }
  85875. }
  85876. }
  85877. if (this._slerping && this._yawRange > Math.PI) {
  85878. //are we going to be crossing into the min/max region?
  85879. var boneFwd = BoneLookController._tmpVecs[8];
  85880. boneFwd.copyFrom(BABYLON.Axis.Z);
  85881. if (this._transformYawPitch) {
  85882. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  85883. }
  85884. var boneRotMat = BoneLookController._tmpMats[4];
  85885. this._boneQuat.toRotationMatrix(boneRotMat);
  85886. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  85887. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  85888. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  85889. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  85890. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  85891. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  85892. if (angBtwTar > angBtwMidYaw) {
  85893. if (xzlen == null) {
  85894. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85895. }
  85896. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  85897. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  85898. if (angBtwMin < angBtwMax) {
  85899. newYaw = boneYaw + Math.PI * .75;
  85900. localTarget.z = Math.cos(newYaw) * xzlen;
  85901. localTarget.x = Math.sin(newYaw) * xzlen;
  85902. }
  85903. else {
  85904. newYaw = boneYaw - Math.PI * .75;
  85905. localTarget.z = Math.cos(newYaw) * xzlen;
  85906. localTarget.x = Math.sin(newYaw) * xzlen;
  85907. }
  85908. }
  85909. }
  85910. if (yaw != newYaw) {
  85911. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  85912. localTarget.addInPlace(bonePos);
  85913. target = localTarget;
  85914. }
  85915. }
  85916. }
  85917. var zaxis = BoneLookController._tmpVecs[5];
  85918. var xaxis = BoneLookController._tmpVecs[6];
  85919. var yaxis = BoneLookController._tmpVecs[7];
  85920. var _tmpQuat = BoneLookController._tmpQuat;
  85921. target.subtractToRef(bonePos, zaxis);
  85922. zaxis.normalize();
  85923. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  85924. xaxis.normalize();
  85925. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  85926. yaxis.normalize();
  85927. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  85928. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  85929. return;
  85930. }
  85931. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  85932. return;
  85933. }
  85934. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  85935. return;
  85936. }
  85937. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  85938. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  85939. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  85940. }
  85941. if (this.slerpAmount < 1) {
  85942. if (!this._slerping) {
  85943. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  85944. }
  85945. if (this._transformYawPitch) {
  85946. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  85947. }
  85948. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  85949. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  85950. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  85951. this._slerping = true;
  85952. }
  85953. else {
  85954. if (this._transformYawPitch) {
  85955. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  85956. }
  85957. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  85958. this._slerping = false;
  85959. }
  85960. };
  85961. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  85962. var angDiff = ang2 - ang1;
  85963. angDiff %= Math.PI * 2;
  85964. if (angDiff > Math.PI) {
  85965. angDiff -= Math.PI * 2;
  85966. }
  85967. else if (angDiff < -Math.PI) {
  85968. angDiff += Math.PI * 2;
  85969. }
  85970. return angDiff;
  85971. };
  85972. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  85973. ang1 %= (2 * Math.PI);
  85974. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  85975. ang2 %= (2 * Math.PI);
  85976. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  85977. var ab = 0;
  85978. if (ang1 < ang2) {
  85979. ab = ang2 - ang1;
  85980. }
  85981. else {
  85982. ab = ang1 - ang2;
  85983. }
  85984. if (ab > Math.PI) {
  85985. ab = Math.PI * 2 - ab;
  85986. }
  85987. return ab;
  85988. };
  85989. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  85990. ang %= (2 * Math.PI);
  85991. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  85992. ang1 %= (2 * Math.PI);
  85993. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  85994. ang2 %= (2 * Math.PI);
  85995. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  85996. if (ang1 < ang2) {
  85997. if (ang > ang1 && ang < ang2) {
  85998. return true;
  85999. }
  86000. }
  86001. else {
  86002. if (ang > ang2 && ang < ang1) {
  86003. return true;
  86004. }
  86005. }
  86006. return false;
  86007. };
  86008. 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()];
  86009. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  86010. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  86011. return BoneLookController;
  86012. }());
  86013. BABYLON.BoneLookController = BoneLookController;
  86014. })(BABYLON || (BABYLON = {}));
  86015. //# sourceMappingURL=babylon.boneLookController.js.map
  86016. var BABYLON;
  86017. (function (BABYLON) {
  86018. /**
  86019. * Class used to handle skinning animations
  86020. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  86021. */
  86022. var Skeleton = /** @class */ (function () {
  86023. /**
  86024. * Creates a new skeleton
  86025. * @param name defines the skeleton name
  86026. * @param id defines the skeleton Id
  86027. * @param scene defines the hosting scene
  86028. */
  86029. function Skeleton(
  86030. /** defines the skeleton name */
  86031. name,
  86032. /** defines the skeleton Id */
  86033. id, scene) {
  86034. this.name = name;
  86035. this.id = id;
  86036. /**
  86037. * Gets the list of child bones
  86038. */
  86039. this.bones = new Array();
  86040. /**
  86041. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  86042. */
  86043. this.needInitialSkinMatrix = false;
  86044. this._isDirty = true;
  86045. this._meshesWithPoseMatrix = new Array();
  86046. this._identity = BABYLON.Matrix.Identity();
  86047. this._ranges = {};
  86048. this._lastAbsoluteTransformsUpdateId = -1;
  86049. /**
  86050. * Specifies if the skeleton should be serialized
  86051. */
  86052. this.doNotSerialize = false;
  86053. this._animationPropertiesOverride = null;
  86054. // Events
  86055. /**
  86056. * An observable triggered before computing the skeleton's matrices
  86057. */
  86058. this.onBeforeComputeObservable = new BABYLON.Observable();
  86059. this.bones = [];
  86060. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86061. scene.skeletons.push(this);
  86062. //make sure it will recalculate the matrix next time prepare is called.
  86063. this._isDirty = true;
  86064. }
  86065. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  86066. /**
  86067. * Gets or sets the animation properties override
  86068. */
  86069. get: function () {
  86070. if (!this._animationPropertiesOverride) {
  86071. return this._scene.animationPropertiesOverride;
  86072. }
  86073. return this._animationPropertiesOverride;
  86074. },
  86075. set: function (value) {
  86076. this._animationPropertiesOverride = value;
  86077. },
  86078. enumerable: true,
  86079. configurable: true
  86080. });
  86081. // Members
  86082. /**
  86083. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  86084. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  86085. * @returns a Float32Array containing matrices data
  86086. */
  86087. Skeleton.prototype.getTransformMatrices = function (mesh) {
  86088. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  86089. return mesh._bonesTransformMatrices;
  86090. }
  86091. if (!this._transformMatrices) {
  86092. this.prepare();
  86093. }
  86094. return this._transformMatrices;
  86095. };
  86096. /**
  86097. * Gets the current hosting scene
  86098. * @returns a scene object
  86099. */
  86100. Skeleton.prototype.getScene = function () {
  86101. return this._scene;
  86102. };
  86103. // Methods
  86104. /**
  86105. * Gets a string representing the current skeleton data
  86106. * @param fullDetails defines a boolean indicating if we want a verbose version
  86107. * @returns a string representing the current skeleton data
  86108. */
  86109. Skeleton.prototype.toString = function (fullDetails) {
  86110. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  86111. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  86112. if (fullDetails) {
  86113. ret += ", Ranges: {";
  86114. var first = true;
  86115. for (var name_1 in this._ranges) {
  86116. if (first) {
  86117. ret += ", ";
  86118. first = false;
  86119. }
  86120. ret += name_1;
  86121. }
  86122. ret += "}";
  86123. }
  86124. return ret;
  86125. };
  86126. /**
  86127. * Get bone's index searching by name
  86128. * @param name defines bone's name to search for
  86129. * @return the indice of the bone. Returns -1 if not found
  86130. */
  86131. Skeleton.prototype.getBoneIndexByName = function (name) {
  86132. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  86133. if (this.bones[boneIndex].name === name) {
  86134. return boneIndex;
  86135. }
  86136. }
  86137. return -1;
  86138. };
  86139. /**
  86140. * Creater a new animation range
  86141. * @param name defines the name of the range
  86142. * @param from defines the start key
  86143. * @param to defines the end key
  86144. */
  86145. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  86146. // check name not already in use
  86147. if (!this._ranges[name]) {
  86148. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  86149. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  86150. if (this.bones[i].animations[0]) {
  86151. this.bones[i].animations[0].createRange(name, from, to);
  86152. }
  86153. }
  86154. }
  86155. };
  86156. /**
  86157. * Delete a specific animation range
  86158. * @param name defines the name of the range
  86159. * @param deleteFrames defines if frames must be removed as well
  86160. */
  86161. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  86162. if (deleteFrames === void 0) { deleteFrames = true; }
  86163. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  86164. if (this.bones[i].animations[0]) {
  86165. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  86166. }
  86167. }
  86168. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  86169. };
  86170. /**
  86171. * Gets a specific animation range
  86172. * @param name defines the name of the range to look for
  86173. * @returns the requested animation range or null if not found
  86174. */
  86175. Skeleton.prototype.getAnimationRange = function (name) {
  86176. return this._ranges[name];
  86177. };
  86178. /**
  86179. * Gets the list of all animation ranges defined on this skeleton
  86180. * @returns an array
  86181. */
  86182. Skeleton.prototype.getAnimationRanges = function () {
  86183. var animationRanges = [];
  86184. var name;
  86185. var i = 0;
  86186. for (name in this._ranges) {
  86187. animationRanges[i] = this._ranges[name];
  86188. i++;
  86189. }
  86190. return animationRanges;
  86191. };
  86192. /**
  86193. * Copy animation range from a source skeleton.
  86194. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  86195. * @param source defines the source skeleton
  86196. * @param name defines the name of the range to copy
  86197. * @param rescaleAsRequired defines if rescaling must be applied if required
  86198. * @returns true if operation was successful
  86199. */
  86200. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  86201. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  86202. if (this._ranges[name] || !source.getAnimationRange(name)) {
  86203. return false;
  86204. }
  86205. var ret = true;
  86206. var frameOffset = this._getHighestAnimationFrame() + 1;
  86207. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  86208. var boneDict = {};
  86209. var sourceBones = source.bones;
  86210. var nBones;
  86211. var i;
  86212. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  86213. boneDict[sourceBones[i].name] = sourceBones[i];
  86214. }
  86215. if (this.bones.length !== sourceBones.length) {
  86216. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  86217. ret = false;
  86218. }
  86219. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  86220. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  86221. var boneName = this.bones[i].name;
  86222. var sourceBone = boneDict[boneName];
  86223. if (sourceBone) {
  86224. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  86225. }
  86226. else {
  86227. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  86228. ret = false;
  86229. }
  86230. }
  86231. // do not call createAnimationRange(), since it also is done to bones, which was already done
  86232. var range = source.getAnimationRange(name);
  86233. if (range) {
  86234. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  86235. }
  86236. return ret;
  86237. };
  86238. /**
  86239. * Forces the skeleton to go to rest pose
  86240. */
  86241. Skeleton.prototype.returnToRest = function () {
  86242. for (var index = 0; index < this.bones.length; index++) {
  86243. this.bones[index].returnToRest();
  86244. }
  86245. };
  86246. Skeleton.prototype._getHighestAnimationFrame = function () {
  86247. var ret = 0;
  86248. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  86249. if (this.bones[i].animations[0]) {
  86250. var highest = this.bones[i].animations[0].getHighestFrame();
  86251. if (ret < highest) {
  86252. ret = highest;
  86253. }
  86254. }
  86255. }
  86256. return ret;
  86257. };
  86258. /**
  86259. * Begin a specific animation range
  86260. * @param name defines the name of the range to start
  86261. * @param loop defines if looping must be turned on (false by default)
  86262. * @param speedRatio defines the speed ratio to apply (1 by default)
  86263. * @param onAnimationEnd defines a callback which will be called when animation will end
  86264. * @returns a new animatable
  86265. */
  86266. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  86267. var range = this.getAnimationRange(name);
  86268. if (!range) {
  86269. return null;
  86270. }
  86271. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  86272. };
  86273. /** @hidden */
  86274. Skeleton.prototype._markAsDirty = function () {
  86275. this._isDirty = true;
  86276. };
  86277. /** @hidden */
  86278. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  86279. this._meshesWithPoseMatrix.push(mesh);
  86280. };
  86281. /** @hidden */
  86282. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  86283. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  86284. if (index > -1) {
  86285. this._meshesWithPoseMatrix.splice(index, 1);
  86286. }
  86287. };
  86288. /** @hidden */
  86289. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  86290. this.onBeforeComputeObservable.notifyObservers(this);
  86291. for (var index = 0; index < this.bones.length; index++) {
  86292. var bone = this.bones[index];
  86293. var parentBone = bone.getParent();
  86294. if (parentBone) {
  86295. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  86296. }
  86297. else {
  86298. if (initialSkinMatrix) {
  86299. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  86300. }
  86301. else {
  86302. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  86303. }
  86304. }
  86305. if (bone._index !== -1) {
  86306. var mappedIndex = bone._index === null ? index : bone._index;
  86307. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  86308. }
  86309. }
  86310. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  86311. };
  86312. /**
  86313. * Build all resources required to render a skeleton
  86314. */
  86315. Skeleton.prototype.prepare = function () {
  86316. if (!this._isDirty) {
  86317. return;
  86318. }
  86319. if (this.needInitialSkinMatrix) {
  86320. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  86321. var mesh = this._meshesWithPoseMatrix[index];
  86322. var poseMatrix = mesh.getPoseMatrix();
  86323. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  86324. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  86325. }
  86326. if (this._synchronizedWithMesh !== mesh) {
  86327. this._synchronizedWithMesh = mesh;
  86328. // Prepare bones
  86329. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  86330. var bone = this.bones[boneIndex];
  86331. if (!bone.getParent()) {
  86332. var matrix = bone.getBaseMatrix();
  86333. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  86334. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  86335. }
  86336. }
  86337. }
  86338. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  86339. }
  86340. }
  86341. else {
  86342. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  86343. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  86344. }
  86345. this._computeTransformMatrices(this._transformMatrices, null);
  86346. }
  86347. this._isDirty = false;
  86348. this._scene._activeBones.addCount(this.bones.length, false);
  86349. };
  86350. /**
  86351. * Gets the list of animatables currently running for this skeleton
  86352. * @returns an array of animatables
  86353. */
  86354. Skeleton.prototype.getAnimatables = function () {
  86355. if (!this._animatables || this._animatables.length !== this.bones.length) {
  86356. this._animatables = [];
  86357. for (var index = 0; index < this.bones.length; index++) {
  86358. this._animatables.push(this.bones[index]);
  86359. }
  86360. }
  86361. return this._animatables;
  86362. };
  86363. /**
  86364. * Clone the current skeleton
  86365. * @param name defines the name of the new skeleton
  86366. * @param id defines the id of the enw skeleton
  86367. * @returns the new skeleton
  86368. */
  86369. Skeleton.prototype.clone = function (name, id) {
  86370. var result = new Skeleton(name, id || name, this._scene);
  86371. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  86372. for (var index = 0; index < this.bones.length; index++) {
  86373. var source = this.bones[index];
  86374. var parentBone = null;
  86375. var parent_1 = source.getParent();
  86376. if (parent_1) {
  86377. var parentIndex = this.bones.indexOf(parent_1);
  86378. parentBone = result.bones[parentIndex];
  86379. }
  86380. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  86381. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  86382. }
  86383. if (this._ranges) {
  86384. result._ranges = {};
  86385. for (var rangeName in this._ranges) {
  86386. var range = this._ranges[rangeName];
  86387. if (range) {
  86388. result._ranges[rangeName] = range.clone();
  86389. }
  86390. }
  86391. }
  86392. this._isDirty = true;
  86393. return result;
  86394. };
  86395. /**
  86396. * Enable animation blending for this skeleton
  86397. * @param blendingSpeed defines the blending speed to apply
  86398. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  86399. */
  86400. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  86401. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  86402. this.bones.forEach(function (bone) {
  86403. bone.animations.forEach(function (animation) {
  86404. animation.enableBlending = true;
  86405. animation.blendingSpeed = blendingSpeed;
  86406. });
  86407. });
  86408. };
  86409. /**
  86410. * Releases all resources associated with the current skeleton
  86411. */
  86412. Skeleton.prototype.dispose = function () {
  86413. this._meshesWithPoseMatrix = [];
  86414. // Animations
  86415. this.getScene().stopAnimation(this);
  86416. // Remove from scene
  86417. this.getScene().removeSkeleton(this);
  86418. };
  86419. /**
  86420. * Serialize the skeleton in a JSON object
  86421. * @returns a JSON object
  86422. */
  86423. Skeleton.prototype.serialize = function () {
  86424. var serializationObject = {};
  86425. serializationObject.name = this.name;
  86426. serializationObject.id = this.id;
  86427. if (this.dimensionsAtRest) {
  86428. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  86429. }
  86430. serializationObject.bones = [];
  86431. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  86432. for (var index = 0; index < this.bones.length; index++) {
  86433. var bone = this.bones[index];
  86434. var parent_2 = bone.getParent();
  86435. var serializedBone = {
  86436. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  86437. name: bone.name,
  86438. matrix: bone.getBaseMatrix().toArray(),
  86439. rest: bone.getRestPose().toArray()
  86440. };
  86441. serializationObject.bones.push(serializedBone);
  86442. if (bone.length) {
  86443. serializedBone.length = bone.length;
  86444. }
  86445. if (bone.metadata) {
  86446. serializedBone.metadata = bone.metadata;
  86447. }
  86448. if (bone.animations && bone.animations.length > 0) {
  86449. serializedBone.animation = bone.animations[0].serialize();
  86450. }
  86451. serializationObject.ranges = [];
  86452. for (var name in this._ranges) {
  86453. var source = this._ranges[name];
  86454. if (!source) {
  86455. continue;
  86456. }
  86457. var range = {};
  86458. range.name = name;
  86459. range.from = source.from;
  86460. range.to = source.to;
  86461. serializationObject.ranges.push(range);
  86462. }
  86463. }
  86464. return serializationObject;
  86465. };
  86466. /**
  86467. * Creates a new skeleton from serialized data
  86468. * @param parsedSkeleton defines the serialized data
  86469. * @param scene defines the hosting scene
  86470. * @returns a new skeleton
  86471. */
  86472. Skeleton.Parse = function (parsedSkeleton, scene) {
  86473. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  86474. if (parsedSkeleton.dimensionsAtRest) {
  86475. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  86476. }
  86477. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  86478. var index;
  86479. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  86480. var parsedBone = parsedSkeleton.bones[index];
  86481. var parentBone = null;
  86482. if (parsedBone.parentBoneIndex > -1) {
  86483. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  86484. }
  86485. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  86486. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  86487. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  86488. bone.id = parsedBone.id;
  86489. }
  86490. if (parsedBone.length) {
  86491. bone.length = parsedBone.length;
  86492. }
  86493. if (parsedBone.metadata) {
  86494. bone.metadata = parsedBone.metadata;
  86495. }
  86496. if (parsedBone.animation) {
  86497. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  86498. }
  86499. }
  86500. // placed after bones, so createAnimationRange can cascade down
  86501. if (parsedSkeleton.ranges) {
  86502. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  86503. var data = parsedSkeleton.ranges[index];
  86504. skeleton.createAnimationRange(data.name, data.from, data.to);
  86505. }
  86506. }
  86507. return skeleton;
  86508. };
  86509. /**
  86510. * Compute all node absolute transforms
  86511. * @param forceUpdate defines if computation must be done even if cache is up to date
  86512. */
  86513. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  86514. if (forceUpdate === void 0) { forceUpdate = false; }
  86515. var renderId = this._scene.getRenderId();
  86516. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  86517. this.bones[0].computeAbsoluteTransforms();
  86518. this._lastAbsoluteTransformsUpdateId = renderId;
  86519. }
  86520. };
  86521. /**
  86522. * Gets the root pose matrix
  86523. * @returns a matrix
  86524. */
  86525. Skeleton.prototype.getPoseMatrix = function () {
  86526. var poseMatrix = null;
  86527. if (this._meshesWithPoseMatrix.length > 0) {
  86528. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  86529. }
  86530. return poseMatrix;
  86531. };
  86532. /**
  86533. * Sorts bones per internal index
  86534. */
  86535. Skeleton.prototype.sortBones = function () {
  86536. var bones = new Array();
  86537. var visited = new Array(this.bones.length);
  86538. for (var index = 0; index < this.bones.length; index++) {
  86539. this._sortBones(index, bones, visited);
  86540. }
  86541. this.bones = bones;
  86542. };
  86543. Skeleton.prototype._sortBones = function (index, bones, visited) {
  86544. if (visited[index]) {
  86545. return;
  86546. }
  86547. visited[index] = true;
  86548. var bone = this.bones[index];
  86549. if (bone._index === undefined) {
  86550. bone._index = index;
  86551. }
  86552. var parentBone = bone.getParent();
  86553. if (parentBone) {
  86554. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  86555. }
  86556. bones.push(bone);
  86557. };
  86558. return Skeleton;
  86559. }());
  86560. BABYLON.Skeleton = Skeleton;
  86561. })(BABYLON || (BABYLON = {}));
  86562. //# sourceMappingURL=babylon.skeleton.js.map
  86563. var BABYLON;
  86564. (function (BABYLON) {
  86565. ;
  86566. /**
  86567. * This groups tools to convert HDR texture to native colors array.
  86568. */
  86569. var HDRTools = /** @class */ (function () {
  86570. function HDRTools() {
  86571. }
  86572. HDRTools.Ldexp = function (mantissa, exponent) {
  86573. if (exponent > 1023) {
  86574. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  86575. }
  86576. if (exponent < -1074) {
  86577. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  86578. }
  86579. return mantissa * Math.pow(2, exponent);
  86580. };
  86581. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  86582. if (exponent > 0) { /*nonzero pixel*/
  86583. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  86584. float32array[index + 0] = red * exponent;
  86585. float32array[index + 1] = green * exponent;
  86586. float32array[index + 2] = blue * exponent;
  86587. }
  86588. else {
  86589. float32array[index + 0] = 0;
  86590. float32array[index + 1] = 0;
  86591. float32array[index + 2] = 0;
  86592. }
  86593. };
  86594. HDRTools.readStringLine = function (uint8array, startIndex) {
  86595. var line = "";
  86596. var character = "";
  86597. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  86598. character = String.fromCharCode(uint8array[i]);
  86599. if (character == "\n") {
  86600. break;
  86601. }
  86602. line += character;
  86603. }
  86604. return line;
  86605. };
  86606. /**
  86607. * Reads header information from an RGBE texture stored in a native array.
  86608. * More information on this format are available here:
  86609. * https://en.wikipedia.org/wiki/RGBE_image_format
  86610. *
  86611. * @param uint8array The binary file stored in native array.
  86612. * @return The header information.
  86613. */
  86614. HDRTools.RGBE_ReadHeader = function (uint8array) {
  86615. var height = 0;
  86616. var width = 0;
  86617. var line = this.readStringLine(uint8array, 0);
  86618. if (line[0] != '#' || line[1] != '?') {
  86619. throw "Bad HDR Format.";
  86620. }
  86621. var endOfHeader = false;
  86622. var findFormat = false;
  86623. var lineIndex = 0;
  86624. do {
  86625. lineIndex += (line.length + 1);
  86626. line = this.readStringLine(uint8array, lineIndex);
  86627. if (line == "FORMAT=32-bit_rle_rgbe") {
  86628. findFormat = true;
  86629. }
  86630. else if (line.length == 0) {
  86631. endOfHeader = true;
  86632. }
  86633. } while (!endOfHeader);
  86634. if (!findFormat) {
  86635. throw "HDR Bad header format, unsupported FORMAT";
  86636. }
  86637. lineIndex += (line.length + 1);
  86638. line = this.readStringLine(uint8array, lineIndex);
  86639. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  86640. var match = sizeRegexp.exec(line);
  86641. // TODO. Support +Y and -X if needed.
  86642. if (!match || match.length < 3) {
  86643. throw "HDR Bad header format, no size";
  86644. }
  86645. width = parseInt(match[2]);
  86646. height = parseInt(match[1]);
  86647. if (width < 8 || width > 0x7fff) {
  86648. throw "HDR Bad header format, unsupported size";
  86649. }
  86650. lineIndex += (line.length + 1);
  86651. return {
  86652. height: height,
  86653. width: width,
  86654. dataPosition: lineIndex
  86655. };
  86656. };
  86657. /**
  86658. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  86659. * This RGBE texture needs to store the information as a panorama.
  86660. *
  86661. * More information on this format are available here:
  86662. * https://en.wikipedia.org/wiki/RGBE_image_format
  86663. *
  86664. * @param buffer The binary file stored in an array buffer.
  86665. * @param size The expected size of the extracted cubemap.
  86666. * @return The Cube Map information.
  86667. */
  86668. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  86669. var uint8array = new Uint8Array(buffer);
  86670. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  86671. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  86672. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  86673. return cubeMapData;
  86674. };
  86675. /**
  86676. * Returns the pixels data extracted from an RGBE texture.
  86677. * This pixels will be stored left to right up to down in the R G B order in one array.
  86678. *
  86679. * More information on this format are available here:
  86680. * https://en.wikipedia.org/wiki/RGBE_image_format
  86681. *
  86682. * @param uint8array The binary file stored in an array buffer.
  86683. * @param hdrInfo The header information of the file.
  86684. * @return The pixels data in RGB right to left up to down order.
  86685. */
  86686. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  86687. // Keep for multi format supports.
  86688. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  86689. };
  86690. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  86691. var num_scanlines = hdrInfo.height;
  86692. var scanline_width = hdrInfo.width;
  86693. var a, b, c, d, count;
  86694. var dataIndex = hdrInfo.dataPosition;
  86695. var index = 0, endIndex = 0, i = 0;
  86696. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  86697. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  86698. // 3 channels of 4 bytes per pixel in float.
  86699. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  86700. var resultArray = new Float32Array(resultBuffer);
  86701. // read in each successive scanline
  86702. while (num_scanlines > 0) {
  86703. a = uint8array[dataIndex++];
  86704. b = uint8array[dataIndex++];
  86705. c = uint8array[dataIndex++];
  86706. d = uint8array[dataIndex++];
  86707. if (a != 2 || b != 2 || (c & 0x80)) {
  86708. // this file is not run length encoded
  86709. throw "HDR Bad header format, not RLE";
  86710. }
  86711. if (((c << 8) | d) != scanline_width) {
  86712. throw "HDR Bad header format, wrong scan line width";
  86713. }
  86714. index = 0;
  86715. // read each of the four channels for the scanline into the buffer
  86716. for (i = 0; i < 4; i++) {
  86717. endIndex = (i + 1) * scanline_width;
  86718. while (index < endIndex) {
  86719. a = uint8array[dataIndex++];
  86720. b = uint8array[dataIndex++];
  86721. if (a > 128) {
  86722. // a run of the same value
  86723. count = a - 128;
  86724. if ((count == 0) || (count > endIndex - index)) {
  86725. throw "HDR Bad Format, bad scanline data (run)";
  86726. }
  86727. while (count-- > 0) {
  86728. scanLineArray[index++] = b;
  86729. }
  86730. }
  86731. else {
  86732. // a non-run
  86733. count = a;
  86734. if ((count == 0) || (count > endIndex - index)) {
  86735. throw "HDR Bad Format, bad scanline data (non-run)";
  86736. }
  86737. scanLineArray[index++] = b;
  86738. if (--count > 0) {
  86739. for (var j = 0; j < count; j++) {
  86740. scanLineArray[index++] = uint8array[dataIndex++];
  86741. }
  86742. }
  86743. }
  86744. }
  86745. }
  86746. // now convert data from buffer into floats
  86747. for (i = 0; i < scanline_width; i++) {
  86748. a = scanLineArray[i];
  86749. b = scanLineArray[i + scanline_width];
  86750. c = scanLineArray[i + 2 * scanline_width];
  86751. d = scanLineArray[i + 3 * scanline_width];
  86752. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  86753. }
  86754. num_scanlines--;
  86755. }
  86756. return resultArray;
  86757. };
  86758. return HDRTools;
  86759. }());
  86760. BABYLON.HDRTools = HDRTools;
  86761. })(BABYLON || (BABYLON = {}));
  86762. //# sourceMappingURL=babylon.hdr.js.map
  86763. var BABYLON;
  86764. (function (BABYLON) {
  86765. /**
  86766. * This represents a texture coming from an HDR input.
  86767. *
  86768. * The only supported format is currently panorama picture stored in RGBE format.
  86769. * Example of such files can be found on HDRLib: http://hdrlib.com/
  86770. */
  86771. var HDRCubeTexture = /** @class */ (function (_super) {
  86772. __extends(HDRCubeTexture, _super);
  86773. /**
  86774. * Instantiates an HDRTexture from the following parameters.
  86775. *
  86776. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  86777. * @param scene The scene the texture will be used in
  86778. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  86779. * @param noMipmap Forces to not generate the mipmap if true
  86780. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  86781. * @param gammaSpace 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)
  86782. * @param reserved Reserved flag for internal use.
  86783. */
  86784. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  86785. if (noMipmap === void 0) { noMipmap = false; }
  86786. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86787. if (gammaSpace === void 0) { gammaSpace = false; }
  86788. if (reserved === void 0) { reserved = false; }
  86789. if (onLoad === void 0) { onLoad = null; }
  86790. if (onError === void 0) { onError = null; }
  86791. var _this = _super.call(this, scene) || this;
  86792. _this._generateHarmonics = true;
  86793. _this._onLoad = null;
  86794. _this._onError = null;
  86795. /**
  86796. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  86797. */
  86798. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  86799. _this._isBlocking = true;
  86800. _this._rotationY = 0;
  86801. /**
  86802. * Gets or sets the center of the bounding box associated with the cube texture
  86803. * It must define where the camera used to render the texture was set
  86804. */
  86805. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  86806. if (!url) {
  86807. return _this;
  86808. }
  86809. _this.name = url;
  86810. _this.url = url;
  86811. _this.hasAlpha = false;
  86812. _this.isCube = true;
  86813. _this._textureMatrix = BABYLON.Matrix.Identity();
  86814. _this._onLoad = onLoad;
  86815. _this._onError = onError;
  86816. _this.gammaSpace = gammaSpace;
  86817. _this._noMipmap = noMipmap;
  86818. _this._size = size;
  86819. _this._texture = _this._getFromCache(url, _this._noMipmap);
  86820. if (!_this._texture) {
  86821. if (!scene.useDelayedTextureLoading) {
  86822. _this.loadTexture();
  86823. }
  86824. else {
  86825. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  86826. }
  86827. }
  86828. return _this;
  86829. }
  86830. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  86831. /**
  86832. * Gets wether or not the texture is blocking during loading.
  86833. */
  86834. get: function () {
  86835. return this._isBlocking;
  86836. },
  86837. /**
  86838. * Sets wether or not the texture is blocking during loading.
  86839. */
  86840. set: function (value) {
  86841. this._isBlocking = value;
  86842. },
  86843. enumerable: true,
  86844. configurable: true
  86845. });
  86846. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  86847. /**
  86848. * Gets texture matrix rotation angle around Y axis radians.
  86849. */
  86850. get: function () {
  86851. return this._rotationY;
  86852. },
  86853. /**
  86854. * Sets texture matrix rotation angle around Y axis in radians.
  86855. */
  86856. set: function (value) {
  86857. this._rotationY = value;
  86858. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  86859. },
  86860. enumerable: true,
  86861. configurable: true
  86862. });
  86863. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  86864. get: function () {
  86865. return this._boundingBoxSize;
  86866. },
  86867. /**
  86868. * Gets or sets the size of the bounding box associated with the cube texture
  86869. * When defined, the cubemap will switch to local mode
  86870. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  86871. * @example https://www.babylonjs-playground.com/#RNASML
  86872. */
  86873. set: function (value) {
  86874. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  86875. return;
  86876. }
  86877. this._boundingBoxSize = value;
  86878. var scene = this.getScene();
  86879. if (scene) {
  86880. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  86881. }
  86882. },
  86883. enumerable: true,
  86884. configurable: true
  86885. });
  86886. /**
  86887. * Occurs when the file is raw .hdr file.
  86888. */
  86889. HDRCubeTexture.prototype.loadTexture = function () {
  86890. var _this = this;
  86891. var callback = function (buffer) {
  86892. _this.lodGenerationOffset = 0.0;
  86893. _this.lodGenerationScale = 0.8;
  86894. var scene = _this.getScene();
  86895. if (!scene) {
  86896. return null;
  86897. }
  86898. // Extract the raw linear data.
  86899. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  86900. // Generate harmonics if needed.
  86901. if (_this._generateHarmonics) {
  86902. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  86903. _this.sphericalPolynomial = sphericalPolynomial;
  86904. }
  86905. var results = [];
  86906. var byteArray = null;
  86907. // Push each faces.
  86908. for (var j = 0; j < 6; j++) {
  86909. // Create uintarray fallback.
  86910. if (!scene.getEngine().getCaps().textureFloat) {
  86911. // 3 channels of 1 bytes per pixel in bytes.
  86912. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  86913. byteArray = new Uint8Array(byteBuffer);
  86914. }
  86915. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  86916. // If special cases.
  86917. if (_this.gammaSpace || byteArray) {
  86918. for (var i = 0; i < _this._size * _this._size; i++) {
  86919. // Put in gamma space if requested.
  86920. if (_this.gammaSpace) {
  86921. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  86922. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  86923. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  86924. }
  86925. // Convert to int texture for fallback.
  86926. if (byteArray) {
  86927. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  86928. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  86929. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  86930. // May use luminance instead if the result is not accurate.
  86931. var max = Math.max(Math.max(r, g), b);
  86932. if (max > 255) {
  86933. var scale = 255 / max;
  86934. r *= scale;
  86935. g *= scale;
  86936. b *= scale;
  86937. }
  86938. byteArray[(i * 3) + 0] = r;
  86939. byteArray[(i * 3) + 1] = g;
  86940. byteArray[(i * 3) + 2] = b;
  86941. }
  86942. }
  86943. }
  86944. if (byteArray) {
  86945. results.push(byteArray);
  86946. }
  86947. else {
  86948. results.push(dataFace);
  86949. }
  86950. }
  86951. return results;
  86952. };
  86953. var scene = this.getScene();
  86954. if (scene) {
  86955. 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, null, this._onLoad, this._onError);
  86956. }
  86957. };
  86958. HDRCubeTexture.prototype.clone = function () {
  86959. var scene = this.getScene();
  86960. if (!scene) {
  86961. return this;
  86962. }
  86963. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  86964. // Base texture
  86965. newTexture.level = this.level;
  86966. newTexture.wrapU = this.wrapU;
  86967. newTexture.wrapV = this.wrapV;
  86968. newTexture.coordinatesIndex = this.coordinatesIndex;
  86969. newTexture.coordinatesMode = this.coordinatesMode;
  86970. return newTexture;
  86971. };
  86972. // Methods
  86973. HDRCubeTexture.prototype.delayLoad = function () {
  86974. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  86975. return;
  86976. }
  86977. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  86978. this._texture = this._getFromCache(this.url, this._noMipmap);
  86979. if (!this._texture) {
  86980. this.loadTexture();
  86981. }
  86982. };
  86983. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  86984. return this._textureMatrix;
  86985. };
  86986. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  86987. this._textureMatrix = value;
  86988. };
  86989. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  86990. var texture = null;
  86991. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  86992. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  86993. texture.name = parsedTexture.name;
  86994. texture.hasAlpha = parsedTexture.hasAlpha;
  86995. texture.level = parsedTexture.level;
  86996. texture.coordinatesMode = parsedTexture.coordinatesMode;
  86997. texture.isBlocking = parsedTexture.isBlocking;
  86998. }
  86999. if (texture) {
  87000. if (parsedTexture.boundingBoxPosition) {
  87001. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  87002. }
  87003. if (parsedTexture.boundingBoxSize) {
  87004. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  87005. }
  87006. if (parsedTexture.rotationY) {
  87007. texture.rotationY = parsedTexture.rotationY;
  87008. }
  87009. }
  87010. return texture;
  87011. };
  87012. HDRCubeTexture.prototype.serialize = function () {
  87013. if (!this.name) {
  87014. return null;
  87015. }
  87016. var serializationObject = {};
  87017. serializationObject.name = this.name;
  87018. serializationObject.hasAlpha = this.hasAlpha;
  87019. serializationObject.isCube = true;
  87020. serializationObject.level = this.level;
  87021. serializationObject.size = this._size;
  87022. serializationObject.coordinatesMode = this.coordinatesMode;
  87023. serializationObject.useInGammaSpace = this.gammaSpace;
  87024. serializationObject.generateHarmonics = this._generateHarmonics;
  87025. serializationObject.customType = "BABYLON.HDRCubeTexture";
  87026. serializationObject.noMipmap = this._noMipmap;
  87027. serializationObject.isBlocking = this._isBlocking;
  87028. serializationObject.rotationY = this._rotationY;
  87029. return serializationObject;
  87030. };
  87031. HDRCubeTexture._facesMapping = [
  87032. "right",
  87033. "left",
  87034. "up",
  87035. "down",
  87036. "front",
  87037. "back"
  87038. ];
  87039. return HDRCubeTexture;
  87040. }(BABYLON.BaseTexture));
  87041. BABYLON.HDRCubeTexture = HDRCubeTexture;
  87042. })(BABYLON || (BABYLON = {}));
  87043. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  87044. var BABYLON;
  87045. (function (BABYLON) {
  87046. /**
  87047. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  87048. */
  87049. var PanoramaToCubeMapTools = /** @class */ (function () {
  87050. function PanoramaToCubeMapTools() {
  87051. }
  87052. /**
  87053. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  87054. *
  87055. * @param float32Array The source data.
  87056. * @param inputWidth The width of the input panorama.
  87057. * @param inputhHeight The height of the input panorama.
  87058. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  87059. * @return The cubemap data
  87060. */
  87061. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  87062. if (!float32Array) {
  87063. throw "ConvertPanoramaToCubemap: input cannot be null";
  87064. }
  87065. if (float32Array.length != inputWidth * inputHeight * 3) {
  87066. throw "ConvertPanoramaToCubemap: input size is wrong";
  87067. }
  87068. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  87069. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  87070. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  87071. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  87072. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  87073. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  87074. return {
  87075. front: textureFront,
  87076. back: textureBack,
  87077. left: textureLeft,
  87078. right: textureRight,
  87079. up: textureUp,
  87080. down: textureDown,
  87081. size: size,
  87082. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87083. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  87084. gammaSpace: false,
  87085. };
  87086. };
  87087. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  87088. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  87089. var textureArray = new Float32Array(buffer);
  87090. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  87091. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  87092. var dy = 1 / texSize;
  87093. var fy = 0;
  87094. for (var y = 0; y < texSize; y++) {
  87095. var xv1 = faceData[0];
  87096. var xv2 = faceData[2];
  87097. for (var x = 0; x < texSize; x++) {
  87098. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  87099. v.normalize();
  87100. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  87101. // 3 channels per pixels
  87102. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  87103. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  87104. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  87105. xv1 = xv1.add(rotDX1);
  87106. xv2 = xv2.add(rotDX2);
  87107. }
  87108. fy += dy;
  87109. }
  87110. return textureArray;
  87111. };
  87112. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  87113. var theta = Math.atan2(vDir.z, vDir.x);
  87114. var phi = Math.acos(vDir.y);
  87115. while (theta < -Math.PI)
  87116. theta += 2 * Math.PI;
  87117. while (theta > Math.PI)
  87118. theta -= 2 * Math.PI;
  87119. var dx = theta / Math.PI;
  87120. var dy = phi / Math.PI;
  87121. // recenter.
  87122. dx = dx * 0.5 + 0.5;
  87123. var px = Math.round(dx * inputWidth);
  87124. if (px < 0)
  87125. px = 0;
  87126. else if (px >= inputWidth)
  87127. px = inputWidth - 1;
  87128. var py = Math.round(dy * inputHeight);
  87129. if (py < 0)
  87130. py = 0;
  87131. else if (py >= inputHeight)
  87132. py = inputHeight - 1;
  87133. var inputY = (inputHeight - py - 1);
  87134. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  87135. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  87136. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  87137. return {
  87138. r: r,
  87139. g: g,
  87140. b: b
  87141. };
  87142. };
  87143. PanoramaToCubeMapTools.FACE_FRONT = [
  87144. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  87145. new BABYLON.Vector3(1.0, -1.0, -1.0),
  87146. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  87147. new BABYLON.Vector3(1.0, 1.0, -1.0)
  87148. ];
  87149. PanoramaToCubeMapTools.FACE_BACK = [
  87150. new BABYLON.Vector3(1.0, -1.0, 1.0),
  87151. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  87152. new BABYLON.Vector3(1.0, 1.0, 1.0),
  87153. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  87154. ];
  87155. PanoramaToCubeMapTools.FACE_RIGHT = [
  87156. new BABYLON.Vector3(1.0, -1.0, -1.0),
  87157. new BABYLON.Vector3(1.0, -1.0, 1.0),
  87158. new BABYLON.Vector3(1.0, 1.0, -1.0),
  87159. new BABYLON.Vector3(1.0, 1.0, 1.0)
  87160. ];
  87161. PanoramaToCubeMapTools.FACE_LEFT = [
  87162. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  87163. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  87164. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  87165. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  87166. ];
  87167. PanoramaToCubeMapTools.FACE_DOWN = [
  87168. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  87169. new BABYLON.Vector3(1.0, 1.0, -1.0),
  87170. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  87171. new BABYLON.Vector3(1.0, 1.0, 1.0)
  87172. ];
  87173. PanoramaToCubeMapTools.FACE_UP = [
  87174. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  87175. new BABYLON.Vector3(1.0, -1.0, 1.0),
  87176. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  87177. new BABYLON.Vector3(1.0, -1.0, -1.0)
  87178. ];
  87179. return PanoramaToCubeMapTools;
  87180. }());
  87181. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  87182. })(BABYLON || (BABYLON = {}));
  87183. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  87184. var BABYLON;
  87185. (function (BABYLON) {
  87186. var IndexedVector2 = /** @class */ (function (_super) {
  87187. __extends(IndexedVector2, _super);
  87188. function IndexedVector2(original, index) {
  87189. var _this = _super.call(this, original.x, original.y) || this;
  87190. _this.index = index;
  87191. return _this;
  87192. }
  87193. return IndexedVector2;
  87194. }(BABYLON.Vector2));
  87195. var PolygonPoints = /** @class */ (function () {
  87196. function PolygonPoints() {
  87197. this.elements = new Array();
  87198. }
  87199. PolygonPoints.prototype.add = function (originalPoints) {
  87200. var _this = this;
  87201. var result = new Array();
  87202. originalPoints.forEach(function (point) {
  87203. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  87204. var newPoint = new IndexedVector2(point, _this.elements.length);
  87205. result.push(newPoint);
  87206. _this.elements.push(newPoint);
  87207. }
  87208. });
  87209. return result;
  87210. };
  87211. PolygonPoints.prototype.computeBounds = function () {
  87212. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  87213. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  87214. this.elements.forEach(function (point) {
  87215. // x
  87216. if (point.x < lmin.x) {
  87217. lmin.x = point.x;
  87218. }
  87219. else if (point.x > lmax.x) {
  87220. lmax.x = point.x;
  87221. }
  87222. // y
  87223. if (point.y < lmin.y) {
  87224. lmin.y = point.y;
  87225. }
  87226. else if (point.y > lmax.y) {
  87227. lmax.y = point.y;
  87228. }
  87229. });
  87230. return {
  87231. min: lmin,
  87232. max: lmax,
  87233. width: lmax.x - lmin.x,
  87234. height: lmax.y - lmin.y
  87235. };
  87236. };
  87237. return PolygonPoints;
  87238. }());
  87239. var Polygon = /** @class */ (function () {
  87240. function Polygon() {
  87241. }
  87242. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  87243. return [
  87244. new BABYLON.Vector2(xmin, ymin),
  87245. new BABYLON.Vector2(xmax, ymin),
  87246. new BABYLON.Vector2(xmax, ymax),
  87247. new BABYLON.Vector2(xmin, ymax)
  87248. ];
  87249. };
  87250. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  87251. if (cx === void 0) { cx = 0; }
  87252. if (cy === void 0) { cy = 0; }
  87253. if (numberOfSides === void 0) { numberOfSides = 32; }
  87254. var result = new Array();
  87255. var angle = 0;
  87256. var increment = (Math.PI * 2) / numberOfSides;
  87257. for (var i = 0; i < numberOfSides; i++) {
  87258. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  87259. angle -= increment;
  87260. }
  87261. return result;
  87262. };
  87263. Polygon.Parse = function (input) {
  87264. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  87265. var i, result = [];
  87266. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  87267. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  87268. }
  87269. return result;
  87270. };
  87271. Polygon.StartingAt = function (x, y) {
  87272. return BABYLON.Path2.StartingAt(x, y);
  87273. };
  87274. return Polygon;
  87275. }());
  87276. BABYLON.Polygon = Polygon;
  87277. var PolygonMeshBuilder = /** @class */ (function () {
  87278. function PolygonMeshBuilder(name, contours, scene) {
  87279. this._points = new PolygonPoints();
  87280. this._outlinepoints = new PolygonPoints();
  87281. this._holes = new Array();
  87282. this._epoints = new Array();
  87283. this._eholes = new Array();
  87284. this._name = name;
  87285. this._scene = scene;
  87286. var points;
  87287. if (contours instanceof BABYLON.Path2) {
  87288. points = contours.getPoints();
  87289. }
  87290. else {
  87291. points = contours;
  87292. }
  87293. this._addToepoint(points);
  87294. this._points.add(points);
  87295. this._outlinepoints.add(points);
  87296. if (typeof earcut === 'undefined') {
  87297. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  87298. }
  87299. }
  87300. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  87301. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  87302. var p = points_1[_i];
  87303. this._epoints.push(p.x, p.y);
  87304. }
  87305. };
  87306. PolygonMeshBuilder.prototype.addHole = function (hole) {
  87307. this._points.add(hole);
  87308. var holepoints = new PolygonPoints();
  87309. holepoints.add(hole);
  87310. this._holes.push(holepoints);
  87311. this._eholes.push(this._epoints.length / 2);
  87312. this._addToepoint(hole);
  87313. return this;
  87314. };
  87315. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  87316. var _this = this;
  87317. if (updatable === void 0) { updatable = false; }
  87318. if (depth === void 0) { depth = 0; }
  87319. var result = new BABYLON.Mesh(this._name, this._scene);
  87320. var normals = new Array();
  87321. var positions = new Array();
  87322. var uvs = new Array();
  87323. var bounds = this._points.computeBounds();
  87324. this._points.elements.forEach(function (p) {
  87325. normals.push(0, 1.0, 0);
  87326. positions.push(p.x, 0, p.y);
  87327. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  87328. });
  87329. var indices = new Array();
  87330. var res = earcut(this._epoints, this._eholes, 2);
  87331. for (var i = 0; i < res.length; i++) {
  87332. indices.push(res[i]);
  87333. }
  87334. if (depth > 0) {
  87335. var positionscount = (positions.length / 3); //get the current pointcount
  87336. this._points.elements.forEach(function (p) {
  87337. normals.push(0, -1.0, 0);
  87338. positions.push(p.x, -depth, p.y);
  87339. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  87340. });
  87341. var totalCount = indices.length;
  87342. for (var i = 0; i < totalCount; i += 3) {
  87343. var i0 = indices[i + 0];
  87344. var i1 = indices[i + 1];
  87345. var i2 = indices[i + 2];
  87346. indices.push(i2 + positionscount);
  87347. indices.push(i1 + positionscount);
  87348. indices.push(i0 + positionscount);
  87349. }
  87350. //Add the sides
  87351. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  87352. this._holes.forEach(function (hole) {
  87353. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  87354. });
  87355. }
  87356. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  87357. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  87358. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  87359. result.setIndices(indices);
  87360. return result;
  87361. };
  87362. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  87363. var StartIndex = positions.length / 3;
  87364. var ulength = 0;
  87365. for (var i = 0; i < points.elements.length; i++) {
  87366. var p = points.elements[i];
  87367. var p1;
  87368. if ((i + 1) > points.elements.length - 1) {
  87369. p1 = points.elements[0];
  87370. }
  87371. else {
  87372. p1 = points.elements[i + 1];
  87373. }
  87374. positions.push(p.x, 0, p.y);
  87375. positions.push(p.x, -depth, p.y);
  87376. positions.push(p1.x, 0, p1.y);
  87377. positions.push(p1.x, -depth, p1.y);
  87378. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  87379. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  87380. var v3 = v2.subtract(v1);
  87381. var v4 = new BABYLON.Vector3(0, 1, 0);
  87382. var vn = BABYLON.Vector3.Cross(v3, v4);
  87383. vn = vn.normalize();
  87384. uvs.push(ulength / bounds.width, 0);
  87385. uvs.push(ulength / bounds.width, 1);
  87386. ulength += v3.length();
  87387. uvs.push((ulength / bounds.width), 0);
  87388. uvs.push((ulength / bounds.width), 1);
  87389. if (!flip) {
  87390. normals.push(-vn.x, -vn.y, -vn.z);
  87391. normals.push(-vn.x, -vn.y, -vn.z);
  87392. normals.push(-vn.x, -vn.y, -vn.z);
  87393. normals.push(-vn.x, -vn.y, -vn.z);
  87394. indices.push(StartIndex);
  87395. indices.push(StartIndex + 1);
  87396. indices.push(StartIndex + 2);
  87397. indices.push(StartIndex + 1);
  87398. indices.push(StartIndex + 3);
  87399. indices.push(StartIndex + 2);
  87400. }
  87401. else {
  87402. normals.push(vn.x, vn.y, vn.z);
  87403. normals.push(vn.x, vn.y, vn.z);
  87404. normals.push(vn.x, vn.y, vn.z);
  87405. normals.push(vn.x, vn.y, vn.z);
  87406. indices.push(StartIndex);
  87407. indices.push(StartIndex + 2);
  87408. indices.push(StartIndex + 1);
  87409. indices.push(StartIndex + 1);
  87410. indices.push(StartIndex + 2);
  87411. indices.push(StartIndex + 3);
  87412. }
  87413. StartIndex += 4;
  87414. }
  87415. ;
  87416. };
  87417. return PolygonMeshBuilder;
  87418. }());
  87419. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  87420. })(BABYLON || (BABYLON = {}));
  87421. //# sourceMappingURL=babylon.polygonMesh.js.map
  87422. var BABYLON;
  87423. (function (BABYLON) {
  87424. // Unique ID when we import meshes from Babylon to CSG
  87425. var currentCSGMeshId = 0;
  87426. // # class Vertex
  87427. // Represents a vertex of a polygon. Use your own vertex class instead of this
  87428. // one to provide additional features like texture coordinates and vertex
  87429. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  87430. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  87431. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  87432. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  87433. // is not used anywhere else.
  87434. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  87435. var Vertex = /** @class */ (function () {
  87436. function Vertex(pos, normal, uv) {
  87437. this.pos = pos;
  87438. this.normal = normal;
  87439. this.uv = uv;
  87440. }
  87441. Vertex.prototype.clone = function () {
  87442. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  87443. };
  87444. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  87445. // orientation of a polygon is flipped.
  87446. Vertex.prototype.flip = function () {
  87447. this.normal = this.normal.scale(-1);
  87448. };
  87449. // Create a new vertex between this vertex and `other` by linearly
  87450. // interpolating all properties using a parameter of `t`. Subclasses should
  87451. // override this to interpolate additional properties.
  87452. Vertex.prototype.interpolate = function (other, t) {
  87453. 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));
  87454. };
  87455. return Vertex;
  87456. }());
  87457. // # class Plane
  87458. // Represents a plane in 3D space.
  87459. var Plane = /** @class */ (function () {
  87460. function Plane(normal, w) {
  87461. this.normal = normal;
  87462. this.w = w;
  87463. }
  87464. Plane.FromPoints = function (a, b, c) {
  87465. var v0 = c.subtract(a);
  87466. var v1 = b.subtract(a);
  87467. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  87468. return null;
  87469. }
  87470. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  87471. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  87472. };
  87473. Plane.prototype.clone = function () {
  87474. return new Plane(this.normal.clone(), this.w);
  87475. };
  87476. Plane.prototype.flip = function () {
  87477. this.normal.scaleInPlace(-1);
  87478. this.w = -this.w;
  87479. };
  87480. // Split `polygon` by this plane if needed, then put the polygon or polygon
  87481. // fragments in the appropriate lists. Coplanar polygons go into either
  87482. // `coplanarFront` or `coplanarBack` depending on their orientation with
  87483. // respect to this plane. Polygons in front or in back of this plane go into
  87484. // either `front` or `back`.
  87485. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  87486. var COPLANAR = 0;
  87487. var FRONT = 1;
  87488. var BACK = 2;
  87489. var SPANNING = 3;
  87490. // Classify each point as well as the entire polygon into one of the above
  87491. // four classes.
  87492. var polygonType = 0;
  87493. var types = [];
  87494. var i;
  87495. var t;
  87496. for (i = 0; i < polygon.vertices.length; i++) {
  87497. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  87498. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  87499. polygonType |= type;
  87500. types.push(type);
  87501. }
  87502. // Put the polygon in the correct list, splitting it when necessary.
  87503. switch (polygonType) {
  87504. case COPLANAR:
  87505. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  87506. break;
  87507. case FRONT:
  87508. front.push(polygon);
  87509. break;
  87510. case BACK:
  87511. back.push(polygon);
  87512. break;
  87513. case SPANNING:
  87514. var f = [], b = [];
  87515. for (i = 0; i < polygon.vertices.length; i++) {
  87516. var j = (i + 1) % polygon.vertices.length;
  87517. var ti = types[i], tj = types[j];
  87518. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  87519. if (ti !== BACK)
  87520. f.push(vi);
  87521. if (ti !== FRONT)
  87522. b.push(ti !== BACK ? vi.clone() : vi);
  87523. if ((ti | tj) === SPANNING) {
  87524. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  87525. var v = vi.interpolate(vj, t);
  87526. f.push(v);
  87527. b.push(v.clone());
  87528. }
  87529. }
  87530. var poly;
  87531. if (f.length >= 3) {
  87532. poly = new Polygon(f, polygon.shared);
  87533. if (poly.plane)
  87534. front.push(poly);
  87535. }
  87536. if (b.length >= 3) {
  87537. poly = new Polygon(b, polygon.shared);
  87538. if (poly.plane)
  87539. back.push(poly);
  87540. }
  87541. break;
  87542. }
  87543. };
  87544. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  87545. // point is on the plane.
  87546. Plane.EPSILON = 1e-5;
  87547. return Plane;
  87548. }());
  87549. // # class Polygon
  87550. // Represents a convex polygon. The vertices used to initialize a polygon must
  87551. // be coplanar and form a convex loop.
  87552. //
  87553. // Each convex polygon has a `shared` property, which is shared between all
  87554. // polygons that are clones of each other or were split from the same polygon.
  87555. // This can be used to define per-polygon properties (such as surface color).
  87556. var Polygon = /** @class */ (function () {
  87557. function Polygon(vertices, shared) {
  87558. this.vertices = vertices;
  87559. this.shared = shared;
  87560. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  87561. }
  87562. Polygon.prototype.clone = function () {
  87563. var vertices = this.vertices.map(function (v) { return v.clone(); });
  87564. return new Polygon(vertices, this.shared);
  87565. };
  87566. Polygon.prototype.flip = function () {
  87567. this.vertices.reverse().map(function (v) { v.flip(); });
  87568. this.plane.flip();
  87569. };
  87570. return Polygon;
  87571. }());
  87572. // # class Node
  87573. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  87574. // by picking a polygon to split along. That polygon (and all other coplanar
  87575. // polygons) are added directly to that node and the other polygons are added to
  87576. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  87577. // no distinction between internal and leaf nodes.
  87578. var Node = /** @class */ (function () {
  87579. function Node(polygons) {
  87580. this.plane = null;
  87581. this.front = null;
  87582. this.back = null;
  87583. this.polygons = new Array();
  87584. if (polygons) {
  87585. this.build(polygons);
  87586. }
  87587. }
  87588. Node.prototype.clone = function () {
  87589. var node = new Node();
  87590. node.plane = this.plane && this.plane.clone();
  87591. node.front = this.front && this.front.clone();
  87592. node.back = this.back && this.back.clone();
  87593. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  87594. return node;
  87595. };
  87596. // Convert solid space to empty space and empty space to solid space.
  87597. Node.prototype.invert = function () {
  87598. for (var i = 0; i < this.polygons.length; i++) {
  87599. this.polygons[i].flip();
  87600. }
  87601. if (this.plane) {
  87602. this.plane.flip();
  87603. }
  87604. if (this.front) {
  87605. this.front.invert();
  87606. }
  87607. if (this.back) {
  87608. this.back.invert();
  87609. }
  87610. var temp = this.front;
  87611. this.front = this.back;
  87612. this.back = temp;
  87613. };
  87614. // Recursively remove all polygons in `polygons` that are inside this BSP
  87615. // tree.
  87616. Node.prototype.clipPolygons = function (polygons) {
  87617. if (!this.plane)
  87618. return polygons.slice();
  87619. var front = new Array(), back = new Array();
  87620. for (var i = 0; i < polygons.length; i++) {
  87621. this.plane.splitPolygon(polygons[i], front, back, front, back);
  87622. }
  87623. if (this.front) {
  87624. front = this.front.clipPolygons(front);
  87625. }
  87626. if (this.back) {
  87627. back = this.back.clipPolygons(back);
  87628. }
  87629. else {
  87630. back = [];
  87631. }
  87632. return front.concat(back);
  87633. };
  87634. // Remove all polygons in this BSP tree that are inside the other BSP tree
  87635. // `bsp`.
  87636. Node.prototype.clipTo = function (bsp) {
  87637. this.polygons = bsp.clipPolygons(this.polygons);
  87638. if (this.front)
  87639. this.front.clipTo(bsp);
  87640. if (this.back)
  87641. this.back.clipTo(bsp);
  87642. };
  87643. // Return a list of all polygons in this BSP tree.
  87644. Node.prototype.allPolygons = function () {
  87645. var polygons = this.polygons.slice();
  87646. if (this.front)
  87647. polygons = polygons.concat(this.front.allPolygons());
  87648. if (this.back)
  87649. polygons = polygons.concat(this.back.allPolygons());
  87650. return polygons;
  87651. };
  87652. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  87653. // new polygons are filtered down to the bottom of the tree and become new
  87654. // nodes there. Each set of polygons is partitioned using the first polygon
  87655. // (no heuristic is used to pick a good split).
  87656. Node.prototype.build = function (polygons) {
  87657. if (!polygons.length)
  87658. return;
  87659. if (!this.plane)
  87660. this.plane = polygons[0].plane.clone();
  87661. var front = new Array(), back = new Array();
  87662. for (var i = 0; i < polygons.length; i++) {
  87663. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  87664. }
  87665. if (front.length) {
  87666. if (!this.front)
  87667. this.front = new Node();
  87668. this.front.build(front);
  87669. }
  87670. if (back.length) {
  87671. if (!this.back)
  87672. this.back = new Node();
  87673. this.back.build(back);
  87674. }
  87675. };
  87676. return Node;
  87677. }());
  87678. var CSG = /** @class */ (function () {
  87679. function CSG() {
  87680. this.polygons = new Array();
  87681. }
  87682. // Convert BABYLON.Mesh to BABYLON.CSG
  87683. CSG.FromMesh = function (mesh) {
  87684. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  87685. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  87686. if (mesh instanceof BABYLON.Mesh) {
  87687. mesh.computeWorldMatrix(true);
  87688. matrix = mesh.getWorldMatrix();
  87689. meshPosition = mesh.position.clone();
  87690. meshRotation = mesh.rotation.clone();
  87691. if (mesh.rotationQuaternion) {
  87692. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  87693. }
  87694. meshScaling = mesh.scaling.clone();
  87695. }
  87696. else {
  87697. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  87698. }
  87699. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  87700. var subMeshes = mesh.subMeshes;
  87701. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  87702. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  87703. vertices = [];
  87704. for (var j = 0; j < 3; j++) {
  87705. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  87706. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  87707. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  87708. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  87709. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  87710. vertex = new Vertex(position, normal, uv);
  87711. vertices.push(vertex);
  87712. }
  87713. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  87714. // To handle the case of degenerated triangle
  87715. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  87716. if (polygon.plane)
  87717. polygons.push(polygon);
  87718. }
  87719. }
  87720. var csg = CSG.FromPolygons(polygons);
  87721. csg.matrix = matrix;
  87722. csg.position = meshPosition;
  87723. csg.rotation = meshRotation;
  87724. csg.scaling = meshScaling;
  87725. csg.rotationQuaternion = meshRotationQuaternion;
  87726. currentCSGMeshId++;
  87727. return csg;
  87728. };
  87729. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  87730. CSG.FromPolygons = function (polygons) {
  87731. var csg = new CSG();
  87732. csg.polygons = polygons;
  87733. return csg;
  87734. };
  87735. CSG.prototype.clone = function () {
  87736. var csg = new CSG();
  87737. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  87738. csg.copyTransformAttributes(this);
  87739. return csg;
  87740. };
  87741. CSG.prototype.union = function (csg) {
  87742. var a = new Node(this.clone().polygons);
  87743. var b = new Node(csg.clone().polygons);
  87744. a.clipTo(b);
  87745. b.clipTo(a);
  87746. b.invert();
  87747. b.clipTo(a);
  87748. b.invert();
  87749. a.build(b.allPolygons());
  87750. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87751. };
  87752. CSG.prototype.unionInPlace = function (csg) {
  87753. var a = new Node(this.polygons);
  87754. var b = new Node(csg.polygons);
  87755. a.clipTo(b);
  87756. b.clipTo(a);
  87757. b.invert();
  87758. b.clipTo(a);
  87759. b.invert();
  87760. a.build(b.allPolygons());
  87761. this.polygons = a.allPolygons();
  87762. };
  87763. CSG.prototype.subtract = function (csg) {
  87764. var a = new Node(this.clone().polygons);
  87765. var b = new Node(csg.clone().polygons);
  87766. a.invert();
  87767. a.clipTo(b);
  87768. b.clipTo(a);
  87769. b.invert();
  87770. b.clipTo(a);
  87771. b.invert();
  87772. a.build(b.allPolygons());
  87773. a.invert();
  87774. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87775. };
  87776. CSG.prototype.subtractInPlace = function (csg) {
  87777. var a = new Node(this.polygons);
  87778. var b = new Node(csg.polygons);
  87779. a.invert();
  87780. a.clipTo(b);
  87781. b.clipTo(a);
  87782. b.invert();
  87783. b.clipTo(a);
  87784. b.invert();
  87785. a.build(b.allPolygons());
  87786. a.invert();
  87787. this.polygons = a.allPolygons();
  87788. };
  87789. CSG.prototype.intersect = function (csg) {
  87790. var a = new Node(this.clone().polygons);
  87791. var b = new Node(csg.clone().polygons);
  87792. a.invert();
  87793. b.clipTo(a);
  87794. b.invert();
  87795. a.clipTo(b);
  87796. b.clipTo(a);
  87797. a.build(b.allPolygons());
  87798. a.invert();
  87799. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87800. };
  87801. CSG.prototype.intersectInPlace = function (csg) {
  87802. var a = new Node(this.polygons);
  87803. var b = new Node(csg.polygons);
  87804. a.invert();
  87805. b.clipTo(a);
  87806. b.invert();
  87807. a.clipTo(b);
  87808. b.clipTo(a);
  87809. a.build(b.allPolygons());
  87810. a.invert();
  87811. this.polygons = a.allPolygons();
  87812. };
  87813. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  87814. // not modified.
  87815. CSG.prototype.inverse = function () {
  87816. var csg = this.clone();
  87817. csg.inverseInPlace();
  87818. return csg;
  87819. };
  87820. CSG.prototype.inverseInPlace = function () {
  87821. this.polygons.map(function (p) { p.flip(); });
  87822. };
  87823. // This is used to keep meshes transformations so they can be restored
  87824. // when we build back a Babylon Mesh
  87825. // NB : All CSG operations are performed in world coordinates
  87826. CSG.prototype.copyTransformAttributes = function (csg) {
  87827. this.matrix = csg.matrix;
  87828. this.position = csg.position;
  87829. this.rotation = csg.rotation;
  87830. this.scaling = csg.scaling;
  87831. this.rotationQuaternion = csg.rotationQuaternion;
  87832. return this;
  87833. };
  87834. // Build Raw mesh from CSG
  87835. // Coordinates here are in world space
  87836. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  87837. var matrix = this.matrix.clone();
  87838. matrix.invert();
  87839. 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;
  87840. if (keepSubMeshes) {
  87841. // Sort Polygons, since subMeshes are indices range
  87842. polygons.sort(function (a, b) {
  87843. if (a.shared.meshId === b.shared.meshId) {
  87844. return a.shared.subMeshId - b.shared.subMeshId;
  87845. }
  87846. else {
  87847. return a.shared.meshId - b.shared.meshId;
  87848. }
  87849. });
  87850. }
  87851. for (var i = 0, il = polygons.length; i < il; i++) {
  87852. polygon = polygons[i];
  87853. // Building SubMeshes
  87854. if (!subMesh_dict[polygon.shared.meshId]) {
  87855. subMesh_dict[polygon.shared.meshId] = {};
  87856. }
  87857. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  87858. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  87859. indexStart: +Infinity,
  87860. indexEnd: -Infinity,
  87861. materialIndex: polygon.shared.materialIndex
  87862. };
  87863. }
  87864. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  87865. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  87866. polygonIndices[0] = 0;
  87867. polygonIndices[1] = j - 1;
  87868. polygonIndices[2] = j;
  87869. for (var k = 0; k < 3; k++) {
  87870. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  87871. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  87872. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  87873. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  87874. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  87875. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  87876. // Check if 2 points can be merged
  87877. if (!(typeof vertex_idx !== 'undefined' &&
  87878. normals[vertex_idx * 3] === localNormal.x &&
  87879. normals[vertex_idx * 3 + 1] === localNormal.y &&
  87880. normals[vertex_idx * 3 + 2] === localNormal.z &&
  87881. uvs[vertex_idx * 2] === uv.x &&
  87882. uvs[vertex_idx * 2 + 1] === uv.y)) {
  87883. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  87884. uvs.push(uv.x, uv.y);
  87885. normals.push(normal.x, normal.y, normal.z);
  87886. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  87887. }
  87888. indices.push(vertex_idx);
  87889. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  87890. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  87891. currentIndex++;
  87892. }
  87893. }
  87894. }
  87895. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  87896. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  87897. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  87898. mesh.setIndices(indices, null);
  87899. if (keepSubMeshes) {
  87900. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  87901. var materialIndexOffset = 0, materialMaxIndex;
  87902. mesh.subMeshes = new Array();
  87903. for (var m in subMesh_dict) {
  87904. materialMaxIndex = -1;
  87905. for (var sm in subMesh_dict[m]) {
  87906. subMesh_obj = subMesh_dict[m][sm];
  87907. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  87908. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  87909. }
  87910. materialIndexOffset += ++materialMaxIndex;
  87911. }
  87912. }
  87913. return mesh;
  87914. };
  87915. // Build Mesh from CSG taking material and transforms into account
  87916. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  87917. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  87918. mesh.material = material;
  87919. mesh.position.copyFrom(this.position);
  87920. mesh.rotation.copyFrom(this.rotation);
  87921. if (this.rotationQuaternion) {
  87922. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  87923. }
  87924. mesh.scaling.copyFrom(this.scaling);
  87925. mesh.computeWorldMatrix(true);
  87926. return mesh;
  87927. };
  87928. return CSG;
  87929. }());
  87930. BABYLON.CSG = CSG;
  87931. })(BABYLON || (BABYLON = {}));
  87932. //# sourceMappingURL=babylon.csg.js.map
  87933. var BABYLON;
  87934. (function (BABYLON) {
  87935. var LensFlare = /** @class */ (function () {
  87936. function LensFlare(size, position, color, imgUrl, system) {
  87937. this.size = size;
  87938. this.position = position;
  87939. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  87940. this.color = color || new BABYLON.Color3(1, 1, 1);
  87941. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  87942. this._system = system;
  87943. system.lensFlares.push(this);
  87944. }
  87945. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  87946. return new LensFlare(size, position, color, imgUrl, system);
  87947. };
  87948. LensFlare.prototype.dispose = function () {
  87949. if (this.texture) {
  87950. this.texture.dispose();
  87951. }
  87952. // Remove from scene
  87953. var index = this._system.lensFlares.indexOf(this);
  87954. this._system.lensFlares.splice(index, 1);
  87955. };
  87956. ;
  87957. return LensFlare;
  87958. }());
  87959. BABYLON.LensFlare = LensFlare;
  87960. })(BABYLON || (BABYLON = {}));
  87961. //# sourceMappingURL=babylon.lensFlare.js.map
  87962. var BABYLON;
  87963. (function (BABYLON) {
  87964. // Adds the parser to the scene parsers.
  87965. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  87966. // Lens flares
  87967. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  87968. if (!container.lensFlareSystems) {
  87969. container.lensFlareSystems = new Array();
  87970. }
  87971. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  87972. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  87973. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  87974. container.lensFlareSystems.push(lf);
  87975. }
  87976. }
  87977. });
  87978. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  87979. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  87980. if (this.lensFlareSystems[index].name === name) {
  87981. return this.lensFlareSystems[index];
  87982. }
  87983. }
  87984. return null;
  87985. };
  87986. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  87987. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  87988. if (this.lensFlareSystems[index].id === id) {
  87989. return this.lensFlareSystems[index];
  87990. }
  87991. }
  87992. return null;
  87993. };
  87994. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  87995. var index = this.lensFlareSystems.indexOf(toRemove);
  87996. if (index !== -1) {
  87997. this.lensFlareSystems.splice(index, 1);
  87998. }
  87999. return index;
  88000. };
  88001. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  88002. this.lensFlareSystems.push(newLensFlareSystem);
  88003. };
  88004. /**
  88005. * Defines the lens flare scene component responsible to manage any lens flares
  88006. * in a given scene.
  88007. */
  88008. var LensFlareSystemSceneComponent = /** @class */ (function () {
  88009. /**
  88010. * Creates a new instance of the component for the given scene
  88011. * @param scene Defines the scene to register the component in
  88012. */
  88013. function LensFlareSystemSceneComponent(scene) {
  88014. /**
  88015. * The component name helpfull to identify the component in the list of scene components.
  88016. */
  88017. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  88018. this.scene = scene;
  88019. scene.lensFlareSystems = new Array();
  88020. }
  88021. /**
  88022. * Registers the component in a given scene
  88023. */
  88024. LensFlareSystemSceneComponent.prototype.register = function () {
  88025. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  88026. };
  88027. /**
  88028. * Rebuilds the elements related to this component in case of
  88029. * context lost for instance.
  88030. */
  88031. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  88032. // Nothing to do for lens flare
  88033. };
  88034. /**
  88035. * Adds all the element from the container to the scene
  88036. * @param container the container holding the elements
  88037. */
  88038. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  88039. var _this = this;
  88040. if (!container.lensFlareSystems) {
  88041. return;
  88042. }
  88043. container.lensFlareSystems.forEach(function (o) {
  88044. _this.scene.addLensFlareSystem(o);
  88045. });
  88046. };
  88047. /**
  88048. * Removes all the elements in the container from the scene
  88049. * @param container contains the elements to remove
  88050. */
  88051. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  88052. var _this = this;
  88053. if (!container.lensFlareSystems) {
  88054. return;
  88055. }
  88056. container.lensFlareSystems.forEach(function (o) {
  88057. _this.scene.removeLensFlareSystem(o);
  88058. });
  88059. };
  88060. /**
  88061. * Serializes the component data to the specified json object
  88062. * @param serializationObject The object to serialize to
  88063. */
  88064. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  88065. // Lens flares
  88066. serializationObject.lensFlareSystems = [];
  88067. var lensFlareSystems = this.scene.lensFlareSystems;
  88068. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  88069. var lensFlareSystem = lensFlareSystems_1[_i];
  88070. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  88071. }
  88072. };
  88073. /**
  88074. * Disposes the component and the associated ressources.
  88075. */
  88076. LensFlareSystemSceneComponent.prototype.dispose = function () {
  88077. var lensFlareSystems = this.scene.lensFlareSystems;
  88078. while (lensFlareSystems.length) {
  88079. lensFlareSystems[0].dispose();
  88080. }
  88081. };
  88082. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  88083. // Lens flares
  88084. if (this.scene.lensFlaresEnabled) {
  88085. var lensFlareSystems = this.scene.lensFlareSystems;
  88086. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  88087. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  88088. var lensFlareSystem = lensFlareSystems_2[_i];
  88089. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  88090. lensFlareSystem.render();
  88091. }
  88092. }
  88093. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  88094. }
  88095. };
  88096. return LensFlareSystemSceneComponent;
  88097. }());
  88098. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  88099. })(BABYLON || (BABYLON = {}));
  88100. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  88101. var BABYLON;
  88102. (function (BABYLON) {
  88103. var LensFlareSystem = /** @class */ (function () {
  88104. function LensFlareSystem(name, emitter, scene) {
  88105. this.name = name;
  88106. this.lensFlares = new Array();
  88107. this.borderLimit = 300;
  88108. this.viewportBorder = 0;
  88109. this.layerMask = 0x0FFFFFFF;
  88110. this._vertexBuffers = {};
  88111. this._isEnabled = true;
  88112. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88113. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  88114. if (!component) {
  88115. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  88116. scene._addComponent(component);
  88117. }
  88118. this._emitter = emitter;
  88119. this.id = name;
  88120. scene.lensFlareSystems.push(this);
  88121. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  88122. var engine = scene.getEngine();
  88123. // VBO
  88124. var vertices = [];
  88125. vertices.push(1, 1);
  88126. vertices.push(-1, 1);
  88127. vertices.push(-1, -1);
  88128. vertices.push(1, -1);
  88129. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88130. // Indices
  88131. var indices = [];
  88132. indices.push(0);
  88133. indices.push(1);
  88134. indices.push(2);
  88135. indices.push(0);
  88136. indices.push(2);
  88137. indices.push(3);
  88138. this._indexBuffer = engine.createIndexBuffer(indices);
  88139. // Effects
  88140. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  88141. }
  88142. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  88143. get: function () {
  88144. return this._isEnabled;
  88145. },
  88146. set: function (value) {
  88147. this._isEnabled = value;
  88148. },
  88149. enumerable: true,
  88150. configurable: true
  88151. });
  88152. LensFlareSystem.prototype.getScene = function () {
  88153. return this._scene;
  88154. };
  88155. LensFlareSystem.prototype.getEmitter = function () {
  88156. return this._emitter;
  88157. };
  88158. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  88159. this._emitter = newEmitter;
  88160. };
  88161. LensFlareSystem.prototype.getEmitterPosition = function () {
  88162. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  88163. };
  88164. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  88165. var position = this.getEmitterPosition();
  88166. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  88167. this._positionX = position.x;
  88168. this._positionY = position.y;
  88169. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  88170. if (this.viewportBorder > 0) {
  88171. globalViewport.x -= this.viewportBorder;
  88172. globalViewport.y -= this.viewportBorder;
  88173. globalViewport.width += this.viewportBorder * 2;
  88174. globalViewport.height += this.viewportBorder * 2;
  88175. position.x += this.viewportBorder;
  88176. position.y += this.viewportBorder;
  88177. this._positionX += this.viewportBorder;
  88178. this._positionY += this.viewportBorder;
  88179. }
  88180. if (position.z > 0) {
  88181. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  88182. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  88183. return true;
  88184. }
  88185. return true;
  88186. }
  88187. return false;
  88188. };
  88189. /** @hidden */
  88190. LensFlareSystem.prototype._isVisible = function () {
  88191. if (!this._isEnabled || !this._scene.activeCamera) {
  88192. return false;
  88193. }
  88194. var emitterPosition = this.getEmitterPosition();
  88195. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  88196. var distance = direction.length();
  88197. direction.normalize();
  88198. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  88199. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  88200. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  88201. };
  88202. LensFlareSystem.prototype.render = function () {
  88203. if (!this._effect.isReady() || !this._scene.activeCamera)
  88204. return false;
  88205. var engine = this._scene.getEngine();
  88206. var viewport = this._scene.activeCamera.viewport;
  88207. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  88208. // Position
  88209. if (!this.computeEffectivePosition(globalViewport)) {
  88210. return false;
  88211. }
  88212. // Visibility
  88213. if (!this._isVisible()) {
  88214. return false;
  88215. }
  88216. // Intensity
  88217. var awayX;
  88218. var awayY;
  88219. if (this._positionX < this.borderLimit + globalViewport.x) {
  88220. awayX = this.borderLimit + globalViewport.x - this._positionX;
  88221. }
  88222. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  88223. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  88224. }
  88225. else {
  88226. awayX = 0;
  88227. }
  88228. if (this._positionY < this.borderLimit + globalViewport.y) {
  88229. awayY = this.borderLimit + globalViewport.y - this._positionY;
  88230. }
  88231. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  88232. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  88233. }
  88234. else {
  88235. awayY = 0;
  88236. }
  88237. var away = (awayX > awayY) ? awayX : awayY;
  88238. away -= this.viewportBorder;
  88239. if (away > this.borderLimit) {
  88240. away = this.borderLimit;
  88241. }
  88242. var intensity = 1.0 - (away / this.borderLimit);
  88243. if (intensity < 0) {
  88244. return false;
  88245. }
  88246. if (intensity > 1.0) {
  88247. intensity = 1.0;
  88248. }
  88249. if (this.viewportBorder > 0) {
  88250. globalViewport.x += this.viewportBorder;
  88251. globalViewport.y += this.viewportBorder;
  88252. globalViewport.width -= this.viewportBorder * 2;
  88253. globalViewport.height -= this.viewportBorder * 2;
  88254. this._positionX -= this.viewportBorder;
  88255. this._positionY -= this.viewportBorder;
  88256. }
  88257. // Position
  88258. var centerX = globalViewport.x + globalViewport.width / 2;
  88259. var centerY = globalViewport.y + globalViewport.height / 2;
  88260. var distX = centerX - this._positionX;
  88261. var distY = centerY - this._positionY;
  88262. // Effects
  88263. engine.enableEffect(this._effect);
  88264. engine.setState(false);
  88265. engine.setDepthBuffer(false);
  88266. // VBOs
  88267. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  88268. // Flares
  88269. for (var index = 0; index < this.lensFlares.length; index++) {
  88270. var flare = this.lensFlares[index];
  88271. engine.setAlphaMode(flare.alphaMode);
  88272. var x = centerX - (distX * flare.position);
  88273. var y = centerY - (distY * flare.position);
  88274. var cw = flare.size;
  88275. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  88276. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  88277. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  88278. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  88279. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  88280. // Texture
  88281. this._effect.setTexture("textureSampler", flare.texture);
  88282. // Color
  88283. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  88284. // Draw order
  88285. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88286. }
  88287. engine.setDepthBuffer(true);
  88288. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88289. return true;
  88290. };
  88291. LensFlareSystem.prototype.dispose = function () {
  88292. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88293. if (vertexBuffer) {
  88294. vertexBuffer.dispose();
  88295. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88296. }
  88297. if (this._indexBuffer) {
  88298. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88299. this._indexBuffer = null;
  88300. }
  88301. while (this.lensFlares.length) {
  88302. this.lensFlares[0].dispose();
  88303. }
  88304. // Remove from scene
  88305. var index = this._scene.lensFlareSystems.indexOf(this);
  88306. this._scene.lensFlareSystems.splice(index, 1);
  88307. };
  88308. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  88309. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  88310. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  88311. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  88312. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  88313. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  88314. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  88315. var parsedFlare = parsedLensFlareSystem.flares[index];
  88316. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  88317. }
  88318. return lensFlareSystem;
  88319. };
  88320. LensFlareSystem.prototype.serialize = function () {
  88321. var serializationObject = {};
  88322. serializationObject.id = this.id;
  88323. serializationObject.name = this.name;
  88324. serializationObject.emitterId = this.getEmitter().id;
  88325. serializationObject.borderLimit = this.borderLimit;
  88326. serializationObject.flares = [];
  88327. for (var index = 0; index < this.lensFlares.length; index++) {
  88328. var flare = this.lensFlares[index];
  88329. serializationObject.flares.push({
  88330. size: flare.size,
  88331. position: flare.position,
  88332. color: flare.color.asArray(),
  88333. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  88334. });
  88335. }
  88336. return serializationObject;
  88337. };
  88338. return LensFlareSystem;
  88339. }());
  88340. BABYLON.LensFlareSystem = LensFlareSystem;
  88341. })(BABYLON || (BABYLON = {}));
  88342. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  88343. var BABYLON;
  88344. (function (BABYLON) {
  88345. /**
  88346. * This is a holder class for the physics joint created by the physics plugin.
  88347. * It holds a set of functions to control the underlying joint.
  88348. */
  88349. var PhysicsJoint = /** @class */ (function () {
  88350. function PhysicsJoint(type, jointData) {
  88351. this.type = type;
  88352. this.jointData = jointData;
  88353. jointData.nativeParams = jointData.nativeParams || {};
  88354. }
  88355. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  88356. get: function () {
  88357. return this._physicsJoint;
  88358. },
  88359. set: function (newJoint) {
  88360. if (this._physicsJoint) {
  88361. //remove from the wolrd
  88362. }
  88363. this._physicsJoint = newJoint;
  88364. },
  88365. enumerable: true,
  88366. configurable: true
  88367. });
  88368. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  88369. set: function (physicsPlugin) {
  88370. this._physicsPlugin = physicsPlugin;
  88371. },
  88372. enumerable: true,
  88373. configurable: true
  88374. });
  88375. /**
  88376. * Execute a function that is physics-plugin specific.
  88377. * @param {Function} func the function that will be executed.
  88378. * It accepts two parameters: the physics world and the physics joint.
  88379. */
  88380. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  88381. func(this._physicsPlugin.world, this._physicsJoint);
  88382. };
  88383. //TODO check if the native joints are the same
  88384. //Joint Types
  88385. PhysicsJoint.DistanceJoint = 0;
  88386. PhysicsJoint.HingeJoint = 1;
  88387. PhysicsJoint.BallAndSocketJoint = 2;
  88388. PhysicsJoint.WheelJoint = 3;
  88389. PhysicsJoint.SliderJoint = 4;
  88390. //OIMO
  88391. PhysicsJoint.PrismaticJoint = 5;
  88392. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  88393. PhysicsJoint.UniversalJoint = 6;
  88394. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  88395. //Cannon
  88396. //Similar to a Ball-Joint. Different in params
  88397. PhysicsJoint.PointToPointJoint = 8;
  88398. //Cannon only at the moment
  88399. PhysicsJoint.SpringJoint = 9;
  88400. PhysicsJoint.LockJoint = 10;
  88401. return PhysicsJoint;
  88402. }());
  88403. BABYLON.PhysicsJoint = PhysicsJoint;
  88404. /**
  88405. * A class representing a physics distance joint.
  88406. */
  88407. var DistanceJoint = /** @class */ (function (_super) {
  88408. __extends(DistanceJoint, _super);
  88409. function DistanceJoint(jointData) {
  88410. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  88411. }
  88412. /**
  88413. * Update the predefined distance.
  88414. */
  88415. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  88416. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  88417. };
  88418. return DistanceJoint;
  88419. }(PhysicsJoint));
  88420. BABYLON.DistanceJoint = DistanceJoint;
  88421. var MotorEnabledJoint = /** @class */ (function (_super) {
  88422. __extends(MotorEnabledJoint, _super);
  88423. function MotorEnabledJoint(type, jointData) {
  88424. return _super.call(this, type, jointData) || this;
  88425. }
  88426. /**
  88427. * Set the motor values.
  88428. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88429. * @param {number} force the force to apply
  88430. * @param {number} maxForce max force for this motor.
  88431. */
  88432. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  88433. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  88434. };
  88435. /**
  88436. * Set the motor's limits.
  88437. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88438. */
  88439. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  88440. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  88441. };
  88442. return MotorEnabledJoint;
  88443. }(PhysicsJoint));
  88444. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  88445. /**
  88446. * This class represents a single hinge physics joint
  88447. */
  88448. var HingeJoint = /** @class */ (function (_super) {
  88449. __extends(HingeJoint, _super);
  88450. function HingeJoint(jointData) {
  88451. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  88452. }
  88453. /**
  88454. * Set the motor values.
  88455. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88456. * @param {number} force the force to apply
  88457. * @param {number} maxForce max force for this motor.
  88458. */
  88459. HingeJoint.prototype.setMotor = function (force, maxForce) {
  88460. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  88461. };
  88462. /**
  88463. * Set the motor's limits.
  88464. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88465. */
  88466. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  88467. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  88468. };
  88469. return HingeJoint;
  88470. }(MotorEnabledJoint));
  88471. BABYLON.HingeJoint = HingeJoint;
  88472. /**
  88473. * This class represents a dual hinge physics joint (same as wheel joint)
  88474. */
  88475. var Hinge2Joint = /** @class */ (function (_super) {
  88476. __extends(Hinge2Joint, _super);
  88477. function Hinge2Joint(jointData) {
  88478. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  88479. }
  88480. /**
  88481. * Set the motor values.
  88482. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88483. * @param {number} force the force to apply
  88484. * @param {number} maxForce max force for this motor.
  88485. * @param {motorIndex} the motor's index, 0 or 1.
  88486. */
  88487. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  88488. if (motorIndex === void 0) { motorIndex = 0; }
  88489. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  88490. };
  88491. /**
  88492. * Set the motor limits.
  88493. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88494. * @param {number} upperLimit the upper limit
  88495. * @param {number} lowerLimit lower limit
  88496. * @param {motorIndex} the motor's index, 0 or 1.
  88497. */
  88498. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  88499. if (motorIndex === void 0) { motorIndex = 0; }
  88500. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  88501. };
  88502. return Hinge2Joint;
  88503. }(MotorEnabledJoint));
  88504. BABYLON.Hinge2Joint = Hinge2Joint;
  88505. })(BABYLON || (BABYLON = {}));
  88506. //# sourceMappingURL=babylon.physicsJoint.js.map
  88507. var BABYLON;
  88508. (function (BABYLON) {
  88509. var PhysicsImpostor = /** @class */ (function () {
  88510. function PhysicsImpostor(object, type, _options, _scene) {
  88511. if (_options === void 0) { _options = { mass: 0 }; }
  88512. var _this = this;
  88513. this.object = object;
  88514. this.type = type;
  88515. this._options = _options;
  88516. this._scene = _scene;
  88517. this._bodyUpdateRequired = false;
  88518. this._onBeforePhysicsStepCallbacks = new Array();
  88519. this._onAfterPhysicsStepCallbacks = new Array();
  88520. this._onPhysicsCollideCallbacks = [];
  88521. this._deltaPosition = BABYLON.Vector3.Zero();
  88522. this._isDisposed = false;
  88523. //temp variables for parent rotation calculations
  88524. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  88525. this._tmpQuat = new BABYLON.Quaternion();
  88526. this._tmpQuat2 = new BABYLON.Quaternion();
  88527. /**
  88528. * this function is executed by the physics engine.
  88529. */
  88530. this.beforeStep = function () {
  88531. if (!_this._physicsEngine) {
  88532. return;
  88533. }
  88534. _this.object.translate(_this._deltaPosition, -1);
  88535. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  88536. _this.object.computeWorldMatrix(false);
  88537. if (_this.object.parent && _this.object.rotationQuaternion) {
  88538. _this.getParentsRotation();
  88539. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  88540. }
  88541. else {
  88542. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  88543. }
  88544. if (!_this._options.disableBidirectionalTransformation) {
  88545. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  88546. }
  88547. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  88548. func(_this);
  88549. });
  88550. };
  88551. /**
  88552. * this function is executed by the physics engine.
  88553. */
  88554. this.afterStep = function () {
  88555. if (!_this._physicsEngine) {
  88556. return;
  88557. }
  88558. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  88559. func(_this);
  88560. });
  88561. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  88562. // object has now its world rotation. needs to be converted to local.
  88563. if (_this.object.parent && _this.object.rotationQuaternion) {
  88564. _this.getParentsRotation();
  88565. _this._tmpQuat.conjugateInPlace();
  88566. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  88567. }
  88568. // take the position set and make it the absolute position of this object.
  88569. _this.object.setAbsolutePosition(_this.object.position);
  88570. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  88571. _this.object.translate(_this._deltaPosition, 1);
  88572. };
  88573. /**
  88574. * Legacy collision detection event support
  88575. */
  88576. this.onCollideEvent = null;
  88577. //event and body object due to cannon's event-based architecture.
  88578. this.onCollide = function (e) {
  88579. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  88580. return;
  88581. }
  88582. if (!_this._physicsEngine) {
  88583. return;
  88584. }
  88585. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  88586. if (otherImpostor) {
  88587. // Legacy collision detection event support
  88588. if (_this.onCollideEvent) {
  88589. _this.onCollideEvent(_this, otherImpostor);
  88590. }
  88591. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  88592. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  88593. }).forEach(function (obj) {
  88594. obj.callback(_this, otherImpostor);
  88595. });
  88596. }
  88597. };
  88598. //sanity check!
  88599. if (!this.object) {
  88600. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  88601. return;
  88602. }
  88603. //legacy support for old syntax.
  88604. if (!this._scene && object.getScene) {
  88605. this._scene = object.getScene();
  88606. }
  88607. if (!this._scene) {
  88608. return;
  88609. }
  88610. this._physicsEngine = this._scene.getPhysicsEngine();
  88611. if (!this._physicsEngine) {
  88612. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  88613. }
  88614. else {
  88615. //set the object's quaternion, if not set
  88616. if (!this.object.rotationQuaternion) {
  88617. if (this.object.rotation) {
  88618. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  88619. }
  88620. else {
  88621. this.object.rotationQuaternion = new BABYLON.Quaternion();
  88622. }
  88623. }
  88624. //default options params
  88625. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  88626. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  88627. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  88628. this._joints = [];
  88629. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  88630. if (!this.object.parent || this._options.ignoreParent) {
  88631. this._init();
  88632. }
  88633. else if (this.object.parent.physicsImpostor) {
  88634. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  88635. }
  88636. }
  88637. }
  88638. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  88639. get: function () {
  88640. return this._isDisposed;
  88641. },
  88642. enumerable: true,
  88643. configurable: true
  88644. });
  88645. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  88646. get: function () {
  88647. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  88648. },
  88649. set: function (value) {
  88650. this.setMass(value);
  88651. },
  88652. enumerable: true,
  88653. configurable: true
  88654. });
  88655. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  88656. get: function () {
  88657. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  88658. },
  88659. set: function (value) {
  88660. if (!this._physicsEngine) {
  88661. return;
  88662. }
  88663. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  88664. },
  88665. enumerable: true,
  88666. configurable: true
  88667. });
  88668. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  88669. get: function () {
  88670. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  88671. },
  88672. set: function (value) {
  88673. if (!this._physicsEngine) {
  88674. return;
  88675. }
  88676. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  88677. },
  88678. enumerable: true,
  88679. configurable: true
  88680. });
  88681. /**
  88682. * This function will completly initialize this impostor.
  88683. * It will create a new body - but only if this mesh has no parent.
  88684. * If it has, this impostor will not be used other than to define the impostor
  88685. * of the child mesh.
  88686. * @hidden
  88687. */
  88688. PhysicsImpostor.prototype._init = function () {
  88689. if (!this._physicsEngine) {
  88690. return;
  88691. }
  88692. this._physicsEngine.removeImpostor(this);
  88693. this.physicsBody = null;
  88694. this._parent = this._parent || this._getPhysicsParent();
  88695. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  88696. this._physicsEngine.addImpostor(this);
  88697. }
  88698. };
  88699. PhysicsImpostor.prototype._getPhysicsParent = function () {
  88700. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  88701. var parentMesh = this.object.parent;
  88702. return parentMesh.physicsImpostor;
  88703. }
  88704. return null;
  88705. };
  88706. /**
  88707. * Should a new body be generated.
  88708. */
  88709. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  88710. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  88711. };
  88712. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  88713. this.forceUpdate();
  88714. };
  88715. /**
  88716. * Force a regeneration of this or the parent's impostor's body.
  88717. * Use under cautious - This will remove all joints already implemented.
  88718. */
  88719. PhysicsImpostor.prototype.forceUpdate = function () {
  88720. this._init();
  88721. if (this.parent && !this._options.ignoreParent) {
  88722. this.parent.forceUpdate();
  88723. }
  88724. };
  88725. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  88726. /*public get mesh(): AbstractMesh {
  88727. return this._mesh;
  88728. }*/
  88729. /**
  88730. * Gets the body that holds this impostor. Either its own, or its parent.
  88731. */
  88732. get: function () {
  88733. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  88734. },
  88735. /**
  88736. * Set the physics body. Used mainly by the physics engine/plugin
  88737. */
  88738. set: function (physicsBody) {
  88739. if (this._physicsBody && this._physicsEngine) {
  88740. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  88741. }
  88742. this._physicsBody = physicsBody;
  88743. this.resetUpdateFlags();
  88744. },
  88745. enumerable: true,
  88746. configurable: true
  88747. });
  88748. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  88749. get: function () {
  88750. return !this._options.ignoreParent && this._parent ? this._parent : null;
  88751. },
  88752. set: function (value) {
  88753. this._parent = value;
  88754. },
  88755. enumerable: true,
  88756. configurable: true
  88757. });
  88758. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  88759. this._bodyUpdateRequired = false;
  88760. };
  88761. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  88762. if (this.object.getBoundingInfo) {
  88763. var q = this.object.rotationQuaternion;
  88764. //reset rotation
  88765. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  88766. //calculate the world matrix with no rotation
  88767. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  88768. var boundingInfo = this.object.getBoundingInfo();
  88769. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  88770. //bring back the rotation
  88771. this.object.rotationQuaternion = q;
  88772. //calculate the world matrix with the new rotation
  88773. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  88774. return size;
  88775. }
  88776. else {
  88777. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  88778. }
  88779. };
  88780. PhysicsImpostor.prototype.getObjectCenter = function () {
  88781. if (this.object.getBoundingInfo) {
  88782. var boundingInfo = this.object.getBoundingInfo();
  88783. return boundingInfo.boundingBox.centerWorld;
  88784. }
  88785. else {
  88786. return this.object.position;
  88787. }
  88788. };
  88789. /**
  88790. * Get a specific parametes from the options parameter.
  88791. */
  88792. PhysicsImpostor.prototype.getParam = function (paramName) {
  88793. return this._options[paramName];
  88794. };
  88795. /**
  88796. * Sets a specific parameter in the options given to the physics plugin
  88797. */
  88798. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  88799. this._options[paramName] = value;
  88800. this._bodyUpdateRequired = true;
  88801. };
  88802. /**
  88803. * Specifically change the body's mass option. Won't recreate the physics body object
  88804. */
  88805. PhysicsImpostor.prototype.setMass = function (mass) {
  88806. if (this.getParam("mass") !== mass) {
  88807. this.setParam("mass", mass);
  88808. }
  88809. if (this._physicsEngine) {
  88810. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  88811. }
  88812. };
  88813. PhysicsImpostor.prototype.getLinearVelocity = function () {
  88814. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  88815. };
  88816. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  88817. if (this._physicsEngine) {
  88818. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  88819. }
  88820. };
  88821. PhysicsImpostor.prototype.getAngularVelocity = function () {
  88822. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  88823. };
  88824. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  88825. if (this._physicsEngine) {
  88826. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  88827. }
  88828. };
  88829. /**
  88830. * Execute a function with the physics plugin native code.
  88831. * Provide a function the will have two variables - the world object and the physics body object.
  88832. */
  88833. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  88834. if (this._physicsEngine) {
  88835. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  88836. }
  88837. };
  88838. /**
  88839. * Register a function that will be executed before the physics world is stepping forward.
  88840. */
  88841. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  88842. this._onBeforePhysicsStepCallbacks.push(func);
  88843. };
  88844. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  88845. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  88846. if (index > -1) {
  88847. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  88848. }
  88849. else {
  88850. BABYLON.Tools.Warn("Function to remove was not found");
  88851. }
  88852. };
  88853. /**
  88854. * Register a function that will be executed after the physics step
  88855. */
  88856. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  88857. this._onAfterPhysicsStepCallbacks.push(func);
  88858. };
  88859. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  88860. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  88861. if (index > -1) {
  88862. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  88863. }
  88864. else {
  88865. BABYLON.Tools.Warn("Function to remove was not found");
  88866. }
  88867. };
  88868. /**
  88869. * register a function that will be executed when this impostor collides against a different body.
  88870. */
  88871. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  88872. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  88873. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  88874. };
  88875. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  88876. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  88877. var index = -1;
  88878. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  88879. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  88880. // chcek the arrays match
  88881. var sameList = cbDef.otherImpostors.every(function (impostor) {
  88882. return collidedAgainstList.indexOf(impostor) > -1;
  88883. });
  88884. if (sameList) {
  88885. index = idx;
  88886. }
  88887. return sameList;
  88888. }
  88889. return false;
  88890. });
  88891. if (found) {
  88892. this._onPhysicsCollideCallbacks.splice(index, 1);
  88893. }
  88894. else {
  88895. BABYLON.Tools.Warn("Function to remove was not found");
  88896. }
  88897. };
  88898. PhysicsImpostor.prototype.getParentsRotation = function () {
  88899. var parent = this.object.parent;
  88900. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  88901. while (parent) {
  88902. if (parent.rotationQuaternion) {
  88903. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  88904. }
  88905. else {
  88906. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  88907. }
  88908. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  88909. parent = parent.parent;
  88910. }
  88911. return this._tmpQuat;
  88912. };
  88913. /**
  88914. * Apply a force
  88915. */
  88916. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  88917. if (this._physicsEngine) {
  88918. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  88919. }
  88920. return this;
  88921. };
  88922. /**
  88923. * Apply an impulse
  88924. */
  88925. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  88926. if (this._physicsEngine) {
  88927. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  88928. }
  88929. return this;
  88930. };
  88931. /**
  88932. * A help function to create a joint.
  88933. */
  88934. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  88935. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  88936. this.addJoint(otherImpostor, joint);
  88937. return this;
  88938. };
  88939. /**
  88940. * Add a joint to this impostor with a different impostor.
  88941. */
  88942. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  88943. this._joints.push({
  88944. otherImpostor: otherImpostor,
  88945. joint: joint
  88946. });
  88947. if (this._physicsEngine) {
  88948. this._physicsEngine.addJoint(this, otherImpostor, joint);
  88949. }
  88950. return this;
  88951. };
  88952. /**
  88953. * Will keep this body still, in a sleep mode.
  88954. */
  88955. PhysicsImpostor.prototype.sleep = function () {
  88956. if (this._physicsEngine) {
  88957. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  88958. }
  88959. return this;
  88960. };
  88961. /**
  88962. * Wake the body up.
  88963. */
  88964. PhysicsImpostor.prototype.wakeUp = function () {
  88965. if (this._physicsEngine) {
  88966. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  88967. }
  88968. return this;
  88969. };
  88970. PhysicsImpostor.prototype.clone = function (newObject) {
  88971. if (!newObject)
  88972. return null;
  88973. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  88974. };
  88975. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  88976. var _this = this;
  88977. //no dispose if no physics engine is available.
  88978. if (!this._physicsEngine) {
  88979. return;
  88980. }
  88981. this._joints.forEach(function (j) {
  88982. if (_this._physicsEngine) {
  88983. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  88984. }
  88985. });
  88986. //dispose the physics body
  88987. this._physicsEngine.removeImpostor(this);
  88988. if (this.parent) {
  88989. this.parent.forceUpdate();
  88990. }
  88991. else {
  88992. /*this._object.getChildMeshes().forEach(function(mesh) {
  88993. if (mesh.physicsImpostor) {
  88994. if (disposeChildren) {
  88995. mesh.physicsImpostor.dispose();
  88996. mesh.physicsImpostor = null;
  88997. }
  88998. }
  88999. })*/
  89000. }
  89001. this._isDisposed = true;
  89002. };
  89003. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  89004. this._deltaPosition.copyFrom(position);
  89005. };
  89006. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  89007. if (!this._deltaRotation) {
  89008. this._deltaRotation = new BABYLON.Quaternion();
  89009. }
  89010. this._deltaRotation.copyFrom(rotation);
  89011. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  89012. };
  89013. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  89014. if (this._physicsEngine) {
  89015. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  89016. }
  89017. return this;
  89018. };
  89019. PhysicsImpostor.prototype.getRadius = function () {
  89020. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  89021. };
  89022. /**
  89023. * Sync a bone with this impostor
  89024. * @param bone The bone to sync to the impostor.
  89025. * @param boneMesh The mesh that the bone is influencing.
  89026. * @param jointPivot The pivot of the joint / bone in local space.
  89027. * @param distToJoint Optional distance from the impostor to the joint.
  89028. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  89029. */
  89030. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  89031. var tempVec = PhysicsImpostor._tmpVecs[0];
  89032. var mesh = this.object;
  89033. if (mesh.rotationQuaternion) {
  89034. if (adjustRotation) {
  89035. var tempQuat = PhysicsImpostor._tmpQuat;
  89036. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  89037. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  89038. }
  89039. else {
  89040. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  89041. }
  89042. }
  89043. tempVec.x = 0;
  89044. tempVec.y = 0;
  89045. tempVec.z = 0;
  89046. if (jointPivot) {
  89047. tempVec.x = jointPivot.x;
  89048. tempVec.y = jointPivot.y;
  89049. tempVec.z = jointPivot.z;
  89050. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  89051. if (distToJoint === undefined || distToJoint === null) {
  89052. distToJoint = jointPivot.length();
  89053. }
  89054. tempVec.x *= distToJoint;
  89055. tempVec.y *= distToJoint;
  89056. tempVec.z *= distToJoint;
  89057. }
  89058. if (bone.getParent()) {
  89059. tempVec.addInPlace(mesh.getAbsolutePosition());
  89060. bone.setAbsolutePosition(tempVec, boneMesh);
  89061. }
  89062. else {
  89063. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  89064. boneMesh.position.x -= tempVec.x;
  89065. boneMesh.position.y -= tempVec.y;
  89066. boneMesh.position.z -= tempVec.z;
  89067. }
  89068. };
  89069. /**
  89070. * Sync impostor to a bone
  89071. * @param bone The bone that the impostor will be synced to.
  89072. * @param boneMesh The mesh that the bone is influencing.
  89073. * @param jointPivot The pivot of the joint / bone in local space.
  89074. * @param distToJoint Optional distance from the impostor to the joint.
  89075. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  89076. * @param boneAxis Optional vector3 axis the bone is aligned with
  89077. */
  89078. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  89079. var mesh = this.object;
  89080. if (mesh.rotationQuaternion) {
  89081. if (adjustRotation) {
  89082. var tempQuat = PhysicsImpostor._tmpQuat;
  89083. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  89084. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  89085. }
  89086. else {
  89087. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  89088. }
  89089. }
  89090. var pos = PhysicsImpostor._tmpVecs[0];
  89091. var boneDir = PhysicsImpostor._tmpVecs[1];
  89092. if (!boneAxis) {
  89093. boneAxis = PhysicsImpostor._tmpVecs[2];
  89094. boneAxis.x = 0;
  89095. boneAxis.y = 1;
  89096. boneAxis.z = 0;
  89097. }
  89098. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  89099. bone.getAbsolutePositionToRef(boneMesh, pos);
  89100. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  89101. distToJoint = jointPivot.length();
  89102. }
  89103. if (distToJoint !== undefined && distToJoint !== null) {
  89104. pos.x += boneDir.x * distToJoint;
  89105. pos.y += boneDir.y * distToJoint;
  89106. pos.z += boneDir.z * distToJoint;
  89107. }
  89108. mesh.setAbsolutePosition(pos);
  89109. };
  89110. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  89111. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  89112. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  89113. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  89114. //Impostor types
  89115. PhysicsImpostor.NoImpostor = 0;
  89116. PhysicsImpostor.SphereImpostor = 1;
  89117. PhysicsImpostor.BoxImpostor = 2;
  89118. PhysicsImpostor.PlaneImpostor = 3;
  89119. PhysicsImpostor.MeshImpostor = 4;
  89120. PhysicsImpostor.CylinderImpostor = 7;
  89121. PhysicsImpostor.ParticleImpostor = 8;
  89122. PhysicsImpostor.HeightmapImpostor = 9;
  89123. return PhysicsImpostor;
  89124. }());
  89125. BABYLON.PhysicsImpostor = PhysicsImpostor;
  89126. })(BABYLON || (BABYLON = {}));
  89127. //# sourceMappingURL=babylon.physicsImpostor.js.map
  89128. var BABYLON;
  89129. (function (BABYLON) {
  89130. /**
  89131. * Class used to control physics engine
  89132. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  89133. */
  89134. var PhysicsEngine = /** @class */ (function () {
  89135. /**
  89136. * Creates a new Physics Engine
  89137. * @param gravity defines the gravity vector used by the simulation
  89138. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  89139. */
  89140. function PhysicsEngine(gravity, _physicsPlugin) {
  89141. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  89142. this._physicsPlugin = _physicsPlugin;
  89143. this._impostors = [];
  89144. this._joints = [];
  89145. if (!this._physicsPlugin.isSupported()) {
  89146. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  89147. + "Please make sure it is included.");
  89148. }
  89149. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  89150. this.setGravity(gravity);
  89151. this.setTimeStep();
  89152. }
  89153. /**
  89154. * Sets the gravity vector used by the simulation
  89155. * @param gravity defines the gravity vector to use
  89156. */
  89157. PhysicsEngine.prototype.setGravity = function (gravity) {
  89158. this.gravity = gravity;
  89159. this._physicsPlugin.setGravity(this.gravity);
  89160. };
  89161. /**
  89162. * Set the time step of the physics engine.
  89163. * Default is 1/60.
  89164. * To slow it down, enter 1/600 for example.
  89165. * To speed it up, 1/30
  89166. * @param newTimeStep defines the new timestep to apply to this world.
  89167. */
  89168. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  89169. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  89170. this._physicsPlugin.setTimeStep(newTimeStep);
  89171. };
  89172. /**
  89173. * Get the time step of the physics engine.
  89174. * @returns the current time step
  89175. */
  89176. PhysicsEngine.prototype.getTimeStep = function () {
  89177. return this._physicsPlugin.getTimeStep();
  89178. };
  89179. /**
  89180. * Release all resources
  89181. */
  89182. PhysicsEngine.prototype.dispose = function () {
  89183. this._impostors.forEach(function (impostor) {
  89184. impostor.dispose();
  89185. });
  89186. this._physicsPlugin.dispose();
  89187. };
  89188. /**
  89189. * Gets the name of the current physics plugin
  89190. * @returns the name of the plugin
  89191. */
  89192. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  89193. return this._physicsPlugin.name;
  89194. };
  89195. /**
  89196. * Adding a new impostor for the impostor tracking.
  89197. * This will be done by the impostor itself.
  89198. * @param impostor the impostor to add
  89199. */
  89200. PhysicsEngine.prototype.addImpostor = function (impostor) {
  89201. impostor.uniqueId = this._impostors.push(impostor);
  89202. //if no parent, generate the body
  89203. if (!impostor.parent) {
  89204. this._physicsPlugin.generatePhysicsBody(impostor);
  89205. }
  89206. };
  89207. /**
  89208. * Remove an impostor from the engine.
  89209. * This impostor and its mesh will not longer be updated by the physics engine.
  89210. * @param impostor the impostor to remove
  89211. */
  89212. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  89213. var index = this._impostors.indexOf(impostor);
  89214. if (index > -1) {
  89215. var removed = this._impostors.splice(index, 1);
  89216. //Is it needed?
  89217. if (removed.length) {
  89218. //this will also remove it from the world.
  89219. removed[0].physicsBody = null;
  89220. }
  89221. }
  89222. };
  89223. /**
  89224. * Add a joint to the physics engine
  89225. * @param mainImpostor defines the main impostor to which the joint is added.
  89226. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  89227. * @param joint defines the joint that will connect both impostors.
  89228. */
  89229. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  89230. var impostorJoint = {
  89231. mainImpostor: mainImpostor,
  89232. connectedImpostor: connectedImpostor,
  89233. joint: joint
  89234. };
  89235. joint.physicsPlugin = this._physicsPlugin;
  89236. this._joints.push(impostorJoint);
  89237. this._physicsPlugin.generateJoint(impostorJoint);
  89238. };
  89239. /**
  89240. * Removes a joint from the simulation
  89241. * @param mainImpostor defines the impostor used with the joint
  89242. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  89243. * @param joint defines the joint to remove
  89244. */
  89245. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  89246. var matchingJoints = this._joints.filter(function (impostorJoint) {
  89247. return (impostorJoint.connectedImpostor === connectedImpostor
  89248. && impostorJoint.joint === joint
  89249. && impostorJoint.mainImpostor === mainImpostor);
  89250. });
  89251. if (matchingJoints.length) {
  89252. this._physicsPlugin.removeJoint(matchingJoints[0]);
  89253. //TODO remove it from the list as well
  89254. }
  89255. };
  89256. /**
  89257. * Called by the scene. No need to call it.
  89258. * @param delta defines the timespam between frames
  89259. */
  89260. PhysicsEngine.prototype._step = function (delta) {
  89261. var _this = this;
  89262. //check if any mesh has no body / requires an update
  89263. this._impostors.forEach(function (impostor) {
  89264. if (impostor.isBodyInitRequired()) {
  89265. _this._physicsPlugin.generatePhysicsBody(impostor);
  89266. }
  89267. });
  89268. if (delta > 0.1) {
  89269. delta = 0.1;
  89270. }
  89271. else if (delta <= 0) {
  89272. delta = 1.0 / 60.0;
  89273. }
  89274. this._physicsPlugin.executeStep(delta, this._impostors);
  89275. };
  89276. /**
  89277. * Gets the current plugin used to run the simulation
  89278. * @returns current plugin
  89279. */
  89280. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  89281. return this._physicsPlugin;
  89282. };
  89283. /**
  89284. * Gets the list of physic impostors
  89285. * @returns an array of PhysicsImpostor
  89286. */
  89287. PhysicsEngine.prototype.getImpostors = function () {
  89288. return this._impostors;
  89289. };
  89290. /**
  89291. * Gets the impostor for a physics enabled object
  89292. * @param object defines the object impersonated by the impostor
  89293. * @returns the PhysicsImpostor or null if not found
  89294. */
  89295. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  89296. for (var i = 0; i < this._impostors.length; ++i) {
  89297. if (this._impostors[i].object === object) {
  89298. return this._impostors[i];
  89299. }
  89300. }
  89301. return null;
  89302. };
  89303. /**
  89304. * Gets the impostor for a physics body object
  89305. * @param body defines physics body used by the impostor
  89306. * @returns the PhysicsImpostor or null if not found
  89307. */
  89308. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  89309. for (var i = 0; i < this._impostors.length; ++i) {
  89310. if (this._impostors[i].physicsBody === body) {
  89311. return this._impostors[i];
  89312. }
  89313. }
  89314. return null;
  89315. };
  89316. /**
  89317. * Global value used to control the smallest number supported by the simulation
  89318. */
  89319. PhysicsEngine.Epsilon = 0.001;
  89320. return PhysicsEngine;
  89321. }());
  89322. BABYLON.PhysicsEngine = PhysicsEngine;
  89323. })(BABYLON || (BABYLON = {}));
  89324. //# sourceMappingURL=babylon.physicsEngine.js.map
  89325. var BABYLON;
  89326. (function (BABYLON) {
  89327. var PhysicsHelper = /** @class */ (function () {
  89328. function PhysicsHelper(scene) {
  89329. this._scene = scene;
  89330. this._physicsEngine = this._scene.getPhysicsEngine();
  89331. if (!this._physicsEngine) {
  89332. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  89333. }
  89334. }
  89335. /**
  89336. * @param {Vector3} origin the origin of the explosion
  89337. * @param {number} radius the explosion radius
  89338. * @param {number} strength the explosion strength
  89339. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89340. */
  89341. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  89342. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89343. if (!this._physicsEngine) {
  89344. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  89345. return null;
  89346. }
  89347. var impostors = this._physicsEngine.getImpostors();
  89348. if (impostors.length === 0) {
  89349. return null;
  89350. }
  89351. var event = new PhysicsRadialExplosionEvent(this._scene);
  89352. impostors.forEach(function (impostor) {
  89353. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  89354. if (!impostorForceAndContactPoint) {
  89355. return;
  89356. }
  89357. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89358. });
  89359. event.dispose(false);
  89360. return event;
  89361. };
  89362. /**
  89363. * @param {Vector3} origin the origin of the explosion
  89364. * @param {number} radius the explosion radius
  89365. * @param {number} strength the explosion strength
  89366. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89367. */
  89368. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  89369. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89370. if (!this._physicsEngine) {
  89371. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89372. return null;
  89373. }
  89374. var impostors = this._physicsEngine.getImpostors();
  89375. if (impostors.length === 0) {
  89376. return null;
  89377. }
  89378. var event = new PhysicsRadialExplosionEvent(this._scene);
  89379. impostors.forEach(function (impostor) {
  89380. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  89381. if (!impostorForceAndContactPoint) {
  89382. return;
  89383. }
  89384. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89385. });
  89386. event.dispose(false);
  89387. return event;
  89388. };
  89389. /**
  89390. * @param {Vector3} origin the origin of the explosion
  89391. * @param {number} radius the explosion radius
  89392. * @param {number} strength the explosion strength
  89393. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89394. */
  89395. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  89396. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89397. if (!this._physicsEngine) {
  89398. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89399. return null;
  89400. }
  89401. var impostors = this._physicsEngine.getImpostors();
  89402. if (impostors.length === 0) {
  89403. return null;
  89404. }
  89405. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  89406. event.dispose(false);
  89407. return event;
  89408. };
  89409. /**
  89410. * @param {Vector3} origin the origin of the updraft
  89411. * @param {number} radius the radius of the updraft
  89412. * @param {number} strength the strength of the updraft
  89413. * @param {number} height the height of the updraft
  89414. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  89415. */
  89416. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  89417. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  89418. if (!this._physicsEngine) {
  89419. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89420. return null;
  89421. }
  89422. if (this._physicsEngine.getImpostors().length === 0) {
  89423. return null;
  89424. }
  89425. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  89426. event.dispose(false);
  89427. return event;
  89428. };
  89429. /**
  89430. * @param {Vector3} origin the of the vortex
  89431. * @param {number} radius the radius of the vortex
  89432. * @param {number} strength the strength of the vortex
  89433. * @param {number} height the height of the vortex
  89434. */
  89435. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  89436. if (!this._physicsEngine) {
  89437. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89438. return null;
  89439. }
  89440. if (this._physicsEngine.getImpostors().length === 0) {
  89441. return null;
  89442. }
  89443. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  89444. event.dispose(false);
  89445. return event;
  89446. };
  89447. return PhysicsHelper;
  89448. }());
  89449. BABYLON.PhysicsHelper = PhysicsHelper;
  89450. /***** Radial explosion *****/
  89451. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  89452. function PhysicsRadialExplosionEvent(scene) {
  89453. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  89454. this._rays = [];
  89455. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  89456. this._scene = scene;
  89457. }
  89458. /**
  89459. * Returns the data related to the radial explosion event (sphere & rays).
  89460. * @returns {PhysicsRadialExplosionEventData}
  89461. */
  89462. PhysicsRadialExplosionEvent.prototype.getData = function () {
  89463. this._dataFetched = true;
  89464. return {
  89465. sphere: this._sphere,
  89466. rays: this._rays,
  89467. };
  89468. };
  89469. /**
  89470. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  89471. * @param impostor
  89472. * @param {Vector3} origin the origin of the explosion
  89473. * @param {number} radius the explosion radius
  89474. * @param {number} strength the explosion strength
  89475. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  89476. * @returns {Nullable<PhysicsForceAndContactPoint>}
  89477. */
  89478. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  89479. if (impostor.mass === 0) {
  89480. return null;
  89481. }
  89482. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  89483. return null;
  89484. }
  89485. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  89486. return null;
  89487. }
  89488. var impostorObjectCenter = impostor.getObjectCenter();
  89489. var direction = impostorObjectCenter.subtract(origin);
  89490. var ray = new BABYLON.Ray(origin, direction, radius);
  89491. this._rays.push(ray);
  89492. var hit = ray.intersectsMesh(impostor.object);
  89493. var contactPoint = hit.pickedPoint;
  89494. if (!contactPoint) {
  89495. return null;
  89496. }
  89497. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  89498. if (distanceFromOrigin > radius) {
  89499. return null;
  89500. }
  89501. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  89502. ? strength
  89503. : strength * (1 - (distanceFromOrigin / radius));
  89504. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  89505. return { force: force, contactPoint: contactPoint };
  89506. };
  89507. /**
  89508. * Disposes the sphere.
  89509. * @param {bolean} force
  89510. */
  89511. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  89512. var _this = this;
  89513. if (force === void 0) { force = true; }
  89514. if (force) {
  89515. this._sphere.dispose();
  89516. }
  89517. else {
  89518. setTimeout(function () {
  89519. if (!_this._dataFetched) {
  89520. _this._sphere.dispose();
  89521. }
  89522. }, 0);
  89523. }
  89524. };
  89525. /*** Helpers ***/
  89526. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  89527. if (!this._sphere) {
  89528. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  89529. this._sphere.isVisible = false;
  89530. }
  89531. };
  89532. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  89533. var impostorObject = impostor.object;
  89534. this._prepareSphere();
  89535. this._sphere.position = origin;
  89536. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  89537. this._sphere._updateBoundingInfo();
  89538. this._sphere.computeWorldMatrix(true);
  89539. return this._sphere.intersectsMesh(impostorObject, true);
  89540. };
  89541. return PhysicsRadialExplosionEvent;
  89542. }());
  89543. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  89544. /***** Gravitational Field *****/
  89545. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  89546. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  89547. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89548. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89549. this._physicsHelper = physicsHelper;
  89550. this._scene = scene;
  89551. this._origin = origin;
  89552. this._radius = radius;
  89553. this._strength = strength;
  89554. this._falloff = falloff;
  89555. this._tickCallback = this._tick.bind(this);
  89556. }
  89557. /**
  89558. * Returns the data related to the gravitational field event (sphere).
  89559. * @returns {PhysicsGravitationalFieldEventData}
  89560. */
  89561. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  89562. this._dataFetched = true;
  89563. return {
  89564. sphere: this._sphere,
  89565. };
  89566. };
  89567. /**
  89568. * Enables the gravitational field.
  89569. */
  89570. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  89571. this._tickCallback.call(this);
  89572. this._scene.registerBeforeRender(this._tickCallback);
  89573. };
  89574. /**
  89575. * Disables the gravitational field.
  89576. */
  89577. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  89578. this._scene.unregisterBeforeRender(this._tickCallback);
  89579. };
  89580. /**
  89581. * Disposes the sphere.
  89582. * @param {bolean} force
  89583. */
  89584. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  89585. var _this = this;
  89586. if (force === void 0) { force = true; }
  89587. if (force) {
  89588. this._sphere.dispose();
  89589. }
  89590. else {
  89591. setTimeout(function () {
  89592. if (!_this._dataFetched) {
  89593. _this._sphere.dispose();
  89594. }
  89595. }, 0);
  89596. }
  89597. };
  89598. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  89599. // Since the params won't change, we fetch the event only once
  89600. if (this._sphere) {
  89601. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  89602. }
  89603. else {
  89604. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  89605. if (radialExplosionEvent) {
  89606. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  89607. }
  89608. }
  89609. };
  89610. return PhysicsGravitationalFieldEvent;
  89611. }());
  89612. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  89613. /***** Updraft *****/
  89614. var PhysicsUpdraftEvent = /** @class */ (function () {
  89615. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  89616. this._scene = _scene;
  89617. this._origin = _origin;
  89618. this._radius = _radius;
  89619. this._strength = _strength;
  89620. this._height = _height;
  89621. this._updraftMode = _updraftMode;
  89622. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  89623. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  89624. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  89625. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89626. this._physicsEngine = this._scene.getPhysicsEngine();
  89627. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  89628. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  89629. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  89630. this._originDirection = this._origin.subtract(this._originTop).normalize();
  89631. }
  89632. this._tickCallback = this._tick.bind(this);
  89633. }
  89634. /**
  89635. * Returns the data related to the updraft event (cylinder).
  89636. * @returns {PhysicsUpdraftEventData}
  89637. */
  89638. PhysicsUpdraftEvent.prototype.getData = function () {
  89639. this._dataFetched = true;
  89640. return {
  89641. cylinder: this._cylinder,
  89642. };
  89643. };
  89644. /**
  89645. * Enables the updraft.
  89646. */
  89647. PhysicsUpdraftEvent.prototype.enable = function () {
  89648. this._tickCallback.call(this);
  89649. this._scene.registerBeforeRender(this._tickCallback);
  89650. };
  89651. /**
  89652. * Disables the cortex.
  89653. */
  89654. PhysicsUpdraftEvent.prototype.disable = function () {
  89655. this._scene.unregisterBeforeRender(this._tickCallback);
  89656. };
  89657. /**
  89658. * Disposes the sphere.
  89659. * @param {bolean} force
  89660. */
  89661. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  89662. var _this = this;
  89663. if (force === void 0) { force = true; }
  89664. if (force) {
  89665. this._cylinder.dispose();
  89666. }
  89667. else {
  89668. setTimeout(function () {
  89669. if (!_this._dataFetched) {
  89670. _this._cylinder.dispose();
  89671. }
  89672. }, 0);
  89673. }
  89674. };
  89675. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  89676. if (impostor.mass === 0) {
  89677. return null;
  89678. }
  89679. if (!this._intersectsWithCylinder(impostor)) {
  89680. return null;
  89681. }
  89682. var impostorObjectCenter = impostor.getObjectCenter();
  89683. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  89684. var direction = this._originDirection;
  89685. }
  89686. else {
  89687. var direction = impostorObjectCenter.subtract(this._originTop);
  89688. }
  89689. var multiplier = this._strength * -1;
  89690. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  89691. return { force: force, contactPoint: impostorObjectCenter };
  89692. };
  89693. PhysicsUpdraftEvent.prototype._tick = function () {
  89694. var _this = this;
  89695. this._physicsEngine.getImpostors().forEach(function (impostor) {
  89696. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  89697. if (!impostorForceAndContactPoint) {
  89698. return;
  89699. }
  89700. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89701. });
  89702. };
  89703. /*** Helpers ***/
  89704. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  89705. if (!this._cylinder) {
  89706. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  89707. height: this._height,
  89708. diameter: this._radius * 2,
  89709. }, this._scene);
  89710. this._cylinder.isVisible = false;
  89711. }
  89712. };
  89713. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  89714. var impostorObject = impostor.object;
  89715. this._prepareCylinder();
  89716. this._cylinder.position = this._cylinderPosition;
  89717. return this._cylinder.intersectsMesh(impostorObject, true);
  89718. };
  89719. return PhysicsUpdraftEvent;
  89720. }());
  89721. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  89722. /***** Vortex *****/
  89723. var PhysicsVortexEvent = /** @class */ (function () {
  89724. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  89725. this._scene = _scene;
  89726. this._origin = _origin;
  89727. this._radius = _radius;
  89728. this._strength = _strength;
  89729. this._height = _height;
  89730. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  89731. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  89732. this._updraftMultiplier = 0.02;
  89733. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  89734. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89735. this._physicsEngine = this._scene.getPhysicsEngine();
  89736. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  89737. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  89738. this._tickCallback = this._tick.bind(this);
  89739. }
  89740. /**
  89741. * Returns the data related to the vortex event (cylinder).
  89742. * @returns {PhysicsVortexEventData}
  89743. */
  89744. PhysicsVortexEvent.prototype.getData = function () {
  89745. this._dataFetched = true;
  89746. return {
  89747. cylinder: this._cylinder,
  89748. };
  89749. };
  89750. /**
  89751. * Enables the vortex.
  89752. */
  89753. PhysicsVortexEvent.prototype.enable = function () {
  89754. this._tickCallback.call(this);
  89755. this._scene.registerBeforeRender(this._tickCallback);
  89756. };
  89757. /**
  89758. * Disables the cortex.
  89759. */
  89760. PhysicsVortexEvent.prototype.disable = function () {
  89761. this._scene.unregisterBeforeRender(this._tickCallback);
  89762. };
  89763. /**
  89764. * Disposes the sphere.
  89765. * @param {bolean} force
  89766. */
  89767. PhysicsVortexEvent.prototype.dispose = function (force) {
  89768. var _this = this;
  89769. if (force === void 0) { force = true; }
  89770. if (force) {
  89771. this._cylinder.dispose();
  89772. }
  89773. else {
  89774. setTimeout(function () {
  89775. if (!_this._dataFetched) {
  89776. _this._cylinder.dispose();
  89777. }
  89778. }, 0);
  89779. }
  89780. };
  89781. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  89782. if (impostor.mass === 0) {
  89783. return null;
  89784. }
  89785. if (!this._intersectsWithCylinder(impostor)) {
  89786. return null;
  89787. }
  89788. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  89789. return null;
  89790. }
  89791. var impostorObjectCenter = impostor.getObjectCenter();
  89792. 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)
  89793. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  89794. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  89795. var hit = ray.intersectsMesh(impostor.object);
  89796. var contactPoint = hit.pickedPoint;
  89797. if (!contactPoint) {
  89798. return null;
  89799. }
  89800. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  89801. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  89802. var directionToOrigin = contactPoint.normalize();
  89803. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  89804. directionToOrigin = directionToOrigin.negate();
  89805. }
  89806. // TODO: find a more physically based solution
  89807. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  89808. var forceX = directionToOrigin.x * this._strength / 8;
  89809. var forceY = directionToOrigin.y * this._updraftMultiplier;
  89810. var forceZ = directionToOrigin.z * this._strength / 8;
  89811. }
  89812. else {
  89813. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  89814. var forceY = this._originTop.y * this._updraftMultiplier;
  89815. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  89816. }
  89817. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  89818. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  89819. return { force: force, contactPoint: impostorObjectCenter };
  89820. };
  89821. PhysicsVortexEvent.prototype._tick = function () {
  89822. var _this = this;
  89823. this._physicsEngine.getImpostors().forEach(function (impostor) {
  89824. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  89825. if (!impostorForceAndContactPoint) {
  89826. return;
  89827. }
  89828. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89829. });
  89830. };
  89831. /*** Helpers ***/
  89832. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  89833. if (!this._cylinder) {
  89834. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  89835. height: this._height,
  89836. diameter: this._radius * 2,
  89837. }, this._scene);
  89838. this._cylinder.isVisible = false;
  89839. }
  89840. };
  89841. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  89842. var impostorObject = impostor.object;
  89843. this._prepareCylinder();
  89844. this._cylinder.position = this._cylinderPosition;
  89845. return this._cylinder.intersectsMesh(impostorObject, true);
  89846. };
  89847. return PhysicsVortexEvent;
  89848. }());
  89849. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  89850. /***** Enums *****/
  89851. /**
  89852. * The strenght of the force in correspondence to the distance of the affected object
  89853. */
  89854. var PhysicsRadialImpulseFalloff;
  89855. (function (PhysicsRadialImpulseFalloff) {
  89856. /** Defines that impulse is constant in strength across it's whole radius */
  89857. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  89858. /** DEfines that impulse gets weaker if it's further from the origin */
  89859. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  89860. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  89861. /**
  89862. * The strenght of the force in correspondence to the distance of the affected object
  89863. */
  89864. var PhysicsUpdraftMode;
  89865. (function (PhysicsUpdraftMode) {
  89866. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  89867. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  89868. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  89869. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  89870. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  89871. })(BABYLON || (BABYLON = {}));
  89872. //# sourceMappingURL=babylon.physicsHelper.js.map
  89873. var BABYLON;
  89874. (function (BABYLON) {
  89875. var CannonJSPlugin = /** @class */ (function () {
  89876. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  89877. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  89878. if (iterations === void 0) { iterations = 10; }
  89879. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  89880. this.name = "CannonJSPlugin";
  89881. this._physicsMaterials = new Array();
  89882. this._fixedTimeStep = 1 / 60;
  89883. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  89884. this.BJSCANNON = CANNON;
  89885. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  89886. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  89887. this._tmpPosition = BABYLON.Vector3.Zero();
  89888. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  89889. this._tmpUnityRotation = new BABYLON.Quaternion();
  89890. if (!this.isSupported()) {
  89891. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  89892. return;
  89893. }
  89894. this._extendNamespace();
  89895. this.world = new this.BJSCANNON.World();
  89896. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  89897. this.world.solver.iterations = iterations;
  89898. }
  89899. CannonJSPlugin.prototype.setGravity = function (gravity) {
  89900. this.world.gravity.copy(gravity);
  89901. };
  89902. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  89903. this._fixedTimeStep = timeStep;
  89904. };
  89905. CannonJSPlugin.prototype.getTimeStep = function () {
  89906. return this._fixedTimeStep;
  89907. };
  89908. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  89909. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  89910. };
  89911. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  89912. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  89913. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  89914. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  89915. };
  89916. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  89917. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  89918. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  89919. impostor.physicsBody.applyForce(impulse, worldPoint);
  89920. };
  89921. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  89922. //parent-child relationship. Does this impostor has a parent impostor?
  89923. if (impostor.parent) {
  89924. if (impostor.physicsBody) {
  89925. this.removePhysicsBody(impostor);
  89926. //TODO is that needed?
  89927. impostor.forceUpdate();
  89928. }
  89929. return;
  89930. }
  89931. //should a new body be created for this impostor?
  89932. if (impostor.isBodyInitRequired()) {
  89933. var shape = this._createShape(impostor);
  89934. //unregister events, if body is being changed
  89935. var oldBody = impostor.physicsBody;
  89936. if (oldBody) {
  89937. this.removePhysicsBody(impostor);
  89938. }
  89939. //create the body and material
  89940. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  89941. var bodyCreationObject = {
  89942. mass: impostor.getParam("mass"),
  89943. material: material
  89944. };
  89945. // A simple extend, in case native options were used.
  89946. var nativeOptions = impostor.getParam("nativeOptions");
  89947. for (var key in nativeOptions) {
  89948. if (nativeOptions.hasOwnProperty(key)) {
  89949. bodyCreationObject[key] = nativeOptions[key];
  89950. }
  89951. }
  89952. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  89953. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  89954. this.world.addEventListener("preStep", impostor.beforeStep);
  89955. this.world.addEventListener("postStep", impostor.afterStep);
  89956. impostor.physicsBody.addShape(shape);
  89957. this.world.add(impostor.physicsBody);
  89958. //try to keep the body moving in the right direction by taking old properties.
  89959. //Should be tested!
  89960. if (oldBody) {
  89961. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  89962. impostor.physicsBody[param].copy(oldBody[param]);
  89963. });
  89964. }
  89965. this._processChildMeshes(impostor);
  89966. }
  89967. //now update the body's transformation
  89968. this._updatePhysicsBodyTransformation(impostor);
  89969. };
  89970. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  89971. var _this = this;
  89972. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  89973. var currentRotation = mainImpostor.object.rotationQuaternion;
  89974. if (meshChildren.length) {
  89975. var processMesh = function (localPosition, mesh) {
  89976. if (!currentRotation || !mesh.rotationQuaternion) {
  89977. return;
  89978. }
  89979. var childImpostor = mesh.getPhysicsImpostor();
  89980. if (childImpostor) {
  89981. var parent = childImpostor.parent;
  89982. if (parent !== mainImpostor) {
  89983. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  89984. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  89985. if (childImpostor.physicsBody) {
  89986. _this.removePhysicsBody(childImpostor);
  89987. childImpostor.physicsBody = null;
  89988. }
  89989. childImpostor.parent = mainImpostor;
  89990. childImpostor.resetUpdateFlags();
  89991. 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));
  89992. //Add the mass of the children.
  89993. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  89994. }
  89995. }
  89996. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  89997. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  89998. };
  89999. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  90000. }
  90001. };
  90002. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  90003. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  90004. this.world.removeEventListener("preStep", impostor.beforeStep);
  90005. this.world.removeEventListener("postStep", impostor.afterStep);
  90006. this.world.remove(impostor.physicsBody);
  90007. };
  90008. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  90009. var mainBody = impostorJoint.mainImpostor.physicsBody;
  90010. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  90011. if (!mainBody || !connectedBody) {
  90012. return;
  90013. }
  90014. var constraint;
  90015. var jointData = impostorJoint.joint.jointData;
  90016. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  90017. var constraintData = {
  90018. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  90019. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  90020. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  90021. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  90022. maxForce: jointData.nativeParams.maxForce,
  90023. collideConnected: !!jointData.collision
  90024. };
  90025. switch (impostorJoint.joint.type) {
  90026. case BABYLON.PhysicsJoint.HingeJoint:
  90027. case BABYLON.PhysicsJoint.Hinge2Joint:
  90028. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  90029. break;
  90030. case BABYLON.PhysicsJoint.DistanceJoint:
  90031. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  90032. break;
  90033. case BABYLON.PhysicsJoint.SpringJoint:
  90034. var springData = jointData;
  90035. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  90036. restLength: springData.length,
  90037. stiffness: springData.stiffness,
  90038. damping: springData.damping,
  90039. localAnchorA: constraintData.pivotA,
  90040. localAnchorB: constraintData.pivotB
  90041. });
  90042. break;
  90043. case BABYLON.PhysicsJoint.LockJoint:
  90044. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  90045. break;
  90046. case BABYLON.PhysicsJoint.PointToPointJoint:
  90047. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  90048. default:
  90049. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  90050. break;
  90051. }
  90052. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  90053. constraint.collideConnected = !!jointData.collision;
  90054. impostorJoint.joint.physicsJoint = constraint;
  90055. //don't add spring as constraint, as it is not one.
  90056. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  90057. this.world.addConstraint(constraint);
  90058. }
  90059. else {
  90060. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  90061. constraint.applyForce();
  90062. };
  90063. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  90064. }
  90065. };
  90066. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  90067. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  90068. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  90069. }
  90070. else {
  90071. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  90072. }
  90073. };
  90074. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  90075. var index;
  90076. var mat;
  90077. for (index = 0; index < this._physicsMaterials.length; index++) {
  90078. mat = this._physicsMaterials[index];
  90079. if (mat.friction === friction && mat.restitution === restitution) {
  90080. return mat;
  90081. }
  90082. }
  90083. var currentMat = new this.BJSCANNON.Material(name);
  90084. currentMat.friction = friction;
  90085. currentMat.restitution = restitution;
  90086. this._physicsMaterials.push(currentMat);
  90087. return currentMat;
  90088. };
  90089. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  90090. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  90091. };
  90092. CannonJSPlugin.prototype._createShape = function (impostor) {
  90093. var object = impostor.object;
  90094. var returnValue;
  90095. var extendSize = impostor.getObjectExtendSize();
  90096. switch (impostor.type) {
  90097. case BABYLON.PhysicsImpostor.SphereImpostor:
  90098. var radiusX = extendSize.x;
  90099. var radiusY = extendSize.y;
  90100. var radiusZ = extendSize.z;
  90101. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  90102. break;
  90103. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  90104. case BABYLON.PhysicsImpostor.CylinderImpostor:
  90105. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  90106. break;
  90107. case BABYLON.PhysicsImpostor.BoxImpostor:
  90108. var box = extendSize.scale(0.5);
  90109. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  90110. break;
  90111. case BABYLON.PhysicsImpostor.PlaneImpostor:
  90112. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  90113. returnValue = new this.BJSCANNON.Plane();
  90114. break;
  90115. case BABYLON.PhysicsImpostor.MeshImpostor:
  90116. // should transform the vertex data to world coordinates!!
  90117. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  90118. var rawFaces = object.getIndices ? object.getIndices() : [];
  90119. if (!rawVerts)
  90120. return;
  90121. // get only scale! so the object could transform correctly.
  90122. var oldPosition = object.position.clone();
  90123. var oldRotation = object.rotation && object.rotation.clone();
  90124. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  90125. object.position.copyFromFloats(0, 0, 0);
  90126. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  90127. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  90128. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  90129. var transform = object.computeWorldMatrix(true);
  90130. // convert rawVerts to object space
  90131. var temp = new Array();
  90132. var index;
  90133. for (index = 0; index < rawVerts.length; index += 3) {
  90134. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  90135. }
  90136. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  90137. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  90138. //now set back the transformation!
  90139. object.position.copyFrom(oldPosition);
  90140. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  90141. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  90142. break;
  90143. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  90144. var oldPosition2 = object.position.clone();
  90145. var oldRotation2 = object.rotation && object.rotation.clone();
  90146. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  90147. object.position.copyFromFloats(0, 0, 0);
  90148. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  90149. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  90150. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  90151. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  90152. returnValue = this._createHeightmap(object);
  90153. object.position.copyFrom(oldPosition2);
  90154. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  90155. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  90156. object.computeWorldMatrix(true);
  90157. break;
  90158. case BABYLON.PhysicsImpostor.ParticleImpostor:
  90159. returnValue = new this.BJSCANNON.Particle();
  90160. break;
  90161. }
  90162. return returnValue;
  90163. };
  90164. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  90165. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  90166. var transform = object.computeWorldMatrix(true);
  90167. // convert rawVerts to object space
  90168. var temp = new Array();
  90169. var index;
  90170. for (index = 0; index < pos.length; index += 3) {
  90171. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  90172. }
  90173. pos = temp;
  90174. var matrix = new Array();
  90175. //For now pointDepth will not be used and will be automatically calculated.
  90176. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  90177. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  90178. var boundingInfo = object.getBoundingInfo();
  90179. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  90180. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  90181. var elementSize = dim * 2 / arraySize;
  90182. for (var i = 0; i < pos.length; i = i + 3) {
  90183. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  90184. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  90185. var y = -pos[i + 2] + minY;
  90186. if (!matrix[x]) {
  90187. matrix[x] = [];
  90188. }
  90189. if (!matrix[x][z]) {
  90190. matrix[x][z] = y;
  90191. }
  90192. matrix[x][z] = Math.max(y, matrix[x][z]);
  90193. }
  90194. for (var x = 0; x <= arraySize; ++x) {
  90195. if (!matrix[x]) {
  90196. var loc = 1;
  90197. while (!matrix[(x + loc) % arraySize]) {
  90198. loc++;
  90199. }
  90200. matrix[x] = matrix[(x + loc) % arraySize].slice();
  90201. //console.log("missing x", x);
  90202. }
  90203. for (var z = 0; z <= arraySize; ++z) {
  90204. if (!matrix[x][z]) {
  90205. var loc = 1;
  90206. var newValue;
  90207. while (newValue === undefined) {
  90208. newValue = matrix[x][(z + loc++) % arraySize];
  90209. }
  90210. matrix[x][z] = newValue;
  90211. }
  90212. }
  90213. }
  90214. var shape = new this.BJSCANNON.Heightfield(matrix, {
  90215. elementSize: elementSize
  90216. });
  90217. //For future reference, needed for body transformation
  90218. shape.minY = minY;
  90219. return shape;
  90220. };
  90221. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  90222. var object = impostor.object;
  90223. //make sure it is updated...
  90224. object.computeWorldMatrix && object.computeWorldMatrix(true);
  90225. // The delta between the mesh position and the mesh bounding box center
  90226. var bInfo = object.getBoundingInfo();
  90227. if (!bInfo)
  90228. return;
  90229. var center = impostor.getObjectCenter();
  90230. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  90231. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  90232. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  90233. this._tmpPosition.copyFrom(center);
  90234. var quaternion = object.rotationQuaternion;
  90235. if (!quaternion) {
  90236. return;
  90237. }
  90238. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  90239. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  90240. //-90 DEG in X, precalculated
  90241. quaternion = quaternion.multiply(this._minus90X);
  90242. //Invert! (Precalculated, 90 deg in X)
  90243. //No need to clone. this will never change.
  90244. impostor.setDeltaRotation(this._plus90X);
  90245. }
  90246. //If it is a heightfield, if should be centered.
  90247. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  90248. var mesh = object;
  90249. var boundingInfo = mesh.getBoundingInfo();
  90250. //calculate the correct body position:
  90251. var rotationQuaternion = mesh.rotationQuaternion;
  90252. mesh.rotationQuaternion = this._tmpUnityRotation;
  90253. mesh.computeWorldMatrix(true);
  90254. //get original center with no rotation
  90255. var c = center.clone();
  90256. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  90257. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  90258. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  90259. mesh.setPreTransformMatrix(p);
  90260. mesh.computeWorldMatrix(true);
  90261. //calculate the translation
  90262. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  90263. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  90264. //add it inverted to the delta
  90265. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  90266. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  90267. //rotation is back
  90268. mesh.rotationQuaternion = rotationQuaternion;
  90269. mesh.setPreTransformMatrix(oldPivot);
  90270. mesh.computeWorldMatrix(true);
  90271. }
  90272. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  90273. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  90274. //this._tmpPosition.copyFrom(object.position);
  90275. }
  90276. impostor.setDeltaPosition(this._tmpDeltaPosition);
  90277. //Now update the impostor object
  90278. impostor.physicsBody.position.copy(this._tmpPosition);
  90279. impostor.physicsBody.quaternion.copy(quaternion);
  90280. };
  90281. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  90282. impostor.object.position.copyFrom(impostor.physicsBody.position);
  90283. if (impostor.object.rotationQuaternion) {
  90284. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  90285. }
  90286. };
  90287. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  90288. impostor.physicsBody.position.copy(newPosition);
  90289. impostor.physicsBody.quaternion.copy(newRotation);
  90290. };
  90291. CannonJSPlugin.prototype.isSupported = function () {
  90292. return this.BJSCANNON !== undefined;
  90293. };
  90294. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  90295. impostor.physicsBody.velocity.copy(velocity);
  90296. };
  90297. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  90298. impostor.physicsBody.angularVelocity.copy(velocity);
  90299. };
  90300. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  90301. var v = impostor.physicsBody.velocity;
  90302. if (!v) {
  90303. return null;
  90304. }
  90305. return new BABYLON.Vector3(v.x, v.y, v.z);
  90306. };
  90307. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  90308. var v = impostor.physicsBody.angularVelocity;
  90309. if (!v) {
  90310. return null;
  90311. }
  90312. return new BABYLON.Vector3(v.x, v.y, v.z);
  90313. };
  90314. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  90315. impostor.physicsBody.mass = mass;
  90316. impostor.physicsBody.updateMassProperties();
  90317. };
  90318. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  90319. return impostor.physicsBody.mass;
  90320. };
  90321. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  90322. return impostor.physicsBody.material.friction;
  90323. };
  90324. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  90325. impostor.physicsBody.material.friction = friction;
  90326. };
  90327. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  90328. return impostor.physicsBody.material.restitution;
  90329. };
  90330. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  90331. impostor.physicsBody.material.restitution = restitution;
  90332. };
  90333. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  90334. impostor.physicsBody.sleep();
  90335. };
  90336. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  90337. impostor.physicsBody.wakeUp();
  90338. };
  90339. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  90340. joint.physicsJoint.distance = maxDistance;
  90341. };
  90342. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  90343. // if (!motorIndex) {
  90344. // joint.physicsJoint.enableMotor();
  90345. // }
  90346. // }
  90347. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  90348. // if (!motorIndex) {
  90349. // joint.physicsJoint.disableMotor();
  90350. // }
  90351. // }
  90352. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  90353. if (!motorIndex) {
  90354. joint.physicsJoint.enableMotor();
  90355. joint.physicsJoint.setMotorSpeed(speed);
  90356. if (maxForce) {
  90357. this.setLimit(joint, maxForce);
  90358. }
  90359. }
  90360. };
  90361. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  90362. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  90363. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  90364. };
  90365. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  90366. var body = impostor.physicsBody;
  90367. mesh.position.x = body.position.x;
  90368. mesh.position.y = body.position.y;
  90369. mesh.position.z = body.position.z;
  90370. if (mesh.rotationQuaternion) {
  90371. mesh.rotationQuaternion.x = body.quaternion.x;
  90372. mesh.rotationQuaternion.y = body.quaternion.y;
  90373. mesh.rotationQuaternion.z = body.quaternion.z;
  90374. mesh.rotationQuaternion.w = body.quaternion.w;
  90375. }
  90376. };
  90377. CannonJSPlugin.prototype.getRadius = function (impostor) {
  90378. var shape = impostor.physicsBody.shapes[0];
  90379. return shape.boundingSphereRadius;
  90380. };
  90381. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  90382. var shape = impostor.physicsBody.shapes[0];
  90383. result.x = shape.halfExtents.x * 2;
  90384. result.y = shape.halfExtents.y * 2;
  90385. result.z = shape.halfExtents.z * 2;
  90386. };
  90387. CannonJSPlugin.prototype.dispose = function () {
  90388. };
  90389. CannonJSPlugin.prototype._extendNamespace = function () {
  90390. //this will force cannon to execute at least one step when using interpolation
  90391. var step_tmp1 = new this.BJSCANNON.Vec3();
  90392. var Engine = this.BJSCANNON;
  90393. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  90394. maxSubSteps = maxSubSteps || 10;
  90395. timeSinceLastCalled = timeSinceLastCalled || 0;
  90396. if (timeSinceLastCalled === 0) {
  90397. this.internalStep(dt);
  90398. this.time += dt;
  90399. }
  90400. else {
  90401. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  90402. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  90403. var t0 = performance.now();
  90404. for (var i = 0; i !== internalSteps; i++) {
  90405. this.internalStep(dt);
  90406. if (performance.now() - t0 > dt * 1000) {
  90407. break;
  90408. }
  90409. }
  90410. this.time += timeSinceLastCalled;
  90411. var h = this.time % dt;
  90412. var h_div_dt = h / dt;
  90413. var interpvelo = step_tmp1;
  90414. var bodies = this.bodies;
  90415. for (var j = 0; j !== bodies.length; j++) {
  90416. var b = bodies[j];
  90417. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  90418. b.position.vsub(b.previousPosition, interpvelo);
  90419. interpvelo.scale(h_div_dt, interpvelo);
  90420. b.position.vadd(interpvelo, b.interpolatedPosition);
  90421. }
  90422. else {
  90423. b.interpolatedPosition.copy(b.position);
  90424. b.interpolatedQuaternion.copy(b.quaternion);
  90425. }
  90426. }
  90427. }
  90428. };
  90429. };
  90430. return CannonJSPlugin;
  90431. }());
  90432. BABYLON.CannonJSPlugin = CannonJSPlugin;
  90433. })(BABYLON || (BABYLON = {}));
  90434. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  90435. var BABYLON;
  90436. (function (BABYLON) {
  90437. var OimoJSPlugin = /** @class */ (function () {
  90438. function OimoJSPlugin(iterations) {
  90439. this.name = "OimoJSPlugin";
  90440. this._tmpImpostorsArray = [];
  90441. this._tmpPositionVector = BABYLON.Vector3.Zero();
  90442. this.BJSOIMO = OIMO;
  90443. this.world = new this.BJSOIMO.World({
  90444. iterations: iterations
  90445. });
  90446. this.world.clear();
  90447. }
  90448. OimoJSPlugin.prototype.setGravity = function (gravity) {
  90449. this.world.gravity.copy(gravity);
  90450. };
  90451. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  90452. this.world.timeStep = timeStep;
  90453. };
  90454. OimoJSPlugin.prototype.getTimeStep = function () {
  90455. return this.world.timeStep;
  90456. };
  90457. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  90458. var _this = this;
  90459. impostors.forEach(function (impostor) {
  90460. impostor.beforeStep();
  90461. });
  90462. this.world.step();
  90463. impostors.forEach(function (impostor) {
  90464. impostor.afterStep();
  90465. //update the ordered impostors array
  90466. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  90467. });
  90468. //check for collisions
  90469. var contact = this.world.contacts;
  90470. while (contact !== null) {
  90471. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  90472. contact = contact.next;
  90473. continue;
  90474. }
  90475. //is this body colliding with any other? get the impostor
  90476. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  90477. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  90478. if (!mainImpostor || !collidingImpostor) {
  90479. contact = contact.next;
  90480. continue;
  90481. }
  90482. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  90483. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  90484. contact = contact.next;
  90485. }
  90486. };
  90487. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  90488. var mass = impostor.physicsBody.mass;
  90489. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  90490. };
  90491. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  90492. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  90493. this.applyImpulse(impostor, force, contactPoint);
  90494. };
  90495. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  90496. var _this = this;
  90497. //parent-child relationship. Does this impostor has a parent impostor?
  90498. if (impostor.parent) {
  90499. if (impostor.physicsBody) {
  90500. this.removePhysicsBody(impostor);
  90501. //TODO is that needed?
  90502. impostor.forceUpdate();
  90503. }
  90504. return;
  90505. }
  90506. if (impostor.isBodyInitRequired()) {
  90507. var bodyConfig = {
  90508. name: impostor.uniqueId,
  90509. //Oimo must have mass, also for static objects.
  90510. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  90511. size: [],
  90512. type: [],
  90513. pos: [],
  90514. posShape: [],
  90515. rot: [],
  90516. rotShape: [],
  90517. move: impostor.getParam("mass") !== 0,
  90518. density: impostor.getParam("mass"),
  90519. friction: impostor.getParam("friction"),
  90520. restitution: impostor.getParam("restitution"),
  90521. //Supporting older versions of Oimo
  90522. world: this.world
  90523. };
  90524. var impostors = [impostor];
  90525. var addToArray = function (parent) {
  90526. if (!parent.getChildMeshes)
  90527. return;
  90528. parent.getChildMeshes().forEach(function (m) {
  90529. if (m.physicsImpostor) {
  90530. impostors.push(m.physicsImpostor);
  90531. //m.physicsImpostor._init();
  90532. }
  90533. });
  90534. };
  90535. addToArray(impostor.object);
  90536. var checkWithEpsilon_1 = function (value) {
  90537. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  90538. };
  90539. var globalQuaternion_1 = new BABYLON.Quaternion();
  90540. impostors.forEach(function (i) {
  90541. if (!i.object.rotationQuaternion) {
  90542. return;
  90543. }
  90544. //get the correct bounding box
  90545. var oldQuaternion = i.object.rotationQuaternion;
  90546. globalQuaternion_1 = oldQuaternion.clone();
  90547. var rot = oldQuaternion.toEulerAngles();
  90548. var extendSize = i.getObjectExtendSize();
  90549. var radToDeg = 57.295779513082320876;
  90550. if (i === impostor) {
  90551. var center = impostor.getObjectCenter();
  90552. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  90553. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  90554. //Can also use Array.prototype.push.apply
  90555. bodyConfig.pos.push(center.x);
  90556. bodyConfig.pos.push(center.y);
  90557. bodyConfig.pos.push(center.z);
  90558. bodyConfig.posShape.push(0, 0, 0);
  90559. //tmp solution
  90560. bodyConfig.rot.push(0);
  90561. bodyConfig.rot.push(0);
  90562. bodyConfig.rot.push(0);
  90563. bodyConfig.rotShape.push(0, 0, 0);
  90564. }
  90565. else {
  90566. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  90567. bodyConfig.posShape.push(localPosition.x);
  90568. bodyConfig.posShape.push(localPosition.y);
  90569. bodyConfig.posShape.push(localPosition.z);
  90570. bodyConfig.pos.push(0, 0, 0);
  90571. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  90572. bodyConfig.rot.push(0);
  90573. bodyConfig.rot.push(0);
  90574. bodyConfig.rot.push(0);
  90575. bodyConfig.rotShape.push(rot.x * radToDeg);
  90576. bodyConfig.rotShape.push(rot.y * radToDeg);
  90577. bodyConfig.rotShape.push(rot.z * radToDeg);
  90578. }
  90579. // register mesh
  90580. switch (i.type) {
  90581. case BABYLON.PhysicsImpostor.ParticleImpostor:
  90582. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  90583. case BABYLON.PhysicsImpostor.SphereImpostor:
  90584. var radiusX = extendSize.x;
  90585. var radiusY = extendSize.y;
  90586. var radiusZ = extendSize.z;
  90587. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  90588. bodyConfig.type.push('sphere');
  90589. //due to the way oimo works with compounds, add 3 times
  90590. bodyConfig.size.push(size);
  90591. bodyConfig.size.push(size);
  90592. bodyConfig.size.push(size);
  90593. break;
  90594. case BABYLON.PhysicsImpostor.CylinderImpostor:
  90595. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  90596. var sizeY = checkWithEpsilon_1(extendSize.y);
  90597. bodyConfig.type.push('cylinder');
  90598. bodyConfig.size.push(sizeX);
  90599. bodyConfig.size.push(sizeY);
  90600. //due to the way oimo works with compounds, add one more value.
  90601. bodyConfig.size.push(sizeY);
  90602. break;
  90603. case BABYLON.PhysicsImpostor.PlaneImpostor:
  90604. case BABYLON.PhysicsImpostor.BoxImpostor:
  90605. default:
  90606. var sizeX = checkWithEpsilon_1(extendSize.x);
  90607. var sizeY = checkWithEpsilon_1(extendSize.y);
  90608. var sizeZ = checkWithEpsilon_1(extendSize.z);
  90609. bodyConfig.type.push('box');
  90610. //if (i === impostor) {
  90611. bodyConfig.size.push(sizeX);
  90612. bodyConfig.size.push(sizeY);
  90613. bodyConfig.size.push(sizeZ);
  90614. //} else {
  90615. // bodyConfig.size.push(0,0,0);
  90616. //}
  90617. break;
  90618. }
  90619. //actually not needed, but hey...
  90620. i.object.rotationQuaternion = oldQuaternion;
  90621. });
  90622. impostor.physicsBody = this.world.add(bodyConfig);
  90623. // set the quaternion, ignoring the previously defined (euler) rotation
  90624. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  90625. // update with delta 0, so the body will reveive the new rotation.
  90626. impostor.physicsBody.updatePosition(0);
  90627. }
  90628. else {
  90629. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  90630. }
  90631. impostor.setDeltaPosition(this._tmpPositionVector);
  90632. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  90633. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  90634. };
  90635. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  90636. //impostor.physicsBody.dispose();
  90637. //Same as : (older oimo versions)
  90638. this.world.removeRigidBody(impostor.physicsBody);
  90639. };
  90640. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  90641. var mainBody = impostorJoint.mainImpostor.physicsBody;
  90642. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  90643. if (!mainBody || !connectedBody) {
  90644. return;
  90645. }
  90646. var jointData = impostorJoint.joint.jointData;
  90647. var options = jointData.nativeParams || {};
  90648. var type;
  90649. var nativeJointData = {
  90650. body1: mainBody,
  90651. body2: connectedBody,
  90652. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  90653. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  90654. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  90655. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  90656. min: options.min,
  90657. max: options.max,
  90658. collision: options.collision || jointData.collision,
  90659. spring: options.spring,
  90660. //supporting older version of Oimo
  90661. world: this.world
  90662. };
  90663. switch (impostorJoint.joint.type) {
  90664. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  90665. type = "jointBall";
  90666. break;
  90667. case BABYLON.PhysicsJoint.SpringJoint:
  90668. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  90669. var springData = jointData;
  90670. nativeJointData.min = springData.length || nativeJointData.min;
  90671. //Max should also be set, just make sure it is at least min
  90672. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  90673. case BABYLON.PhysicsJoint.DistanceJoint:
  90674. type = "jointDistance";
  90675. nativeJointData.max = jointData.maxDistance;
  90676. break;
  90677. case BABYLON.PhysicsJoint.PrismaticJoint:
  90678. type = "jointPrisme";
  90679. break;
  90680. case BABYLON.PhysicsJoint.SliderJoint:
  90681. type = "jointSlide";
  90682. break;
  90683. case BABYLON.PhysicsJoint.WheelJoint:
  90684. type = "jointWheel";
  90685. break;
  90686. case BABYLON.PhysicsJoint.HingeJoint:
  90687. default:
  90688. type = "jointHinge";
  90689. break;
  90690. }
  90691. nativeJointData.type = type;
  90692. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  90693. };
  90694. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  90695. //Bug in Oimo prevents us from disposing a joint in the playground
  90696. //joint.joint.physicsJoint.dispose();
  90697. //So we will bruteforce it!
  90698. try {
  90699. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  90700. }
  90701. catch (e) {
  90702. BABYLON.Tools.Warn(e);
  90703. }
  90704. };
  90705. OimoJSPlugin.prototype.isSupported = function () {
  90706. return this.BJSOIMO !== undefined;
  90707. };
  90708. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  90709. if (!impostor.physicsBody.sleeping) {
  90710. //TODO check that
  90711. /*if (impostor.physicsBody.shapes.next) {
  90712. var parentShape = this._getLastShape(impostor.physicsBody);
  90713. impostor.object.position.copyFrom(parentShape.position);
  90714. console.log(parentShape.position);
  90715. } else {*/
  90716. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  90717. //}
  90718. if (impostor.object.rotationQuaternion) {
  90719. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  90720. }
  90721. }
  90722. };
  90723. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  90724. var body = impostor.physicsBody;
  90725. body.position.copy(newPosition);
  90726. body.orientation.copy(newRotation);
  90727. body.syncShapes();
  90728. body.awake();
  90729. };
  90730. /*private _getLastShape(body: any): any {
  90731. var lastShape = body.shapes;
  90732. while (lastShape.next) {
  90733. lastShape = lastShape.next;
  90734. }
  90735. return lastShape;
  90736. }*/
  90737. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  90738. impostor.physicsBody.linearVelocity.copy(velocity);
  90739. };
  90740. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  90741. impostor.physicsBody.angularVelocity.copy(velocity);
  90742. };
  90743. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  90744. var v = impostor.physicsBody.linearVelocity;
  90745. if (!v) {
  90746. return null;
  90747. }
  90748. return new BABYLON.Vector3(v.x, v.y, v.z);
  90749. };
  90750. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  90751. var v = impostor.physicsBody.angularVelocity;
  90752. if (!v) {
  90753. return null;
  90754. }
  90755. return new BABYLON.Vector3(v.x, v.y, v.z);
  90756. };
  90757. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  90758. var staticBody = mass === 0;
  90759. //this will actually set the body's density and not its mass.
  90760. //But this is how oimo treats the mass variable.
  90761. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  90762. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  90763. };
  90764. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  90765. return impostor.physicsBody.shapes.density;
  90766. };
  90767. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  90768. return impostor.physicsBody.shapes.friction;
  90769. };
  90770. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  90771. impostor.physicsBody.shapes.friction = friction;
  90772. };
  90773. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  90774. return impostor.physicsBody.shapes.restitution;
  90775. };
  90776. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  90777. impostor.physicsBody.shapes.restitution = restitution;
  90778. };
  90779. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  90780. impostor.physicsBody.sleep();
  90781. };
  90782. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  90783. impostor.physicsBody.awake();
  90784. };
  90785. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  90786. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  90787. if (minDistance !== void 0) {
  90788. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  90789. }
  90790. };
  90791. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  90792. //TODO separate rotational and transational motors.
  90793. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  90794. if (motor) {
  90795. motor.setMotor(speed, maxForce);
  90796. }
  90797. };
  90798. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  90799. //TODO separate rotational and transational motors.
  90800. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  90801. if (motor) {
  90802. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  90803. }
  90804. };
  90805. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  90806. var body = impostor.physicsBody;
  90807. mesh.position.x = body.position.x;
  90808. mesh.position.y = body.position.y;
  90809. mesh.position.z = body.position.z;
  90810. if (mesh.rotationQuaternion) {
  90811. mesh.rotationQuaternion.x = body.orientation.x;
  90812. mesh.rotationQuaternion.y = body.orientation.y;
  90813. mesh.rotationQuaternion.z = body.orientation.z;
  90814. mesh.rotationQuaternion.w = body.orientation.s;
  90815. }
  90816. };
  90817. OimoJSPlugin.prototype.getRadius = function (impostor) {
  90818. return impostor.physicsBody.shapes.radius;
  90819. };
  90820. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  90821. var shape = impostor.physicsBody.shapes;
  90822. result.x = shape.halfWidth * 2;
  90823. result.y = shape.halfHeight * 2;
  90824. result.z = shape.halfDepth * 2;
  90825. };
  90826. OimoJSPlugin.prototype.dispose = function () {
  90827. this.world.clear();
  90828. };
  90829. return OimoJSPlugin;
  90830. }());
  90831. BABYLON.OimoJSPlugin = OimoJSPlugin;
  90832. })(BABYLON || (BABYLON = {}));
  90833. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  90834. var BABYLON;
  90835. (function (BABYLON) {
  90836. /**
  90837. * Gets the current physics engine
  90838. * @returns a IPhysicsEngine or null if none attached
  90839. */
  90840. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  90841. return this._physicsEngine;
  90842. };
  90843. /**
  90844. * Enables physics to the current scene
  90845. * @param gravity defines the scene's gravity for the physics engine
  90846. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  90847. * @return a boolean indicating if the physics engine was initialized
  90848. */
  90849. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  90850. if (gravity === void 0) { gravity = null; }
  90851. if (this._physicsEngine) {
  90852. return true;
  90853. }
  90854. // Register the component to the scene
  90855. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  90856. if (!component) {
  90857. component = new PhysicsEngineSceneComponent(this);
  90858. this._addComponent(component);
  90859. }
  90860. try {
  90861. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  90862. return true;
  90863. }
  90864. catch (e) {
  90865. BABYLON.Tools.Error(e.message);
  90866. return false;
  90867. }
  90868. };
  90869. /**
  90870. * Disables and disposes the physics engine associated with the scene
  90871. */
  90872. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  90873. if (!this._physicsEngine) {
  90874. return;
  90875. }
  90876. this._physicsEngine.dispose();
  90877. this._physicsEngine = null;
  90878. };
  90879. /**
  90880. * Gets a boolean indicating if there is an active physics engine
  90881. * @returns a boolean indicating if there is an active physics engine
  90882. */
  90883. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  90884. return this._physicsEngine !== undefined;
  90885. };
  90886. /**
  90887. * Deletes a physics compound impostor
  90888. * @param compound defines the compound to delete
  90889. */
  90890. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  90891. var mesh = compound.parts[0].mesh;
  90892. if (mesh.physicsImpostor) {
  90893. mesh.physicsImpostor.dispose( /*true*/);
  90894. mesh.physicsImpostor = null;
  90895. }
  90896. };
  90897. /** @hidden */
  90898. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  90899. if (this._physicsEngine) {
  90900. this.onBeforePhysicsObservable.notifyObservers(this);
  90901. this._physicsEngine._step(step / 1000);
  90902. this.onAfterPhysicsObservable.notifyObservers(this);
  90903. }
  90904. };
  90905. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  90906. get: function () {
  90907. return this._physicsImpostor;
  90908. },
  90909. set: function (value) {
  90910. var _this = this;
  90911. if (this._physicsImpostor === value) {
  90912. return;
  90913. }
  90914. if (this._disposePhysicsObserver) {
  90915. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  90916. }
  90917. this._physicsImpostor = value;
  90918. if (value) {
  90919. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  90920. // Physics
  90921. if (_this.physicsImpostor) {
  90922. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  90923. _this.physicsImpostor = null;
  90924. }
  90925. });
  90926. }
  90927. },
  90928. enumerable: true,
  90929. configurable: true
  90930. });
  90931. /**
  90932. * Gets the current physics impostor
  90933. * @see http://doc.babylonjs.com/features/physics_engine
  90934. * @returns a physics impostor or null
  90935. */
  90936. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  90937. return this.physicsImpostor;
  90938. };
  90939. /**
  90940. * Apply a physic impulse to the mesh
  90941. * @param force defines the force to apply
  90942. * @param contactPoint defines where to apply the force
  90943. * @returns the current mesh
  90944. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  90945. */
  90946. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  90947. if (!this.physicsImpostor) {
  90948. return this;
  90949. }
  90950. this.physicsImpostor.applyImpulse(force, contactPoint);
  90951. return this;
  90952. };
  90953. /**
  90954. * Creates a physic joint between two meshes
  90955. * @param otherMesh defines the other mesh to use
  90956. * @param pivot1 defines the pivot to use on this mesh
  90957. * @param pivot2 defines the pivot to use on the other mesh
  90958. * @param options defines additional options (can be plugin dependent)
  90959. * @returns the current mesh
  90960. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  90961. */
  90962. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  90963. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  90964. return this;
  90965. }
  90966. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  90967. mainPivot: pivot1,
  90968. connectedPivot: pivot2,
  90969. nativeParams: options
  90970. });
  90971. return this;
  90972. };
  90973. /**
  90974. * Defines the physics engine scene component responsible to manage a physics engine
  90975. */
  90976. var PhysicsEngineSceneComponent = /** @class */ (function () {
  90977. /**
  90978. * Creates a new instance of the component for the given scene
  90979. * @param scene Defines the scene to register the component in
  90980. */
  90981. function PhysicsEngineSceneComponent(scene) {
  90982. var _this = this;
  90983. /**
  90984. * The component name helpful to identify the component in the list of scene components.
  90985. */
  90986. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  90987. this.scene = scene;
  90988. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  90989. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  90990. // Replace the function used to get the deterministic frame time
  90991. this.scene.getDeterministicFrameTime = function () {
  90992. if (_this.scene._physicsEngine) {
  90993. return _this.scene._physicsEngine.getTimeStep() * 1000;
  90994. }
  90995. return 1000.0 / 60.0;
  90996. };
  90997. }
  90998. /**
  90999. * Registers the component in a given scene
  91000. */
  91001. PhysicsEngineSceneComponent.prototype.register = function () {
  91002. };
  91003. /**
  91004. * Rebuilds the elements related to this component in case of
  91005. * context lost for instance.
  91006. */
  91007. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  91008. // Nothing to do for this component
  91009. };
  91010. /**
  91011. * Disposes the component and the associated ressources
  91012. */
  91013. PhysicsEngineSceneComponent.prototype.dispose = function () {
  91014. this.scene.onBeforePhysicsObservable.clear();
  91015. this.scene.onAfterPhysicsObservable.clear();
  91016. if (this.scene._physicsEngine) {
  91017. this.scene.disablePhysicsEngine();
  91018. }
  91019. };
  91020. return PhysicsEngineSceneComponent;
  91021. }());
  91022. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  91023. })(BABYLON || (BABYLON = {}));
  91024. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  91025. var BABYLON;
  91026. (function (BABYLON) {
  91027. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  91028. // All values and structures referenced from:
  91029. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  91030. var DDS_MAGIC = 0x20534444;
  91031. var
  91032. //DDSD_CAPS = 0x1,
  91033. //DDSD_HEIGHT = 0x2,
  91034. //DDSD_WIDTH = 0x4,
  91035. //DDSD_PITCH = 0x8,
  91036. //DDSD_PIXELFORMAT = 0x1000,
  91037. DDSD_MIPMAPCOUNT = 0x20000;
  91038. //DDSD_LINEARSIZE = 0x80000,
  91039. //DDSD_DEPTH = 0x800000;
  91040. // var DDSCAPS_COMPLEX = 0x8,
  91041. // DDSCAPS_MIPMAP = 0x400000,
  91042. // DDSCAPS_TEXTURE = 0x1000;
  91043. var DDSCAPS2_CUBEMAP = 0x200;
  91044. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  91045. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  91046. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  91047. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  91048. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  91049. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  91050. // DDSCAPS2_VOLUME = 0x200000;
  91051. var
  91052. //DDPF_ALPHAPIXELS = 0x1,
  91053. //DDPF_ALPHA = 0x2,
  91054. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  91055. //DDPF_YUV = 0x200,
  91056. DDPF_LUMINANCE = 0x20000;
  91057. function FourCCToInt32(value) {
  91058. return value.charCodeAt(0) +
  91059. (value.charCodeAt(1) << 8) +
  91060. (value.charCodeAt(2) << 16) +
  91061. (value.charCodeAt(3) << 24);
  91062. }
  91063. function Int32ToFourCC(value) {
  91064. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  91065. }
  91066. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  91067. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  91068. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  91069. var FOURCC_DX10 = FourCCToInt32("DX10");
  91070. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  91071. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  91072. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  91073. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  91074. var headerLengthInt = 31; // The header length in 32 bit ints
  91075. // Offsets into the header array
  91076. var off_magic = 0;
  91077. var off_size = 1;
  91078. var off_flags = 2;
  91079. var off_height = 3;
  91080. var off_width = 4;
  91081. var off_mipmapCount = 7;
  91082. var off_pfFlags = 20;
  91083. var off_pfFourCC = 21;
  91084. var off_RGBbpp = 22;
  91085. var off_RMask = 23;
  91086. var off_GMask = 24;
  91087. var off_BMask = 25;
  91088. var off_AMask = 26;
  91089. // var off_caps1 = 27;
  91090. var off_caps2 = 28;
  91091. // var off_caps3 = 29;
  91092. // var off_caps4 = 30;
  91093. var off_dxgiFormat = 32;
  91094. ;
  91095. var DDSTools = /** @class */ (function () {
  91096. function DDSTools() {
  91097. }
  91098. DDSTools.GetDDSInfo = function (arrayBuffer) {
  91099. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  91100. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  91101. var mipmapCount = 1;
  91102. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  91103. mipmapCount = Math.max(1, header[off_mipmapCount]);
  91104. }
  91105. var fourCC = header[off_pfFourCC];
  91106. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  91107. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91108. switch (fourCC) {
  91109. case FOURCC_D3DFMT_R16G16B16A16F:
  91110. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91111. break;
  91112. case FOURCC_D3DFMT_R32G32B32A32F:
  91113. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91114. break;
  91115. case FOURCC_DX10:
  91116. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  91117. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91118. break;
  91119. }
  91120. }
  91121. return {
  91122. width: header[off_width],
  91123. height: header[off_height],
  91124. mipmapCount: mipmapCount,
  91125. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  91126. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  91127. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  91128. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  91129. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  91130. dxgiFormat: dxgiFormat,
  91131. textureType: textureType
  91132. };
  91133. };
  91134. DDSTools._ToHalfFloat = function (value) {
  91135. if (!DDSTools._FloatView) {
  91136. DDSTools._FloatView = new Float32Array(1);
  91137. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  91138. }
  91139. DDSTools._FloatView[0] = value;
  91140. var x = DDSTools._Int32View[0];
  91141. var bits = (x >> 16) & 0x8000; /* Get the sign */
  91142. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  91143. var e = (x >> 23) & 0xff; /* Using int is faster here */
  91144. /* If zero, or denormal, or exponent underflows too much for a denormal
  91145. * half, return signed zero. */
  91146. if (e < 103) {
  91147. return bits;
  91148. }
  91149. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  91150. if (e > 142) {
  91151. bits |= 0x7c00;
  91152. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  91153. * not Inf, so make sure we set one mantissa bit too. */
  91154. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  91155. return bits;
  91156. }
  91157. /* If exponent underflows but not too much, return a denormal */
  91158. if (e < 113) {
  91159. m |= 0x0800;
  91160. /* Extra rounding may overflow and set mantissa to 0 and exponent
  91161. * to 1, which is OK. */
  91162. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  91163. return bits;
  91164. }
  91165. bits |= ((e - 112) << 10) | (m >> 1);
  91166. bits += m & 1;
  91167. return bits;
  91168. };
  91169. DDSTools._FromHalfFloat = function (value) {
  91170. var s = (value & 0x8000) >> 15;
  91171. var e = (value & 0x7C00) >> 10;
  91172. var f = value & 0x03FF;
  91173. if (e === 0) {
  91174. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  91175. }
  91176. else if (e == 0x1F) {
  91177. return f ? NaN : ((s ? -1 : 1) * Infinity);
  91178. }
  91179. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  91180. };
  91181. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91182. var destArray = new Float32Array(dataLength);
  91183. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  91184. var index = 0;
  91185. for (var y = 0; y < height; y++) {
  91186. for (var x = 0; x < width; x++) {
  91187. var srcPos = (x + y * width) * 4;
  91188. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  91189. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  91190. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  91191. if (DDSTools.StoreLODInAlphaChannel) {
  91192. destArray[index + 3] = lod;
  91193. }
  91194. else {
  91195. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  91196. }
  91197. index += 4;
  91198. }
  91199. }
  91200. return destArray;
  91201. };
  91202. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91203. if (DDSTools.StoreLODInAlphaChannel) {
  91204. var destArray = new Uint16Array(dataLength);
  91205. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  91206. var index = 0;
  91207. for (var y = 0; y < height; y++) {
  91208. for (var x = 0; x < width; x++) {
  91209. var srcPos = (x + y * width) * 4;
  91210. destArray[index] = srcData[srcPos];
  91211. destArray[index + 1] = srcData[srcPos + 1];
  91212. destArray[index + 2] = srcData[srcPos + 2];
  91213. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  91214. index += 4;
  91215. }
  91216. }
  91217. return destArray;
  91218. }
  91219. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  91220. };
  91221. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91222. if (DDSTools.StoreLODInAlphaChannel) {
  91223. var destArray = new Float32Array(dataLength);
  91224. var srcData = new Float32Array(arrayBuffer, dataOffset);
  91225. var index = 0;
  91226. for (var y = 0; y < height; y++) {
  91227. for (var x = 0; x < width; x++) {
  91228. var srcPos = (x + y * width) * 4;
  91229. destArray[index] = srcData[srcPos];
  91230. destArray[index + 1] = srcData[srcPos + 1];
  91231. destArray[index + 2] = srcData[srcPos + 2];
  91232. destArray[index + 3] = lod;
  91233. index += 4;
  91234. }
  91235. }
  91236. return destArray;
  91237. }
  91238. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  91239. };
  91240. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91241. var destArray = new Uint8Array(dataLength);
  91242. var srcData = new Float32Array(arrayBuffer, dataOffset);
  91243. var index = 0;
  91244. for (var y = 0; y < height; y++) {
  91245. for (var x = 0; x < width; x++) {
  91246. var srcPos = (x + y * width) * 4;
  91247. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  91248. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  91249. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  91250. if (DDSTools.StoreLODInAlphaChannel) {
  91251. destArray[index + 3] = lod;
  91252. }
  91253. else {
  91254. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  91255. }
  91256. index += 4;
  91257. }
  91258. }
  91259. return destArray;
  91260. };
  91261. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91262. var destArray = new Uint8Array(dataLength);
  91263. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  91264. var index = 0;
  91265. for (var y = 0; y < height; y++) {
  91266. for (var x = 0; x < width; x++) {
  91267. var srcPos = (x + y * width) * 4;
  91268. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  91269. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  91270. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  91271. if (DDSTools.StoreLODInAlphaChannel) {
  91272. destArray[index + 3] = lod;
  91273. }
  91274. else {
  91275. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  91276. }
  91277. index += 4;
  91278. }
  91279. }
  91280. return destArray;
  91281. };
  91282. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  91283. var byteArray = new Uint8Array(dataLength);
  91284. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  91285. var index = 0;
  91286. for (var y = 0; y < height; y++) {
  91287. for (var x = 0; x < width; x++) {
  91288. var srcPos = (x + y * width) * 4;
  91289. byteArray[index] = srcData[srcPos + rOffset];
  91290. byteArray[index + 1] = srcData[srcPos + gOffset];
  91291. byteArray[index + 2] = srcData[srcPos + bOffset];
  91292. byteArray[index + 3] = srcData[srcPos + aOffset];
  91293. index += 4;
  91294. }
  91295. }
  91296. return byteArray;
  91297. };
  91298. DDSTools._ExtractLongWordOrder = function (value) {
  91299. if (value === 0 || value === 255 || value === -16777216) {
  91300. return 0;
  91301. }
  91302. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  91303. };
  91304. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  91305. var byteArray = new Uint8Array(dataLength);
  91306. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  91307. var index = 0;
  91308. for (var y = 0; y < height; y++) {
  91309. for (var x = 0; x < width; x++) {
  91310. var srcPos = (x + y * width) * 3;
  91311. byteArray[index] = srcData[srcPos + rOffset];
  91312. byteArray[index + 1] = srcData[srcPos + gOffset];
  91313. byteArray[index + 2] = srcData[srcPos + bOffset];
  91314. index += 3;
  91315. }
  91316. }
  91317. return byteArray;
  91318. };
  91319. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  91320. var byteArray = new Uint8Array(dataLength);
  91321. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  91322. var index = 0;
  91323. for (var y = 0; y < height; y++) {
  91324. for (var x = 0; x < width; x++) {
  91325. var srcPos = (x + y * width);
  91326. byteArray[index] = srcData[srcPos];
  91327. index++;
  91328. }
  91329. }
  91330. return byteArray;
  91331. };
  91332. /**
  91333. * Uploads DDS Levels to a Babylon Texture
  91334. * @hidden
  91335. */
  91336. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  91337. if (lodIndex === void 0) { lodIndex = -1; }
  91338. var sphericalPolynomialFaces = null;
  91339. if (info.sphericalPolynomial) {
  91340. sphericalPolynomialFaces = new Array();
  91341. }
  91342. var ext = engine.getCaps().s3tc;
  91343. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  91344. var fourCC, width, height, dataLength = 0, dataOffset;
  91345. var byteArray, mipmapCount, mip;
  91346. var internalCompressedFormat = 0;
  91347. var blockBytes = 1;
  91348. if (header[off_magic] !== DDS_MAGIC) {
  91349. BABYLON.Tools.Error("Invalid magic number in DDS header");
  91350. return;
  91351. }
  91352. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  91353. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  91354. return;
  91355. }
  91356. if (info.isCompressed && !ext) {
  91357. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  91358. return;
  91359. }
  91360. var bpp = header[off_RGBbpp];
  91361. dataOffset = header[off_size] + 4;
  91362. var computeFormats = false;
  91363. if (info.isFourCC) {
  91364. fourCC = header[off_pfFourCC];
  91365. switch (fourCC) {
  91366. case FOURCC_DXT1:
  91367. blockBytes = 8;
  91368. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  91369. break;
  91370. case FOURCC_DXT3:
  91371. blockBytes = 16;
  91372. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  91373. break;
  91374. case FOURCC_DXT5:
  91375. blockBytes = 16;
  91376. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  91377. break;
  91378. case FOURCC_D3DFMT_R16G16B16A16F:
  91379. computeFormats = true;
  91380. break;
  91381. case FOURCC_D3DFMT_R32G32B32A32F:
  91382. computeFormats = true;
  91383. break;
  91384. case FOURCC_DX10:
  91385. // There is an additionnal header so dataOffset need to be changed
  91386. dataOffset += 5 * 4; // 5 uints
  91387. var supported = false;
  91388. switch (info.dxgiFormat) {
  91389. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  91390. computeFormats = true;
  91391. supported = true;
  91392. break;
  91393. case DXGI_FORMAT_B8G8R8X8_UNORM:
  91394. info.isRGB = true;
  91395. info.isFourCC = false;
  91396. bpp = 32;
  91397. supported = true;
  91398. break;
  91399. }
  91400. if (supported) {
  91401. break;
  91402. }
  91403. default:
  91404. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  91405. return;
  91406. }
  91407. }
  91408. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  91409. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  91410. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  91411. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  91412. if (computeFormats) {
  91413. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  91414. }
  91415. mipmapCount = 1;
  91416. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  91417. mipmapCount = Math.max(1, header[off_mipmapCount]);
  91418. }
  91419. for (var face = 0; face < faces; face++) {
  91420. width = header[off_width];
  91421. height = header[off_height];
  91422. for (mip = 0; mip < mipmapCount; ++mip) {
  91423. if (lodIndex === -1 || lodIndex === mip) {
  91424. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  91425. var i = (lodIndex === -1) ? mip : 0;
  91426. if (!info.isCompressed && info.isFourCC) {
  91427. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  91428. dataLength = width * height * 4;
  91429. var floatArray = null;
  91430. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  91431. if (bpp === 128) {
  91432. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91433. if (sphericalPolynomialFaces && i == 0) {
  91434. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  91435. }
  91436. }
  91437. else if (bpp === 64) {
  91438. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91439. if (sphericalPolynomialFaces && i == 0) {
  91440. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  91441. }
  91442. }
  91443. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91444. }
  91445. else {
  91446. if (bpp === 128) {
  91447. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91448. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91449. if (sphericalPolynomialFaces && i == 0) {
  91450. sphericalPolynomialFaces.push(floatArray);
  91451. }
  91452. }
  91453. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  91454. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91455. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91456. if (sphericalPolynomialFaces && i == 0) {
  91457. sphericalPolynomialFaces.push(floatArray);
  91458. }
  91459. }
  91460. else { // 64
  91461. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91462. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91463. if (sphericalPolynomialFaces && i == 0) {
  91464. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  91465. }
  91466. }
  91467. }
  91468. if (floatArray) {
  91469. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  91470. }
  91471. }
  91472. else if (info.isRGB) {
  91473. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91474. if (bpp === 24) {
  91475. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  91476. dataLength = width * height * 3;
  91477. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  91478. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  91479. }
  91480. else { // 32
  91481. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  91482. dataLength = width * height * 4;
  91483. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  91484. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  91485. }
  91486. }
  91487. else if (info.isLuminance) {
  91488. var unpackAlignment = engine._getUnpackAlignement();
  91489. var unpaddedRowSize = width;
  91490. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  91491. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  91492. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  91493. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  91494. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91495. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  91496. }
  91497. else {
  91498. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  91499. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  91500. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91501. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  91502. }
  91503. }
  91504. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  91505. width *= 0.5;
  91506. height *= 0.5;
  91507. width = Math.max(1.0, width);
  91508. height = Math.max(1.0, height);
  91509. }
  91510. if (currentFace !== undefined) {
  91511. // Loading a single face
  91512. break;
  91513. }
  91514. }
  91515. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  91516. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  91517. size: header[off_width],
  91518. right: sphericalPolynomialFaces[0],
  91519. left: sphericalPolynomialFaces[1],
  91520. up: sphericalPolynomialFaces[2],
  91521. down: sphericalPolynomialFaces[3],
  91522. front: sphericalPolynomialFaces[4],
  91523. back: sphericalPolynomialFaces[5],
  91524. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  91525. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  91526. gammaSpace: false,
  91527. });
  91528. }
  91529. else {
  91530. info.sphericalPolynomial = undefined;
  91531. }
  91532. };
  91533. DDSTools.StoreLODInAlphaChannel = false;
  91534. return DDSTools;
  91535. }());
  91536. BABYLON.DDSTools = DDSTools;
  91537. })(BABYLON || (BABYLON = {}));
  91538. //# sourceMappingURL=babylon.dds.js.map
  91539. var BABYLON;
  91540. (function (BABYLON) {
  91541. /**
  91542. * Implementation of the DDS Texture Loader.
  91543. */
  91544. var DDSTextureLoader = /** @class */ (function () {
  91545. function DDSTextureLoader() {
  91546. /**
  91547. * Defines wether the loader supports cascade loading the different faces.
  91548. */
  91549. this.supportCascades = true;
  91550. }
  91551. /**
  91552. * This returns if the loader support the current file information.
  91553. * @param extension defines the file extension of the file being loaded
  91554. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91555. * @param fallback defines the fallback internal texture if any
  91556. * @param isBase64 defines whether the texture is encoded as a base64
  91557. * @param isBuffer defines whether the texture data are stored as a buffer
  91558. * @returns true if the loader can load the specified file
  91559. */
  91560. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91561. return extension.indexOf(".dds") === 0;
  91562. };
  91563. /**
  91564. * Transform the url before loading if required.
  91565. * @param rootUrl the url of the texture
  91566. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91567. * @returns the transformed texture
  91568. */
  91569. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91570. return rootUrl;
  91571. };
  91572. /**
  91573. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91574. * @param rootUrl the url of the texture
  91575. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91576. * @returns the fallback texture
  91577. */
  91578. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91579. return null;
  91580. };
  91581. /**
  91582. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91583. * @param data contains the texture data
  91584. * @param texture defines the BabylonJS internal texture
  91585. * @param createPolynomials will be true if polynomials have been requested
  91586. * @param onLoad defines the callback to trigger once the texture is ready
  91587. * @param onError defines the callback to trigger in case of error
  91588. */
  91589. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  91590. var engine = texture.getEngine();
  91591. var info;
  91592. var loadMipmap = false;
  91593. if (Array.isArray(imgs)) {
  91594. for (var index = 0; index < imgs.length; index++) {
  91595. var data_1 = imgs[index];
  91596. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  91597. texture.width = info.width;
  91598. texture.height = info.height;
  91599. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  91600. engine._unpackFlipY(info.isCompressed);
  91601. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  91602. if (!info.isFourCC && info.mipmapCount === 1) {
  91603. engine.generateMipMapsForCubemap(texture);
  91604. }
  91605. }
  91606. }
  91607. else {
  91608. var data = imgs;
  91609. info = BABYLON.DDSTools.GetDDSInfo(data);
  91610. texture.width = info.width;
  91611. texture.height = info.height;
  91612. if (createPolynomials) {
  91613. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  91614. }
  91615. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  91616. engine._unpackFlipY(info.isCompressed);
  91617. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  91618. if (!info.isFourCC && info.mipmapCount === 1) {
  91619. engine.generateMipMapsForCubemap(texture);
  91620. }
  91621. }
  91622. engine._setCubeMapTextureParams(loadMipmap);
  91623. texture.isReady = true;
  91624. if (onLoad) {
  91625. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  91626. }
  91627. };
  91628. /**
  91629. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91630. * @param data contains the texture data
  91631. * @param texture defines the BabylonJS internal texture
  91632. * @param callback defines the method to call once ready to upload
  91633. */
  91634. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  91635. var info = BABYLON.DDSTools.GetDDSInfo(data);
  91636. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  91637. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  91638. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  91639. });
  91640. };
  91641. return DDSTextureLoader;
  91642. }());
  91643. // Register the loader.
  91644. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  91645. })(BABYLON || (BABYLON = {}));
  91646. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  91647. var BABYLON;
  91648. (function (BABYLON) {
  91649. /*
  91650. * Based on jsTGALoader - Javascript loader for TGA file
  91651. * By Vincent Thibault
  91652. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  91653. */
  91654. var TGATools = /** @class */ (function () {
  91655. function TGATools() {
  91656. }
  91657. TGATools.GetTGAHeader = function (data) {
  91658. var offset = 0;
  91659. var header = {
  91660. id_length: data[offset++],
  91661. colormap_type: data[offset++],
  91662. image_type: data[offset++],
  91663. colormap_index: data[offset++] | data[offset++] << 8,
  91664. colormap_length: data[offset++] | data[offset++] << 8,
  91665. colormap_size: data[offset++],
  91666. origin: [
  91667. data[offset++] | data[offset++] << 8,
  91668. data[offset++] | data[offset++] << 8
  91669. ],
  91670. width: data[offset++] | data[offset++] << 8,
  91671. height: data[offset++] | data[offset++] << 8,
  91672. pixel_size: data[offset++],
  91673. flags: data[offset++]
  91674. };
  91675. return header;
  91676. };
  91677. /**
  91678. * Uploads TGA content to a Babylon Texture
  91679. * @hidden
  91680. */
  91681. TGATools.UploadContent = function (texture, data) {
  91682. // Not enough data to contain header ?
  91683. if (data.length < 19) {
  91684. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  91685. return;
  91686. }
  91687. // Read Header
  91688. var offset = 18;
  91689. var header = TGATools.GetTGAHeader(data);
  91690. // Assume it's a valid Targa file.
  91691. if (header.id_length + offset > data.length) {
  91692. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  91693. return;
  91694. }
  91695. // Skip not needed data
  91696. offset += header.id_length;
  91697. var use_rle = false;
  91698. var use_pal = false;
  91699. var use_grey = false;
  91700. // Get some informations.
  91701. switch (header.image_type) {
  91702. case TGATools._TYPE_RLE_INDEXED:
  91703. use_rle = true;
  91704. case TGATools._TYPE_INDEXED:
  91705. use_pal = true;
  91706. break;
  91707. case TGATools._TYPE_RLE_RGB:
  91708. use_rle = true;
  91709. case TGATools._TYPE_RGB:
  91710. // use_rgb = true;
  91711. break;
  91712. case TGATools._TYPE_RLE_GREY:
  91713. use_rle = true;
  91714. case TGATools._TYPE_GREY:
  91715. use_grey = true;
  91716. break;
  91717. }
  91718. var pixel_data;
  91719. // var numAlphaBits = header.flags & 0xf;
  91720. var pixel_size = header.pixel_size >> 3;
  91721. var pixel_total = header.width * header.height * pixel_size;
  91722. // Read palettes
  91723. var palettes;
  91724. if (use_pal) {
  91725. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  91726. }
  91727. // Read LRE
  91728. if (use_rle) {
  91729. pixel_data = new Uint8Array(pixel_total);
  91730. var c, count, i;
  91731. var localOffset = 0;
  91732. var pixels = new Uint8Array(pixel_size);
  91733. while (offset < pixel_total && localOffset < pixel_total) {
  91734. c = data[offset++];
  91735. count = (c & 0x7f) + 1;
  91736. // RLE pixels
  91737. if (c & 0x80) {
  91738. // Bind pixel tmp array
  91739. for (i = 0; i < pixel_size; ++i) {
  91740. pixels[i] = data[offset++];
  91741. }
  91742. // Copy pixel array
  91743. for (i = 0; i < count; ++i) {
  91744. pixel_data.set(pixels, localOffset + i * pixel_size);
  91745. }
  91746. localOffset += pixel_size * count;
  91747. }
  91748. // Raw pixels
  91749. else {
  91750. count *= pixel_size;
  91751. for (i = 0; i < count; ++i) {
  91752. pixel_data[localOffset + i] = data[offset++];
  91753. }
  91754. localOffset += count;
  91755. }
  91756. }
  91757. }
  91758. // RAW Pixels
  91759. else {
  91760. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  91761. }
  91762. // Load to texture
  91763. var x_start, y_start, x_step, y_step, y_end, x_end;
  91764. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  91765. default:
  91766. case TGATools._ORIGIN_UL:
  91767. x_start = 0;
  91768. x_step = 1;
  91769. x_end = header.width;
  91770. y_start = 0;
  91771. y_step = 1;
  91772. y_end = header.height;
  91773. break;
  91774. case TGATools._ORIGIN_BL:
  91775. x_start = 0;
  91776. x_step = 1;
  91777. x_end = header.width;
  91778. y_start = header.height - 1;
  91779. y_step = -1;
  91780. y_end = -1;
  91781. break;
  91782. case TGATools._ORIGIN_UR:
  91783. x_start = header.width - 1;
  91784. x_step = -1;
  91785. x_end = -1;
  91786. y_start = 0;
  91787. y_step = 1;
  91788. y_end = header.height;
  91789. break;
  91790. case TGATools._ORIGIN_BR:
  91791. x_start = header.width - 1;
  91792. x_step = -1;
  91793. x_end = -1;
  91794. y_start = header.height - 1;
  91795. y_step = -1;
  91796. y_end = -1;
  91797. break;
  91798. }
  91799. // Load the specify method
  91800. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  91801. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  91802. var engine = texture.getEngine();
  91803. engine._uploadDataToTextureDirectly(texture, imageData);
  91804. };
  91805. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91806. var image = pixel_data, colormap = palettes;
  91807. var width = header.width, height = header.height;
  91808. var color, i = 0, x, y;
  91809. var imageData = new Uint8Array(width * height * 4);
  91810. for (y = y_start; y !== y_end; y += y_step) {
  91811. for (x = x_start; x !== x_end; x += x_step, i++) {
  91812. color = image[i];
  91813. imageData[(x + width * y) * 4 + 3] = 255;
  91814. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  91815. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  91816. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  91817. }
  91818. }
  91819. return imageData;
  91820. };
  91821. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91822. var image = pixel_data;
  91823. var width = header.width, height = header.height;
  91824. var color, i = 0, x, y;
  91825. var imageData = new Uint8Array(width * height * 4);
  91826. for (y = y_start; y !== y_end; y += y_step) {
  91827. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  91828. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  91829. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  91830. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  91831. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  91832. imageData[(x + width * y) * 4 + 0] = r;
  91833. imageData[(x + width * y) * 4 + 1] = g;
  91834. imageData[(x + width * y) * 4 + 2] = b;
  91835. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  91836. }
  91837. }
  91838. return imageData;
  91839. };
  91840. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91841. var image = pixel_data;
  91842. var width = header.width, height = header.height;
  91843. var i = 0, x, y;
  91844. var imageData = new Uint8Array(width * height * 4);
  91845. for (y = y_start; y !== y_end; y += y_step) {
  91846. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  91847. imageData[(x + width * y) * 4 + 3] = 255;
  91848. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91849. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  91850. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  91851. }
  91852. }
  91853. return imageData;
  91854. };
  91855. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91856. var image = pixel_data;
  91857. var width = header.width, height = header.height;
  91858. var i = 0, x, y;
  91859. var imageData = new Uint8Array(width * height * 4);
  91860. for (y = y_start; y !== y_end; y += y_step) {
  91861. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  91862. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91863. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  91864. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  91865. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  91866. }
  91867. }
  91868. return imageData;
  91869. };
  91870. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91871. var image = pixel_data;
  91872. var width = header.width, height = header.height;
  91873. var color, i = 0, x, y;
  91874. var imageData = new Uint8Array(width * height * 4);
  91875. for (y = y_start; y !== y_end; y += y_step) {
  91876. for (x = x_start; x !== x_end; x += x_step, i++) {
  91877. color = image[i];
  91878. imageData[(x + width * y) * 4 + 0] = color;
  91879. imageData[(x + width * y) * 4 + 1] = color;
  91880. imageData[(x + width * y) * 4 + 2] = color;
  91881. imageData[(x + width * y) * 4 + 3] = 255;
  91882. }
  91883. }
  91884. return imageData;
  91885. };
  91886. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91887. var image = pixel_data;
  91888. var width = header.width, height = header.height;
  91889. var i = 0, x, y;
  91890. var imageData = new Uint8Array(width * height * 4);
  91891. for (y = y_start; y !== y_end; y += y_step) {
  91892. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  91893. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  91894. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  91895. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91896. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  91897. }
  91898. }
  91899. return imageData;
  91900. };
  91901. //private static _TYPE_NO_DATA = 0;
  91902. TGATools._TYPE_INDEXED = 1;
  91903. TGATools._TYPE_RGB = 2;
  91904. TGATools._TYPE_GREY = 3;
  91905. TGATools._TYPE_RLE_INDEXED = 9;
  91906. TGATools._TYPE_RLE_RGB = 10;
  91907. TGATools._TYPE_RLE_GREY = 11;
  91908. TGATools._ORIGIN_MASK = 0x30;
  91909. TGATools._ORIGIN_SHIFT = 0x04;
  91910. TGATools._ORIGIN_BL = 0x00;
  91911. TGATools._ORIGIN_BR = 0x01;
  91912. TGATools._ORIGIN_UL = 0x02;
  91913. TGATools._ORIGIN_UR = 0x03;
  91914. return TGATools;
  91915. }());
  91916. BABYLON.TGATools = TGATools;
  91917. })(BABYLON || (BABYLON = {}));
  91918. //# sourceMappingURL=babylon.tga.js.map
  91919. var BABYLON;
  91920. (function (BABYLON) {
  91921. /**
  91922. * Implementation of the TGA Texture Loader.
  91923. */
  91924. var TGATextureLoader = /** @class */ (function () {
  91925. function TGATextureLoader() {
  91926. /**
  91927. * Defines wether the loader supports cascade loading the different faces.
  91928. */
  91929. this.supportCascades = false;
  91930. }
  91931. /**
  91932. * This returns if the loader support the current file information.
  91933. * @param extension defines the file extension of the file being loaded
  91934. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91935. * @param fallback defines the fallback internal texture if any
  91936. * @param isBase64 defines whether the texture is encoded as a base64
  91937. * @param isBuffer defines whether the texture data are stored as a buffer
  91938. * @returns true if the loader can load the specified file
  91939. */
  91940. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91941. return extension.indexOf(".tga") === 0;
  91942. };
  91943. /**
  91944. * Transform the url before loading if required.
  91945. * @param rootUrl the url of the texture
  91946. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91947. * @returns the transformed texture
  91948. */
  91949. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91950. return rootUrl;
  91951. };
  91952. /**
  91953. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91954. * @param rootUrl the url of the texture
  91955. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91956. * @returns the fallback texture
  91957. */
  91958. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91959. return null;
  91960. };
  91961. /**
  91962. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91963. * @param data contains the texture data
  91964. * @param texture defines the BabylonJS internal texture
  91965. * @param createPolynomials will be true if polynomials have been requested
  91966. * @param onLoad defines the callback to trigger once the texture is ready
  91967. * @param onError defines the callback to trigger in case of error
  91968. */
  91969. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  91970. throw ".env not supported in Cube.";
  91971. };
  91972. /**
  91973. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91974. * @param data contains the texture data
  91975. * @param texture defines the BabylonJS internal texture
  91976. * @param callback defines the method to call once ready to upload
  91977. */
  91978. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  91979. var uintData = new Uint8Array(data);
  91980. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  91981. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  91982. BABYLON.TGATools.UploadContent(texture, uintData);
  91983. });
  91984. };
  91985. return TGATextureLoader;
  91986. }());
  91987. // Register the loader.
  91988. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  91989. })(BABYLON || (BABYLON = {}));
  91990. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  91991. var BABYLON;
  91992. (function (BABYLON) {
  91993. /**
  91994. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  91995. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  91996. */
  91997. var KhronosTextureContainer = /** @class */ (function () {
  91998. /**
  91999. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  92000. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  92001. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  92002. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  92003. */
  92004. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  92005. this.arrayBuffer = arrayBuffer;
  92006. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  92007. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  92008. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  92009. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  92010. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  92011. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  92012. BABYLON.Tools.Error("texture missing KTX identifier");
  92013. return;
  92014. }
  92015. // load the reset of the header in native 32 bit int
  92016. var header = new Int32Array(this.arrayBuffer, 12, 13);
  92017. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  92018. var oppositeEndianess = header[0] === 0x01020304;
  92019. // read all the header elements in order they exist in the file, without modification (sans endainness)
  92020. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  92021. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  92022. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  92023. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  92024. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  92025. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  92026. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  92027. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  92028. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  92029. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  92030. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  92031. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  92032. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  92033. if (this.glType !== 0) {
  92034. BABYLON.Tools.Error("only compressed formats currently supported");
  92035. return;
  92036. }
  92037. else {
  92038. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  92039. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  92040. }
  92041. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  92042. BABYLON.Tools.Error("only 2D textures currently supported");
  92043. return;
  92044. }
  92045. if (this.numberOfArrayElements !== 0) {
  92046. BABYLON.Tools.Error("texture arrays not currently supported");
  92047. return;
  92048. }
  92049. if (this.numberOfFaces !== facesExpected) {
  92050. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  92051. return;
  92052. }
  92053. // we now have a completely validated file, so could use existence of loadType as success
  92054. // would need to make this more elaborate & adjust checks above to support more than one load type
  92055. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  92056. }
  92057. // not as fast hardware based, but will probably never need to use
  92058. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  92059. return ((val & 0xFF) << 24)
  92060. | ((val & 0xFF00) << 8)
  92061. | ((val >> 8) & 0xFF00)
  92062. | ((val >> 24) & 0xFF);
  92063. };
  92064. /**
  92065. * Uploads KTX content to a Babylon Texture.
  92066. * It is assumed that the texture has already been created & is currently bound
  92067. * @hidden
  92068. */
  92069. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  92070. switch (this.loadType) {
  92071. case KhronosTextureContainer.COMPRESSED_2D:
  92072. this._upload2DCompressedLevels(texture, loadMipmaps);
  92073. break;
  92074. case KhronosTextureContainer.TEX_2D:
  92075. case KhronosTextureContainer.COMPRESSED_3D:
  92076. case KhronosTextureContainer.TEX_3D:
  92077. }
  92078. };
  92079. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  92080. // initialize width & height for level 1
  92081. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  92082. var width = this.pixelWidth;
  92083. var height = this.pixelHeight;
  92084. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  92085. for (var level = 0; level < mipmapCount; level++) {
  92086. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  92087. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  92088. for (var face = 0; face < this.numberOfFaces; face++) {
  92089. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  92090. var engine = texture.getEngine();
  92091. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  92092. dataOffset += imageSize; // add size of the image for the next face/mipmap
  92093. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  92094. }
  92095. width = Math.max(1.0, width * 0.5);
  92096. height = Math.max(1.0, height * 0.5);
  92097. }
  92098. };
  92099. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  92100. // load types
  92101. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  92102. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  92103. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  92104. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  92105. return KhronosTextureContainer;
  92106. }());
  92107. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  92108. })(BABYLON || (BABYLON = {}));
  92109. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  92110. var BABYLON;
  92111. (function (BABYLON) {
  92112. /**
  92113. * Implementation of the KTX Texture Loader.
  92114. */
  92115. var KTXTextureLoader = /** @class */ (function () {
  92116. function KTXTextureLoader() {
  92117. /**
  92118. * Defines wether the loader supports cascade loading the different faces.
  92119. */
  92120. this.supportCascades = false;
  92121. }
  92122. /**
  92123. * This returns if the loader support the current file information.
  92124. * @param extension defines the file extension of the file being loaded
  92125. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92126. * @param fallback defines the fallback internal texture if any
  92127. * @param isBase64 defines whether the texture is encoded as a base64
  92128. * @param isBuffer defines whether the texture data are stored as a buffer
  92129. * @returns true if the loader can load the specified file
  92130. */
  92131. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  92132. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  92133. return true;
  92134. }
  92135. return false;
  92136. };
  92137. /**
  92138. * Transform the url before loading if required.
  92139. * @param rootUrl the url of the texture
  92140. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92141. * @returns the transformed texture
  92142. */
  92143. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  92144. var lastDot = rootUrl.lastIndexOf('.');
  92145. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  92146. };
  92147. /**
  92148. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  92149. * @param rootUrl the url of the texture
  92150. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92151. * @returns the fallback texture
  92152. */
  92153. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  92154. // remove the format appended to the rootUrl in the original createCubeTexture call.
  92155. var exp = new RegExp("" + textureFormatInUse + "$");
  92156. return rootUrl.replace(exp, "");
  92157. };
  92158. /**
  92159. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  92160. * @param data contains the texture data
  92161. * @param texture defines the BabylonJS internal texture
  92162. * @param createPolynomials will be true if polynomials have been requested
  92163. * @param onLoad defines the callback to trigger once the texture is ready
  92164. * @param onError defines the callback to trigger in case of error
  92165. */
  92166. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  92167. if (Array.isArray(data)) {
  92168. return;
  92169. }
  92170. var engine = texture.getEngine();
  92171. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  92172. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  92173. engine._unpackFlipY(true);
  92174. ktx.uploadLevels(texture, texture.generateMipMaps);
  92175. texture.width = ktx.pixelWidth;
  92176. texture.height = ktx.pixelHeight;
  92177. engine._setCubeMapTextureParams(loadMipmap);
  92178. texture.isReady = true;
  92179. };
  92180. /**
  92181. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  92182. * @param data contains the texture data
  92183. * @param texture defines the BabylonJS internal texture
  92184. * @param callback defines the method to call once ready to upload
  92185. */
  92186. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  92187. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  92188. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  92189. ktx.uploadLevels(texture, texture.generateMipMaps);
  92190. });
  92191. };
  92192. return KTXTextureLoader;
  92193. }());
  92194. // Register the loader.
  92195. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  92196. })(BABYLON || (BABYLON = {}));
  92197. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  92198. var BABYLON;
  92199. (function (BABYLON) {
  92200. /**
  92201. * Sets of helpers addressing the serialization and deserialization of environment texture
  92202. * stored in a BabylonJS env file.
  92203. * Those files are usually stored as .env files.
  92204. */
  92205. var EnvironmentTextureTools = /** @class */ (function () {
  92206. function EnvironmentTextureTools() {
  92207. }
  92208. /**
  92209. * Gets the environment info from an env file.
  92210. * @param data The array buffer containing the .env bytes.
  92211. * @returns the environment file info (the json header) if successfully parsed.
  92212. */
  92213. EnvironmentTextureTools.GetEnvInfo = function (data) {
  92214. var dataView = new DataView(data);
  92215. var pos = 0;
  92216. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  92217. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  92218. BABYLON.Tools.Error('Not a babylon environment map');
  92219. return null;
  92220. }
  92221. }
  92222. // Read json manifest - collect characters up to null terminator
  92223. var manifestString = '';
  92224. var charCode = 0x00;
  92225. while ((charCode = dataView.getUint8(pos++))) {
  92226. manifestString += String.fromCharCode(charCode);
  92227. }
  92228. var manifest = JSON.parse(manifestString);
  92229. if (manifest.specular) {
  92230. // Extend the header with the position of the payload.
  92231. manifest.specular.specularDataPosition = pos;
  92232. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  92233. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  92234. }
  92235. return manifest;
  92236. };
  92237. /**
  92238. * Creates an environment texture from a loaded cube texture.
  92239. * @param texture defines the cube texture to convert in env file
  92240. * @return a promise containing the environment data if succesfull.
  92241. */
  92242. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  92243. var _this = this;
  92244. var internalTexture = texture.getInternalTexture();
  92245. if (!internalTexture) {
  92246. return Promise.reject("The cube texture is invalid.");
  92247. }
  92248. if (!texture._prefiltered) {
  92249. return Promise.reject("The cube texture is invalid (not prefiltered).");
  92250. }
  92251. var engine = internalTexture.getEngine();
  92252. if (engine && engine.premultipliedAlpha) {
  92253. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  92254. }
  92255. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  92256. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  92257. }
  92258. var canvas = engine.getRenderingCanvas();
  92259. if (!canvas) {
  92260. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  92261. }
  92262. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  92263. if (!engine.getCaps().textureFloatRender) {
  92264. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92265. if (!engine.getCaps().textureHalfFloatRender) {
  92266. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  92267. }
  92268. }
  92269. var cubeWidth = internalTexture.width;
  92270. var hostingScene = new BABYLON.Scene(engine);
  92271. var specularTextures = {};
  92272. var promises = [];
  92273. // Read and collect all mipmaps data from the cube.
  92274. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  92275. mipmapsCount = Math.round(mipmapsCount);
  92276. var _loop_1 = function (i) {
  92277. var faceWidth = Math.pow(2, mipmapsCount - i);
  92278. var _loop_2 = function (face) {
  92279. var data = texture.readPixels(face, i);
  92280. // Creates a temp texture with the face data.
  92281. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  92282. // And rgbdEncode them.
  92283. var promise = new Promise(function (resolve, reject) {
  92284. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  92285. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  92286. rgbdPostProcess.onApply = function (effect) {
  92287. effect._bindTexture("textureSampler", tempTexture);
  92288. };
  92289. // As the process needs to happen on the main canvas, keep track of the current size
  92290. var currentW = engine.getRenderWidth();
  92291. var currentH = engine.getRenderHeight();
  92292. // Set the desired size for the texture
  92293. engine.setSize(faceWidth, faceWidth);
  92294. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  92295. // Reading datas from WebGL
  92296. BABYLON.Tools.ToBlob(canvas, function (blob) {
  92297. var fileReader = new FileReader();
  92298. fileReader.onload = function (event) {
  92299. var arrayBuffer = event.target.result;
  92300. specularTextures[i * 6 + face] = arrayBuffer;
  92301. resolve();
  92302. };
  92303. fileReader.readAsArrayBuffer(blob);
  92304. });
  92305. // Reapply the previous canvas size
  92306. engine.setSize(currentW, currentH);
  92307. });
  92308. });
  92309. promises.push(promise);
  92310. };
  92311. // All faces of the cube.
  92312. for (var face = 0; face < 6; face++) {
  92313. _loop_2(face);
  92314. }
  92315. };
  92316. for (var i = 0; i <= mipmapsCount; i++) {
  92317. _loop_1(i);
  92318. }
  92319. // Once all the textures haves been collected as RGBD stored in PNGs
  92320. return Promise.all(promises).then(function () {
  92321. // We can delete the hosting scene keeping track of all the creation objects
  92322. hostingScene.dispose();
  92323. // Creates the json header for the env texture
  92324. var info = {
  92325. version: 1,
  92326. width: cubeWidth,
  92327. irradiance: _this._CreateEnvTextureIrradiance(texture),
  92328. specular: {
  92329. mipmaps: [],
  92330. lodGenerationScale: texture.lodGenerationScale
  92331. }
  92332. };
  92333. // Sets the specular image data information
  92334. var position = 0;
  92335. for (var i = 0; i <= mipmapsCount; i++) {
  92336. for (var face = 0; face < 6; face++) {
  92337. var byteLength = specularTextures[i * 6 + face].byteLength;
  92338. info.specular.mipmaps.push({
  92339. length: byteLength,
  92340. position: position
  92341. });
  92342. position += byteLength;
  92343. }
  92344. }
  92345. // Encode the JSON as an array buffer
  92346. var infoString = JSON.stringify(info);
  92347. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  92348. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  92349. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  92350. infoView[i] = infoString.charCodeAt(i);
  92351. }
  92352. // Ends up with a null terminator for easier parsing
  92353. infoView[infoString.length] = 0x00;
  92354. // Computes the final required size and creates the storage
  92355. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  92356. var finalBuffer = new ArrayBuffer(totalSize);
  92357. var finalBufferView = new Uint8Array(finalBuffer);
  92358. var dataView = new DataView(finalBuffer);
  92359. // Copy the magic bytes identifying the file in
  92360. var pos = 0;
  92361. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  92362. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  92363. }
  92364. // Add the json info
  92365. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  92366. pos += infoBuffer.byteLength;
  92367. // Finally inserts the texture data
  92368. for (var i = 0; i <= mipmapsCount; i++) {
  92369. for (var face = 0; face < 6; face++) {
  92370. var dataBuffer = specularTextures[i * 6 + face];
  92371. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  92372. pos += dataBuffer.byteLength;
  92373. }
  92374. }
  92375. // Voila
  92376. return finalBuffer;
  92377. });
  92378. };
  92379. /**
  92380. * Creates a JSON representation of the spherical data.
  92381. * @param texture defines the texture containing the polynomials
  92382. * @return the JSON representation of the spherical info
  92383. */
  92384. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  92385. var polynmials = texture.sphericalPolynomial;
  92386. if (polynmials == null) {
  92387. return null;
  92388. }
  92389. return {
  92390. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  92391. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  92392. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  92393. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  92394. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  92395. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  92396. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  92397. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  92398. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  92399. };
  92400. };
  92401. /**
  92402. * Uploads the texture info contained in the env file to the GPU.
  92403. * @param texture defines the internal texture to upload to
  92404. * @param arrayBuffer defines the buffer cotaining the data to load
  92405. * @param info defines the texture info retrieved through the GetEnvInfo method
  92406. * @returns a promise
  92407. */
  92408. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  92409. if (info.version !== 1) {
  92410. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  92411. }
  92412. var specularInfo = info.specular;
  92413. if (!specularInfo) {
  92414. // Nothing else parsed so far
  92415. return Promise.resolve();
  92416. }
  92417. // Double checks the enclosed info
  92418. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  92419. mipmapsCount = Math.round(mipmapsCount) + 1;
  92420. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  92421. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  92422. }
  92423. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  92424. var imageData = new Array(mipmapsCount);
  92425. for (var i = 0; i < mipmapsCount; i++) {
  92426. imageData[i] = new Array(6);
  92427. for (var face = 0; face < 6; face++) {
  92428. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  92429. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  92430. }
  92431. }
  92432. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  92433. };
  92434. /**
  92435. * Uploads the levels of image data to the GPU.
  92436. * @param texture defines the internal texture to upload to
  92437. * @param imageData defines the array buffer views of image data [mipmap][face]
  92438. * @returns a promise
  92439. */
  92440. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  92441. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  92442. throw new Error("Texture size must be a power of two");
  92443. }
  92444. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  92445. // Gets everything ready.
  92446. var engine = texture.getEngine();
  92447. var expandTexture = false;
  92448. var generateNonLODTextures = false;
  92449. var rgbdPostProcess = null;
  92450. var cubeRtt = null;
  92451. var lodTextures = null;
  92452. var caps = engine.getCaps();
  92453. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  92454. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92455. texture.generateMipMaps = true;
  92456. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  92457. // Add extra process if texture lod is not supported
  92458. if (!caps.textureLOD) {
  92459. expandTexture = false;
  92460. generateNonLODTextures = true;
  92461. lodTextures = {};
  92462. }
  92463. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  92464. else if (engine.webGLVersion < 2) {
  92465. expandTexture = false;
  92466. }
  92467. // If half float available we can uncompress the texture
  92468. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  92469. expandTexture = true;
  92470. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92471. }
  92472. // If full float available we can uncompress the texture
  92473. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  92474. expandTexture = true;
  92475. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  92476. }
  92477. // Expand the texture if possible
  92478. if (expandTexture) {
  92479. // Simply run through the decode PP
  92480. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  92481. texture._isRGBD = false;
  92482. texture.invertY = false;
  92483. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  92484. generateDepthBuffer: false,
  92485. generateMipMaps: true,
  92486. generateStencilBuffer: false,
  92487. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  92488. type: texture.type,
  92489. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  92490. });
  92491. }
  92492. else {
  92493. texture._isRGBD = true;
  92494. texture.invertY = true;
  92495. // In case of missing support, applies the same patch than DDS files.
  92496. if (generateNonLODTextures) {
  92497. var mipSlices = 3;
  92498. var scale = texture._lodGenerationScale;
  92499. var offset = texture._lodGenerationOffset;
  92500. for (var i = 0; i < mipSlices; i++) {
  92501. //compute LOD from even spacing in smoothness (matching shader calculation)
  92502. var smoothness = i / (mipSlices - 1);
  92503. var roughness = 1 - smoothness;
  92504. var minLODIndex = offset; // roughness = 0
  92505. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  92506. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  92507. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  92508. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  92509. glTextureFromLod.isCube = true;
  92510. glTextureFromLod.invertY = true;
  92511. glTextureFromLod.generateMipMaps = false;
  92512. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  92513. // Wrap in a base texture for easy binding.
  92514. var lodTexture = new BABYLON.BaseTexture(null);
  92515. lodTexture.isCube = true;
  92516. lodTexture._texture = glTextureFromLod;
  92517. lodTextures[mipmapIndex] = lodTexture;
  92518. switch (i) {
  92519. case 0:
  92520. texture._lodTextureLow = lodTexture;
  92521. break;
  92522. case 1:
  92523. texture._lodTextureMid = lodTexture;
  92524. break;
  92525. case 2:
  92526. texture._lodTextureHigh = lodTexture;
  92527. break;
  92528. }
  92529. }
  92530. }
  92531. }
  92532. var promises = [];
  92533. var _loop_3 = function (i) {
  92534. var _loop_4 = function (face) {
  92535. // Constructs an image element from image data
  92536. var bytes = imageData[i][face];
  92537. var blob = new Blob([bytes], { type: 'image/png' });
  92538. var url = URL.createObjectURL(blob);
  92539. var image = new Image();
  92540. image.src = url;
  92541. // Enqueue promise to upload to the texture.
  92542. var promise = new Promise(function (resolve, reject) {
  92543. image.onload = function () {
  92544. if (expandTexture) {
  92545. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  92546. reject(message);
  92547. }, image);
  92548. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  92549. // Uncompress the data to a RTT
  92550. rgbdPostProcess.onApply = function (effect) {
  92551. effect._bindTexture("textureSampler", tempTexture_1);
  92552. effect.setFloat2("scale", 1, 1);
  92553. };
  92554. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  92555. // Cleanup
  92556. engine.restoreDefaultFramebuffer();
  92557. tempTexture_1.dispose();
  92558. window.URL.revokeObjectURL(url);
  92559. resolve();
  92560. });
  92561. }
  92562. else {
  92563. engine._uploadImageToTexture(texture, image, face, i);
  92564. // Upload the face to the non lod texture support
  92565. if (generateNonLODTextures) {
  92566. var lodTexture = lodTextures[i];
  92567. if (lodTexture) {
  92568. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  92569. }
  92570. }
  92571. resolve();
  92572. }
  92573. };
  92574. image.onerror = function (error) {
  92575. reject(error);
  92576. };
  92577. });
  92578. promises.push(promise);
  92579. };
  92580. // All faces
  92581. for (var face = 0; face < 6; face++) {
  92582. _loop_4(face);
  92583. }
  92584. };
  92585. // All mipmaps up to provided number of images
  92586. for (var i = 0; i < imageData.length; i++) {
  92587. _loop_3(i);
  92588. }
  92589. // Fill remaining mipmaps with black textures.
  92590. if (imageData.length < mipmapsCount) {
  92591. var data = void 0;
  92592. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  92593. var dataLength = size * size * 4;
  92594. switch (texture.type) {
  92595. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  92596. data = new Uint8Array(dataLength);
  92597. break;
  92598. }
  92599. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  92600. data = new Uint16Array(dataLength);
  92601. break;
  92602. }
  92603. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  92604. data = new Float32Array(dataLength);
  92605. break;
  92606. }
  92607. }
  92608. for (var i = imageData.length; i < mipmapsCount; i++) {
  92609. for (var face = 0; face < 6; face++) {
  92610. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  92611. }
  92612. }
  92613. }
  92614. // Once all done, finishes the cleanup and return
  92615. return Promise.all(promises).then(function () {
  92616. // Release temp RTT.
  92617. if (cubeRtt) {
  92618. engine._releaseFramebufferObjects(cubeRtt);
  92619. cubeRtt._swapAndDie(texture);
  92620. }
  92621. // Release temp Post Process.
  92622. if (rgbdPostProcess) {
  92623. rgbdPostProcess.dispose();
  92624. }
  92625. // Flag internal texture as ready in case they are in use.
  92626. if (generateNonLODTextures) {
  92627. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  92628. texture._lodTextureHigh._texture.isReady = true;
  92629. }
  92630. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  92631. texture._lodTextureMid._texture.isReady = true;
  92632. }
  92633. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  92634. texture._lodTextureLow._texture.isReady = true;
  92635. }
  92636. }
  92637. });
  92638. };
  92639. /**
  92640. * Uploads spherical polynomials information to the texture.
  92641. * @param texture defines the texture we are trying to upload the information to
  92642. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  92643. */
  92644. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  92645. if (info.version !== 1) {
  92646. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  92647. }
  92648. var irradianceInfo = info.irradiance;
  92649. if (!irradianceInfo) {
  92650. return;
  92651. }
  92652. var sp = new BABYLON.SphericalPolynomial();
  92653. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  92654. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  92655. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  92656. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  92657. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  92658. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  92659. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  92660. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  92661. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  92662. texture._sphericalPolynomial = sp;
  92663. };
  92664. /**
  92665. * Magic number identifying the env file.
  92666. */
  92667. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  92668. return EnvironmentTextureTools;
  92669. }());
  92670. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  92671. })(BABYLON || (BABYLON = {}));
  92672. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  92673. var BABYLON;
  92674. (function (BABYLON) {
  92675. /**
  92676. * Implementation of the ENV Texture Loader.
  92677. */
  92678. var ENVTextureLoader = /** @class */ (function () {
  92679. function ENVTextureLoader() {
  92680. /**
  92681. * Defines wether the loader supports cascade loading the different faces.
  92682. */
  92683. this.supportCascades = false;
  92684. }
  92685. /**
  92686. * This returns if the loader support the current file information.
  92687. * @param extension defines the file extension of the file being loaded
  92688. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92689. * @param fallback defines the fallback internal texture if any
  92690. * @param isBase64 defines whether the texture is encoded as a base64
  92691. * @param isBuffer defines whether the texture data are stored as a buffer
  92692. * @returns true if the loader can load the specified file
  92693. */
  92694. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  92695. return extension.indexOf(".env") === 0;
  92696. };
  92697. /**
  92698. * Transform the url before loading if required.
  92699. * @param rootUrl the url of the texture
  92700. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92701. * @returns the transformed texture
  92702. */
  92703. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  92704. return rootUrl;
  92705. };
  92706. /**
  92707. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  92708. * @param rootUrl the url of the texture
  92709. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92710. * @returns the fallback texture
  92711. */
  92712. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  92713. return null;
  92714. };
  92715. /**
  92716. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  92717. * @param data contains the texture data
  92718. * @param texture defines the BabylonJS internal texture
  92719. * @param createPolynomials will be true if polynomials have been requested
  92720. * @param onLoad defines the callback to trigger once the texture is ready
  92721. * @param onError defines the callback to trigger in case of error
  92722. */
  92723. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  92724. if (Array.isArray(data)) {
  92725. return;
  92726. }
  92727. data = data;
  92728. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  92729. if (info) {
  92730. texture.width = info.width;
  92731. texture.height = info.width;
  92732. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  92733. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  92734. texture.isReady = true;
  92735. if (onLoad) {
  92736. onLoad();
  92737. }
  92738. });
  92739. }
  92740. else if (onError) {
  92741. onError("Can not parse the environment file", null);
  92742. }
  92743. };
  92744. /**
  92745. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  92746. * @param data contains the texture data
  92747. * @param texture defines the BabylonJS internal texture
  92748. * @param callback defines the method to call once ready to upload
  92749. */
  92750. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  92751. throw ".env not supported in 2d.";
  92752. };
  92753. return ENVTextureLoader;
  92754. }());
  92755. // Register the loader.
  92756. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  92757. })(BABYLON || (BABYLON = {}));
  92758. //# sourceMappingURL=babylon.envTextureLoader.js.map
  92759. var BABYLON;
  92760. (function (BABYLON) {
  92761. /**
  92762. * Renders a layer on top of an existing scene
  92763. */
  92764. var UtilityLayerRenderer = /** @class */ (function () {
  92765. /**
  92766. * Instantiates a UtilityLayerRenderer
  92767. * @param originalScene the original scene that will be rendered on top of
  92768. */
  92769. function UtilityLayerRenderer(
  92770. /** the original scene that will be rendered on top of */
  92771. originalScene) {
  92772. var _this = this;
  92773. this.originalScene = originalScene;
  92774. this._pointerCaptures = {};
  92775. this._lastPointerEvents = {};
  92776. /**
  92777. * If the utility layer should automatically be rendered on top of existing scene
  92778. */
  92779. this.shouldRender = true;
  92780. /**
  92781. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  92782. */
  92783. this.onlyCheckPointerDownEvents = true;
  92784. /**
  92785. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  92786. */
  92787. this.processAllEvents = false;
  92788. /**
  92789. * Observable raised when the pointer move from the utility layer scene to the main scene
  92790. */
  92791. this.onPointerOutObservable = new BABYLON.Observable();
  92792. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  92793. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  92794. this.utilityLayerScene._allowPostProcessClearColor = false;
  92795. originalScene.getEngine().scenes.pop();
  92796. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  92797. this.utilityLayerScene.detachControl();
  92798. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  92799. if (!_this.processAllEvents) {
  92800. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  92801. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  92802. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  92803. return;
  92804. }
  92805. }
  92806. var pointerEvent = (prePointerInfo.event);
  92807. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  92808. _this._pointerCaptures[pointerEvent.pointerId] = false;
  92809. return;
  92810. }
  92811. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  92812. if (!prePointerInfo.ray && utilityScenePick) {
  92813. prePointerInfo.ray = utilityScenePick.ray;
  92814. }
  92815. // always fire the prepointer oversvable
  92816. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  92817. // allow every non pointer down event to flow to the utility layer
  92818. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  92819. if (!prePointerInfo.skipOnPointerObservable) {
  92820. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  92821. }
  92822. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  92823. _this._pointerCaptures[pointerEvent.pointerId] = false;
  92824. }
  92825. return;
  92826. }
  92827. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  92828. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  92829. if (utilityScenePick && utilityScenePick.hit) {
  92830. if (!prePointerInfo.skipOnPointerObservable) {
  92831. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  92832. }
  92833. prePointerInfo.skipOnPointerObservable = true;
  92834. }
  92835. }
  92836. else {
  92837. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  92838. var pointerEvent_1 = (prePointerInfo.event);
  92839. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  92840. if (originalScenePick && utilityScenePick) {
  92841. // No pick in utility scene
  92842. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  92843. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  92844. // We touched an utility mesh present in the main scene
  92845. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  92846. prePointerInfo.skipOnPointerObservable = true;
  92847. }
  92848. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  92849. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  92850. }
  92851. }
  92852. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  92853. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  92854. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  92855. // If a previous utility layer set this, do not unset this
  92856. if (!prePointerInfo.skipOnPointerObservable) {
  92857. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  92858. }
  92859. }
  92860. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  92861. // We have a pick in both scenes but main is closer than utility
  92862. // We touched an utility mesh present in the main scene
  92863. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  92864. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  92865. prePointerInfo.skipOnPointerObservable = true;
  92866. }
  92867. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  92868. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  92869. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  92870. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  92871. }
  92872. }
  92873. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  92874. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  92875. }
  92876. }
  92877. }
  92878. });
  92879. // Render directly on top of existing scene without clearing
  92880. this.utilityLayerScene.autoClear = false;
  92881. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  92882. if (_this.shouldRender) {
  92883. _this.render();
  92884. }
  92885. });
  92886. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  92887. _this.dispose();
  92888. });
  92889. this._updateCamera();
  92890. }
  92891. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  92892. /**
  92893. * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)
  92894. */
  92895. get: function () {
  92896. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  92897. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  92898. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  92899. UtilityLayerRenderer._DefaultUtilityLayer = null;
  92900. });
  92901. }
  92902. return UtilityLayerRenderer._DefaultUtilityLayer;
  92903. },
  92904. enumerable: true,
  92905. configurable: true
  92906. });
  92907. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  92908. /**
  92909. * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)
  92910. */
  92911. get: function () {
  92912. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  92913. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  92914. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  92915. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  92916. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  92917. });
  92918. }
  92919. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  92920. },
  92921. enumerable: true,
  92922. configurable: true
  92923. });
  92924. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  92925. if (!prePointerInfo.skipOnPointerObservable) {
  92926. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  92927. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  92928. }
  92929. };
  92930. /**
  92931. * Renders the utility layers scene on top of the original scene
  92932. */
  92933. UtilityLayerRenderer.prototype.render = function () {
  92934. this._updateCamera();
  92935. if (this.utilityLayerScene.activeCamera) {
  92936. // Set the camera's scene to utility layers scene
  92937. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  92938. var camera = this.utilityLayerScene.activeCamera;
  92939. camera._scene = this.utilityLayerScene;
  92940. if (camera.leftCamera) {
  92941. camera.leftCamera._scene = this.utilityLayerScene;
  92942. }
  92943. if (camera.rightCamera) {
  92944. camera.rightCamera._scene = this.utilityLayerScene;
  92945. }
  92946. this.utilityLayerScene.render(false);
  92947. // Reset camera's scene back to original
  92948. camera._scene = oldScene;
  92949. if (camera.leftCamera) {
  92950. camera.leftCamera._scene = oldScene;
  92951. }
  92952. if (camera.rightCamera) {
  92953. camera.rightCamera._scene = oldScene;
  92954. }
  92955. }
  92956. };
  92957. /**
  92958. * Disposes of the renderer
  92959. */
  92960. UtilityLayerRenderer.prototype.dispose = function () {
  92961. this.onPointerOutObservable.clear();
  92962. if (this._afterRenderObserver) {
  92963. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  92964. }
  92965. if (this._sceneDisposeObserver) {
  92966. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  92967. }
  92968. if (this._originalPointerObserver) {
  92969. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  92970. }
  92971. this.utilityLayerScene.dispose();
  92972. };
  92973. UtilityLayerRenderer.prototype._updateCamera = function () {
  92974. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  92975. };
  92976. UtilityLayerRenderer._DefaultUtilityLayer = null;
  92977. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  92978. return UtilityLayerRenderer;
  92979. }());
  92980. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  92981. })(BABYLON || (BABYLON = {}));
  92982. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  92983. //# sourceMappingURL=babylon.behavior.js.map
  92984. var BABYLON;
  92985. (function (BABYLON) {
  92986. /**
  92987. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  92988. */
  92989. var PointerDragBehavior = /** @class */ (function () {
  92990. /**
  92991. * Creates a pointer drag behavior that can be attached to a mesh
  92992. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  92993. */
  92994. function PointerDragBehavior(options) {
  92995. /**
  92996. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  92997. */
  92998. this.maxDragAngle = 0;
  92999. /**
  93000. * @hidden
  93001. */
  93002. this._useAlternatePickedPointAboveMaxDragAngle = false;
  93003. /**
  93004. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  93005. */
  93006. this.currentDraggingPointerID = -1;
  93007. /**
  93008. * If the behavior is currently in a dragging state
  93009. */
  93010. this.dragging = false;
  93011. /**
  93012. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  93013. */
  93014. this.dragDeltaRatio = 0.2;
  93015. /**
  93016. * If the drag plane orientation should be updated during the dragging (Default: true)
  93017. */
  93018. this.updateDragPlane = true;
  93019. // Debug mode will display drag planes to help visualize behavior
  93020. this._debugMode = false;
  93021. this._moving = false;
  93022. /**
  93023. * Fires each time the attached mesh is dragged with the pointer
  93024. * * delta between last drag position and current drag position in world space
  93025. * * dragDistance along the drag axis
  93026. * * dragPlaneNormal normal of the current drag plane used during the drag
  93027. * * dragPlanePoint in world space where the drag intersects the drag plane
  93028. */
  93029. this.onDragObservable = new BABYLON.Observable();
  93030. /**
  93031. * Fires each time a drag begins (eg. mouse down on mesh)
  93032. */
  93033. this.onDragStartObservable = new BABYLON.Observable();
  93034. /**
  93035. * Fires each time a drag ends (eg. mouse release after drag)
  93036. */
  93037. this.onDragEndObservable = new BABYLON.Observable();
  93038. /**
  93039. * If the attached mesh should be moved when dragged
  93040. */
  93041. this.moveAttached = true;
  93042. /**
  93043. * If the drag behavior will react to drag events (Default: true)
  93044. */
  93045. this.enabled = true;
  93046. /**
  93047. * If camera controls should be detached during the drag
  93048. */
  93049. this.detachCameraControls = true;
  93050. /**
  93051. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  93052. */
  93053. this.useObjectOrienationForDragging = true;
  93054. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  93055. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  93056. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  93057. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  93058. this._attachedElement = null;
  93059. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  93060. this._lastPointerRay = {};
  93061. this._dragDelta = new BABYLON.Vector3();
  93062. // Variables to avoid instantiation in the below method
  93063. this._pointA = new BABYLON.Vector3(0, 0, 0);
  93064. this._pointB = new BABYLON.Vector3(0, 0, 0);
  93065. this._pointC = new BABYLON.Vector3(0, 0, 0);
  93066. this._lineA = new BABYLON.Vector3(0, 0, 0);
  93067. this._lineB = new BABYLON.Vector3(0, 0, 0);
  93068. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  93069. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  93070. this._options = options ? options : {};
  93071. var optionCount = 0;
  93072. if (this._options.dragAxis) {
  93073. optionCount++;
  93074. }
  93075. if (this._options.dragPlaneNormal) {
  93076. optionCount++;
  93077. }
  93078. if (optionCount > 1) {
  93079. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  93080. }
  93081. }
  93082. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  93083. /**
  93084. * The name of the behavior
  93085. */
  93086. get: function () {
  93087. return "PointerDrag";
  93088. },
  93089. enumerable: true,
  93090. configurable: true
  93091. });
  93092. /**
  93093. * Initializes the behavior
  93094. */
  93095. PointerDragBehavior.prototype.init = function () { };
  93096. /**
  93097. * Attaches the drag behavior the passed in mesh
  93098. * @param ownerNode The mesh that will be dragged around once attached
  93099. */
  93100. PointerDragBehavior.prototype.attach = function (ownerNode) {
  93101. var _this = this;
  93102. this._scene = ownerNode.getScene();
  93103. this._attachedNode = ownerNode;
  93104. // Initialize drag plane to not interfere with existing scene
  93105. if (!PointerDragBehavior._planeScene) {
  93106. if (this._debugMode) {
  93107. PointerDragBehavior._planeScene = this._scene;
  93108. }
  93109. else {
  93110. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  93111. PointerDragBehavior._planeScene.detachControl();
  93112. this._scene.getEngine().scenes.pop();
  93113. this._scene.onDisposeObservable.addOnce(function () {
  93114. PointerDragBehavior._planeScene.dispose();
  93115. PointerDragBehavior._planeScene = null;
  93116. });
  93117. }
  93118. }
  93119. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  93120. // State of the drag
  93121. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  93122. var pickPredicate = function (m) {
  93123. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  93124. };
  93125. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  93126. if (!_this.enabled) {
  93127. return;
  93128. }
  93129. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  93130. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  93131. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  93132. }
  93133. }
  93134. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  93135. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  93136. _this.releaseDrag();
  93137. }
  93138. }
  93139. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  93140. var pointerId = pointerInfo.event.pointerId;
  93141. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  93142. if (!_this._lastPointerRay[pointerId]) {
  93143. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  93144. }
  93145. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  93146. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  93147. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  93148. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  93149. _this._moveDrag(pointerInfo.pickInfo.ray);
  93150. }
  93151. }
  93152. }
  93153. });
  93154. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  93155. if (_this._moving && _this.moveAttached) {
  93156. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  93157. // Slowly move mesh to avoid jitter
  93158. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  93159. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  93160. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  93161. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  93162. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  93163. }
  93164. });
  93165. };
  93166. PointerDragBehavior.prototype.releaseDrag = function () {
  93167. this.dragging = false;
  93168. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  93169. this.currentDraggingPointerID = -1;
  93170. this._moving = false;
  93171. // Reattach camera controls
  93172. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  93173. this._scene.activeCamera.attachControl(this._attachedElement, true);
  93174. }
  93175. };
  93176. /**
  93177. * Simulates the start of a pointer drag event on the behavior
  93178. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  93179. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  93180. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  93181. */
  93182. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  93183. if (pointerId === void 0) { pointerId = 1; }
  93184. this._startDrag(pointerId, fromRay, startPickedPoint);
  93185. if (this._lastPointerRay[pointerId]) {
  93186. // if there was a last pointer ray drag the object there
  93187. this._moveDrag(this._lastPointerRay[pointerId]);
  93188. }
  93189. };
  93190. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  93191. if (pointerId === void 0) { pointerId = 1; }
  93192. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  93193. return;
  93194. }
  93195. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  93196. // Create start ray from the camera to the object
  93197. if (fromRay) {
  93198. this._startDragRay.direction.copyFrom(fromRay.direction);
  93199. this._startDragRay.origin.copyFrom(fromRay.origin);
  93200. }
  93201. else {
  93202. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  93203. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  93204. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  93205. }
  93206. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  93207. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  93208. if (pickedPoint) {
  93209. this.dragging = true;
  93210. this.currentDraggingPointerID = pointerId;
  93211. this.lastDragPosition.copyFrom(pickedPoint);
  93212. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  93213. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  93214. // Detatch camera controls
  93215. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  93216. if (this._scene.activeCamera.inputs.attachedElement) {
  93217. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  93218. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  93219. }
  93220. else {
  93221. this._attachedElement = null;
  93222. }
  93223. }
  93224. }
  93225. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  93226. };
  93227. PointerDragBehavior.prototype._moveDrag = function (ray) {
  93228. this._moving = true;
  93229. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  93230. if (pickedPoint) {
  93231. if (this.updateDragPlane) {
  93232. this._updateDragPlanePosition(ray, pickedPoint);
  93233. }
  93234. var dragLength = 0;
  93235. // depending on the drag mode option drag accordingly
  93236. if (this._options.dragAxis) {
  93237. // Convert local drag axis to world
  93238. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  93239. // Project delta drag from the drag plane onto the drag axis
  93240. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  93241. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  93242. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  93243. }
  93244. else {
  93245. dragLength = this._dragDelta.length();
  93246. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  93247. }
  93248. this._targetPosition.addInPlace(this._dragDelta);
  93249. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  93250. this.lastDragPosition.copyFrom(pickedPoint);
  93251. }
  93252. };
  93253. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  93254. var _this = this;
  93255. if (!ray) {
  93256. return null;
  93257. }
  93258. // Calculate angle between plane normal and ray
  93259. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  93260. // Correct if ray is casted from oposite side
  93261. if (angle > Math.PI / 2) {
  93262. angle = Math.PI - angle;
  93263. }
  93264. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  93265. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  93266. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  93267. // Invert ray direction along the towards object axis
  93268. this._tmpVector.copyFrom(ray.direction);
  93269. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  93270. this._alternatePickedPoint.normalize();
  93271. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  93272. this._tmpVector.addInPlace(this._alternatePickedPoint);
  93273. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  93274. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  93275. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  93276. this._alternatePickedPoint.addInPlace(this._tmpVector);
  93277. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  93278. return this._alternatePickedPoint;
  93279. }
  93280. else {
  93281. return null;
  93282. }
  93283. }
  93284. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  93285. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  93286. return pickResult.pickedPoint;
  93287. }
  93288. else {
  93289. return null;
  93290. }
  93291. };
  93292. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  93293. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  93294. this._pointA.copyFrom(dragPlanePosition);
  93295. if (this._options.dragAxis) {
  93296. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  93297. // Calculate plane normal in direction of camera but perpendicular to drag axis
  93298. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  93299. ray.origin.subtractToRef(this._pointA, this._pointC);
  93300. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  93301. // Get perpendicular line from direction to camera and drag axis
  93302. this._pointB.subtractToRef(this._pointA, this._lineA);
  93303. this._pointC.subtractToRef(this._pointA, this._lineB);
  93304. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  93305. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  93306. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  93307. this._lookAt.normalize();
  93308. this._dragPlane.position.copyFrom(this._pointA);
  93309. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  93310. this._dragPlane.lookAt(this._lookAt);
  93311. }
  93312. else if (this._options.dragPlaneNormal) {
  93313. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  93314. this._dragPlane.position.copyFrom(this._pointA);
  93315. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  93316. this._dragPlane.lookAt(this._lookAt);
  93317. }
  93318. else {
  93319. this._dragPlane.position.copyFrom(this._pointA);
  93320. this._dragPlane.lookAt(ray.origin);
  93321. }
  93322. this._dragPlane.computeWorldMatrix(true);
  93323. };
  93324. /**
  93325. * Detaches the behavior from the mesh
  93326. */
  93327. PointerDragBehavior.prototype.detach = function () {
  93328. if (this._pointerObserver) {
  93329. this._scene.onPointerObservable.remove(this._pointerObserver);
  93330. }
  93331. if (this._beforeRenderObserver) {
  93332. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  93333. }
  93334. };
  93335. return PointerDragBehavior;
  93336. }());
  93337. BABYLON.PointerDragBehavior = PointerDragBehavior;
  93338. })(BABYLON || (BABYLON = {}));
  93339. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  93340. var BABYLON;
  93341. (function (BABYLON) {
  93342. /**
  93343. * A behavior that when attached to a mesh will allow the mesh to be scaled
  93344. */
  93345. var MultiPointerScaleBehavior = /** @class */ (function () {
  93346. function MultiPointerScaleBehavior() {
  93347. this._startDistance = 0;
  93348. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  93349. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  93350. this._sceneRenderObserver = null;
  93351. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  93352. this._dragBehaviorA.moveAttached = false;
  93353. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  93354. this._dragBehaviorB.moveAttached = false;
  93355. }
  93356. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  93357. /**
  93358. * The name of the behavior
  93359. */
  93360. get: function () {
  93361. return "MultiPointerScale";
  93362. },
  93363. enumerable: true,
  93364. configurable: true
  93365. });
  93366. /**
  93367. * Initializes the behavior
  93368. */
  93369. MultiPointerScaleBehavior.prototype.init = function () { };
  93370. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  93371. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  93372. };
  93373. /**
  93374. * Attaches the scale behavior the passed in mesh
  93375. * @param ownerNode The mesh that will be scaled around once attached
  93376. */
  93377. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  93378. var _this = this;
  93379. this._ownerNode = ownerNode;
  93380. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  93381. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  93382. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93383. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  93384. _this._dragBehaviorA.releaseDrag();
  93385. }
  93386. else {
  93387. _this._initialScale.copyFrom(ownerNode.scaling);
  93388. _this._startDistance = _this._getCurrentDistance();
  93389. }
  93390. }
  93391. });
  93392. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  93393. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93394. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  93395. _this._dragBehaviorB.releaseDrag();
  93396. }
  93397. else {
  93398. _this._initialScale.copyFrom(ownerNode.scaling);
  93399. _this._startDistance = _this._getCurrentDistance();
  93400. }
  93401. }
  93402. });
  93403. // Once both drag behaviors are active scale based on the distance between the two pointers
  93404. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  93405. behavior.onDragObservable.add(function () {
  93406. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93407. var ratio = _this._getCurrentDistance() / _this._startDistance;
  93408. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  93409. }
  93410. });
  93411. });
  93412. ownerNode.addBehavior(this._dragBehaviorA);
  93413. ownerNode.addBehavior(this._dragBehaviorB);
  93414. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  93415. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  93416. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93417. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  93418. if (change.length() > 0.01) {
  93419. ownerNode.scaling.addInPlace(change);
  93420. }
  93421. }
  93422. });
  93423. };
  93424. /**
  93425. * Detaches the behavior from the mesh
  93426. */
  93427. MultiPointerScaleBehavior.prototype.detach = function () {
  93428. var _this = this;
  93429. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  93430. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  93431. behavior.onDragStartObservable.clear();
  93432. behavior.onDragObservable.clear();
  93433. _this._ownerNode.removeBehavior(behavior);
  93434. });
  93435. };
  93436. return MultiPointerScaleBehavior;
  93437. }());
  93438. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  93439. })(BABYLON || (BABYLON = {}));
  93440. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  93441. var BABYLON;
  93442. (function (BABYLON) {
  93443. /**
  93444. * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  93445. */
  93446. var SixDofDragBehavior = /** @class */ (function () {
  93447. function SixDofDragBehavior() {
  93448. this._sceneRenderObserver = null;
  93449. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  93450. this._moving = false;
  93451. this._startingOrientation = new BABYLON.Quaternion();
  93452. /**
  93453. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3)
  93454. */
  93455. this.zDragFactor = 3;
  93456. /**
  93457. * If the behavior is currently in a dragging state
  93458. */
  93459. this.dragging = false;
  93460. /**
  93461. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  93462. */
  93463. this.dragDeltaRatio = 0.2;
  93464. /**
  93465. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  93466. */
  93467. this.currentDraggingPointerID = -1;
  93468. /**
  93469. * If camera controls should be detached during the drag
  93470. */
  93471. this.detachCameraControls = true;
  93472. }
  93473. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  93474. /**
  93475. * The name of the behavior
  93476. */
  93477. get: function () {
  93478. return "SixDofDrag";
  93479. },
  93480. enumerable: true,
  93481. configurable: true
  93482. });
  93483. /**
  93484. * Initializes the behavior
  93485. */
  93486. SixDofDragBehavior.prototype.init = function () { };
  93487. /**
  93488. * Attaches the scale behavior the passed in mesh
  93489. * @param ownerNode The mesh that will be scaled around once attached
  93490. */
  93491. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  93492. var _this = this;
  93493. this._ownerNode = ownerNode;
  93494. this._scene = this._ownerNode.getScene();
  93495. if (!SixDofDragBehavior._virtualScene) {
  93496. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  93497. this._scene.getEngine().scenes.pop();
  93498. }
  93499. var pickedMesh = null;
  93500. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  93501. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  93502. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  93503. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  93504. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  93505. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  93506. var pickPredicate = function (m) {
  93507. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  93508. };
  93509. var attachedElement = null;
  93510. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  93511. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  93512. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  93513. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  93514. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  93515. }
  93516. pickedMesh = _this._ownerNode;
  93517. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  93518. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  93519. // Set position and orientation of the controller
  93520. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  93521. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  93522. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  93523. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93524. pickedMesh.computeWorldMatrix();
  93525. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  93526. if (!pickedMesh.rotationQuaternion) {
  93527. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  93528. }
  93529. var oldParent = pickedMesh.parent;
  93530. pickedMesh.setParent(null);
  93531. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  93532. pickedMesh.setParent(oldParent);
  93533. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  93534. // Update state
  93535. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  93536. _this.dragging = true;
  93537. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  93538. // Detatch camera controls
  93539. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  93540. if (_this._scene.activeCamera.inputs.attachedElement) {
  93541. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  93542. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  93543. }
  93544. else {
  93545. attachedElement = null;
  93546. }
  93547. }
  93548. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  93549. }
  93550. }
  93551. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  93552. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  93553. _this.dragging = false;
  93554. _this._moving = false;
  93555. _this.currentDraggingPointerID = -1;
  93556. pickedMesh = null;
  93557. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93558. // Reattach camera controls
  93559. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  93560. _this._scene.activeCamera.attachControl(attachedElement, true);
  93561. }
  93562. }
  93563. }
  93564. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  93565. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  93566. var zDragFactor = _this.zDragFactor;
  93567. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  93568. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  93569. zDragFactor = 0;
  93570. }
  93571. // Calculate controller drag distance in controller space
  93572. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  93573. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  93574. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  93575. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  93576. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  93577. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  93578. if (_this._virtualDragMesh.position.z < 0) {
  93579. _this._virtualDragMesh.position.z = 0;
  93580. }
  93581. // Update the controller position
  93582. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  93583. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  93584. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93585. // Move the virtualObjectsPosition into the picked mesh's space if needed
  93586. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  93587. if (pickedMesh.parent) {
  93588. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  93589. }
  93590. if (!_this._moving) {
  93591. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  93592. }
  93593. _this._moving = true;
  93594. }
  93595. }
  93596. });
  93597. var tmpQuaternion = new BABYLON.Quaternion();
  93598. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  93599. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  93600. if (_this.dragging && _this._moving && pickedMesh) {
  93601. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  93602. // Slowly move mesh to avoid jitter
  93603. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  93604. // Get change in rotation
  93605. tmpQuaternion.copyFrom(_this._startingOrientation);
  93606. tmpQuaternion.x = -tmpQuaternion.x;
  93607. tmpQuaternion.y = -tmpQuaternion.y;
  93608. tmpQuaternion.z = -tmpQuaternion.z;
  93609. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  93610. // Convert change in rotation to only y axis rotation
  93611. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  93612. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  93613. // Slowly move mesh to avoid jitter
  93614. var oldParent = pickedMesh.parent;
  93615. pickedMesh.setParent(null);
  93616. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  93617. pickedMesh.setParent(oldParent);
  93618. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  93619. }
  93620. });
  93621. };
  93622. /**
  93623. * Detaches the behavior from the mesh
  93624. */
  93625. SixDofDragBehavior.prototype.detach = function () {
  93626. if (this._scene) {
  93627. this._scene.onPointerObservable.remove(this._pointerObserver);
  93628. }
  93629. if (this._ownerNode) {
  93630. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  93631. }
  93632. if (this._virtualOriginMesh) {
  93633. this._virtualOriginMesh.dispose();
  93634. }
  93635. if (this._virtualDragMesh) {
  93636. this._virtualDragMesh.dispose();
  93637. }
  93638. };
  93639. return SixDofDragBehavior;
  93640. }());
  93641. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  93642. })(BABYLON || (BABYLON = {}));
  93643. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  93644. var BABYLON;
  93645. (function (BABYLON) {
  93646. /**
  93647. * @hidden
  93648. */
  93649. var FaceDirectionInfo = /** @class */ (function () {
  93650. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  93651. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  93652. if (diff === void 0) { diff = 0; }
  93653. if (ignore === void 0) { ignore = false; }
  93654. this.direction = direction;
  93655. this.rotatedDirection = rotatedDirection;
  93656. this.diff = diff;
  93657. this.ignore = ignore;
  93658. }
  93659. return FaceDirectionInfo;
  93660. }());
  93661. /**
  93662. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  93663. */
  93664. var AttachToBoxBehavior = /** @class */ (function () {
  93665. /**
  93666. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  93667. * @param ui The transform node that should be attched to the mesh
  93668. */
  93669. function AttachToBoxBehavior(ui) {
  93670. this.ui = ui;
  93671. /**
  93672. * The name of the behavior
  93673. */
  93674. this.name = "AttachToBoxBehavior";
  93675. /**
  93676. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  93677. */
  93678. this.distanceAwayFromFace = 0.15;
  93679. /**
  93680. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  93681. */
  93682. this.distanceAwayFromBottomOfFace = 0.15;
  93683. this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];
  93684. this._tmpMatrix = new BABYLON.Matrix();
  93685. this._tmpVector = new BABYLON.Vector3();
  93686. this._zeroVector = BABYLON.Vector3.Zero();
  93687. this._lookAtTmpMatrix = new BABYLON.Matrix();
  93688. /* Does nothing */
  93689. }
  93690. /**
  93691. * Initializes the behavior
  93692. */
  93693. AttachToBoxBehavior.prototype.init = function () {
  93694. /* Does nothing */
  93695. };
  93696. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  93697. var _this = this;
  93698. // Go over each face and calculate the angle between the face's normal and targetDirection
  93699. this._faceVectors.forEach(function (v) {
  93700. if (!_this._target.rotationQuaternion) {
  93701. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  93702. }
  93703. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  93704. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  93705. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  93706. });
  93707. // Return the face information of the one with the normal closeset to target direction
  93708. return this._faceVectors.reduce(function (min, p) {
  93709. if (min.ignore) {
  93710. return p;
  93711. }
  93712. else if (p.ignore) {
  93713. return min;
  93714. }
  93715. else {
  93716. return min.diff < p.diff ? min : p;
  93717. }
  93718. }, this._faceVectors[0]);
  93719. };
  93720. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  93721. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  93722. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  93723. this._lookAtTmpMatrix.invert();
  93724. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  93725. };
  93726. /**
  93727. * Attaches the AttachToBoxBehavior to the passed in mesh
  93728. * @param target The mesh that the specified node will be attached to
  93729. */
  93730. AttachToBoxBehavior.prototype.attach = function (target) {
  93731. var _this = this;
  93732. this._target = target;
  93733. this._scene = this._target.getScene();
  93734. // Every frame, update the app bars position
  93735. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  93736. if (!_this._scene.activeCamera) {
  93737. return;
  93738. }
  93739. // Find the face closest to the cameras position
  93740. var cameraPos = _this._scene.activeCamera.position;
  93741. if (_this._scene.activeCamera.devicePosition) {
  93742. cameraPos = _this._scene.activeCamera.devicePosition;
  93743. }
  93744. var facing = _this._closestFace(cameraPos.subtract(target.position));
  93745. if (_this._scene.activeCamera.leftCamera) {
  93746. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  93747. }
  93748. else {
  93749. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  93750. }
  93751. // Get camera up direction
  93752. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  93753. // Ignore faces to not select a parrelel face for the up vector of the UI
  93754. _this._faceVectors.forEach(function (v) {
  93755. if (facing.direction.x && v.direction.x) {
  93756. v.ignore = true;
  93757. }
  93758. if (facing.direction.y && v.direction.y) {
  93759. v.ignore = true;
  93760. }
  93761. if (facing.direction.z && v.direction.z) {
  93762. v.ignore = true;
  93763. }
  93764. });
  93765. var facingUp = _this._closestFace(_this._tmpVector);
  93766. // Unignore faces
  93767. _this._faceVectors.forEach(function (v) {
  93768. v.ignore = false;
  93769. });
  93770. // Position the app bar on that face
  93771. _this.ui.position.copyFrom(target.position);
  93772. if (facing.direction.x) {
  93773. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93774. _this.ui.position.addInPlace(_this._tmpVector);
  93775. }
  93776. if (facing.direction.y) {
  93777. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93778. _this.ui.position.addInPlace(_this._tmpVector);
  93779. }
  93780. if (facing.direction.z) {
  93781. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93782. _this.ui.position.addInPlace(_this._tmpVector);
  93783. }
  93784. // Rotate to be oriented properly to the camera
  93785. if (!_this.ui.rotationQuaternion) {
  93786. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  93787. }
  93788. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  93789. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  93790. // Place ui the correct distance from the bottom of the mesh
  93791. if (facingUp.direction.x) {
  93792. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  93793. }
  93794. if (facingUp.direction.y) {
  93795. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  93796. }
  93797. if (facingUp.direction.z) {
  93798. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  93799. }
  93800. _this.ui.position.addInPlace(_this._tmpVector);
  93801. });
  93802. };
  93803. /**
  93804. * Detaches the behavior from the mesh
  93805. */
  93806. AttachToBoxBehavior.prototype.detach = function () {
  93807. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  93808. };
  93809. return AttachToBoxBehavior;
  93810. }());
  93811. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  93812. })(BABYLON || (BABYLON = {}));
  93813. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  93814. var BABYLON;
  93815. (function (BABYLON) {
  93816. /**
  93817. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  93818. */
  93819. var FadeInOutBehavior = /** @class */ (function () {
  93820. /**
  93821. * Instatiates the FadeInOutBehavior
  93822. */
  93823. function FadeInOutBehavior() {
  93824. var _this = this;
  93825. /**
  93826. * Time in milliseconds to delay before fading in (Default: 0)
  93827. */
  93828. this.delay = 0;
  93829. /**
  93830. * Time in milliseconds for the mesh to fade in (Default: 300)
  93831. */
  93832. this.fadeInTime = 300;
  93833. this._millisecondsPerFrame = 1000 / 60;
  93834. this._hovered = false;
  93835. this._hoverValue = 0;
  93836. this._ownerNode = null;
  93837. this._update = function () {
  93838. if (_this._ownerNode) {
  93839. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  93840. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  93841. if (_this._ownerNode.visibility > 1) {
  93842. _this._setAllVisibility(_this._ownerNode, 1);
  93843. _this._hoverValue = _this.fadeInTime + _this.delay;
  93844. return;
  93845. }
  93846. else if (_this._ownerNode.visibility < 0) {
  93847. _this._setAllVisibility(_this._ownerNode, 0);
  93848. if (_this._hoverValue < 0) {
  93849. _this._hoverValue = 0;
  93850. return;
  93851. }
  93852. }
  93853. setTimeout(_this._update, _this._millisecondsPerFrame);
  93854. }
  93855. };
  93856. }
  93857. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  93858. /**
  93859. * The name of the behavior
  93860. */
  93861. get: function () {
  93862. return "FadeInOut";
  93863. },
  93864. enumerable: true,
  93865. configurable: true
  93866. });
  93867. /**
  93868. * Initializes the behavior
  93869. */
  93870. FadeInOutBehavior.prototype.init = function () {
  93871. };
  93872. /**
  93873. * Attaches the fade behavior on the passed in mesh
  93874. * @param ownerNode The mesh that will be faded in/out once attached
  93875. */
  93876. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  93877. this._ownerNode = ownerNode;
  93878. this._setAllVisibility(this._ownerNode, 0);
  93879. };
  93880. /**
  93881. * Detaches the behavior from the mesh
  93882. */
  93883. FadeInOutBehavior.prototype.detach = function () {
  93884. this._ownerNode = null;
  93885. };
  93886. /**
  93887. * Triggers the mesh to begin fading in or out
  93888. * @param value if the object should fade in or out (true to fade in)
  93889. */
  93890. FadeInOutBehavior.prototype.fadeIn = function (value) {
  93891. this._hovered = value;
  93892. this._update();
  93893. };
  93894. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  93895. var _this = this;
  93896. mesh.visibility = value;
  93897. mesh.getChildMeshes().forEach(function (c) {
  93898. _this._setAllVisibility(c, value);
  93899. });
  93900. };
  93901. return FadeInOutBehavior;
  93902. }());
  93903. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  93904. })(BABYLON || (BABYLON = {}));
  93905. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  93906. var BABYLON;
  93907. (function (BABYLON) {
  93908. /**
  93909. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  93910. */
  93911. var Gizmo = /** @class */ (function () {
  93912. /**
  93913. * Creates a gizmo
  93914. * @param gizmoLayer The utility layer the gizmo will be added to
  93915. */
  93916. function Gizmo(
  93917. /** The utility layer the gizmo will be added to */
  93918. gizmoLayer) {
  93919. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93920. var _this = this;
  93921. this.gizmoLayer = gizmoLayer;
  93922. /**
  93923. * Ratio for the scale of the gizmo (Default: 1)
  93924. */
  93925. this.scaleRatio = 1;
  93926. this._tmpMatrix = new BABYLON.Matrix();
  93927. /**
  93928. * If a custom mesh has been set (Default: false)
  93929. */
  93930. this._customMeshSet = false;
  93931. /**
  93932. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  93933. */
  93934. this.updateGizmoRotationToMatchAttachedMesh = true;
  93935. /**
  93936. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  93937. */
  93938. this.updateGizmoPositionToMatchAttachedMesh = true;
  93939. /**
  93940. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  93941. */
  93942. this._updateScale = true;
  93943. this._interactionsEnabled = true;
  93944. this._tempVector = new BABYLON.Vector3();
  93945. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  93946. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  93947. _this._update();
  93948. });
  93949. this.attachedMesh = null;
  93950. }
  93951. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  93952. /**
  93953. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  93954. * * When set, interactions will be enabled
  93955. */
  93956. get: function () {
  93957. return this._attachedMesh;
  93958. },
  93959. set: function (value) {
  93960. this._attachedMesh = value;
  93961. this._rootMesh.setEnabled(value ? true : false);
  93962. this._attachedMeshChanged(value);
  93963. },
  93964. enumerable: true,
  93965. configurable: true
  93966. });
  93967. /**
  93968. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  93969. * @param mesh The mesh to replace the default mesh of the gizmo
  93970. */
  93971. Gizmo.prototype.setCustomMesh = function (mesh) {
  93972. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  93973. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  93974. }
  93975. this._rootMesh.getChildMeshes().forEach(function (c) {
  93976. c.dispose();
  93977. });
  93978. mesh.parent = this._rootMesh;
  93979. this._customMeshSet = true;
  93980. };
  93981. Gizmo.prototype._attachedMeshChanged = function (value) {
  93982. };
  93983. /**
  93984. * @hidden
  93985. * Updates the gizmo to match the attached mesh's position/rotation
  93986. */
  93987. Gizmo.prototype._update = function () {
  93988. if (this.attachedMesh) {
  93989. if (this.updateGizmoRotationToMatchAttachedMesh) {
  93990. if (!this._rootMesh.rotationQuaternion) {
  93991. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  93992. }
  93993. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  93994. this._tempVector.copyFrom(this.attachedMesh.scaling);
  93995. if (this.attachedMesh.scaling.x < 0) {
  93996. this.attachedMesh.scaling.x *= -1;
  93997. }
  93998. if (this.attachedMesh.scaling.y < 0) {
  93999. this.attachedMesh.scaling.y *= -1;
  94000. }
  94001. if (this.attachedMesh.scaling.z < 0) {
  94002. this.attachedMesh.scaling.z *= -1;
  94003. }
  94004. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  94005. this.attachedMesh.scaling.copyFrom(this._tempVector);
  94006. this.attachedMesh.computeWorldMatrix();
  94007. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  94008. }
  94009. else if (this._rootMesh.rotationQuaternion) {
  94010. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  94011. }
  94012. if (this.updateGizmoPositionToMatchAttachedMesh) {
  94013. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  94014. }
  94015. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  94016. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  94017. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  94018. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  94019. }
  94020. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  94021. var dist = this._tempVector.length() * this.scaleRatio;
  94022. this._rootMesh.scaling.set(dist, dist, dist);
  94023. }
  94024. }
  94025. };
  94026. /**
  94027. * Disposes of the gizmo
  94028. */
  94029. Gizmo.prototype.dispose = function () {
  94030. this._rootMesh.dispose();
  94031. if (this._beforeRenderObserver) {
  94032. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  94033. }
  94034. };
  94035. return Gizmo;
  94036. }());
  94037. BABYLON.Gizmo = Gizmo;
  94038. })(BABYLON || (BABYLON = {}));
  94039. //# sourceMappingURL=babylon.gizmo.js.map
  94040. var BABYLON;
  94041. (function (BABYLON) {
  94042. /**
  94043. * Single axis drag gizmo
  94044. */
  94045. var AxisDragGizmo = /** @class */ (function (_super) {
  94046. __extends(AxisDragGizmo, _super);
  94047. /**
  94048. * Creates an AxisDragGizmo
  94049. * @param gizmoLayer The utility layer the gizmo will be added to
  94050. * @param dragAxis The axis which the gizmo will be able to drag on
  94051. * @param color The color of the gizmo
  94052. */
  94053. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  94054. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94055. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94056. var _this = _super.call(this, gizmoLayer) || this;
  94057. _this._pointerObserver = null;
  94058. /**
  94059. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94060. */
  94061. _this.snapDistance = 0;
  94062. /**
  94063. * Event that fires each time the gizmo snaps to a new location.
  94064. * * snapDistance is the the change in distance
  94065. */
  94066. _this.onSnapObservable = new BABYLON.Observable();
  94067. // Create Material
  94068. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94069. coloredMaterial.disableLighting = true;
  94070. coloredMaterial.emissiveColor = color;
  94071. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94072. hoverMaterial.disableLighting = true;
  94073. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94074. // Build mesh on root node
  94075. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94076. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  94077. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  94078. arrowTail.color = coloredMaterial.emissiveColor;
  94079. arrow.addChild(arrowMesh);
  94080. arrow.addChild(arrowTail);
  94081. // Position arrow pointing in its drag axis
  94082. arrowMesh.scaling.scaleInPlace(0.05);
  94083. arrowMesh.material = coloredMaterial;
  94084. arrowMesh.rotation.x = Math.PI / 2;
  94085. arrowMesh.position.z += 0.3;
  94086. arrowTail.scaling.scaleInPlace(0.26);
  94087. arrowTail.rotation.x = Math.PI / 2;
  94088. arrowTail.material = coloredMaterial;
  94089. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  94090. arrow.scaling.scaleInPlace(1 / 3);
  94091. _this._rootMesh.addChild(arrow);
  94092. var currentSnapDragDistance = 0;
  94093. var tmpVector = new BABYLON.Vector3();
  94094. var tmpSnapEvent = { snapDistance: 0 };
  94095. // Add drag behavior to handle events when the gizmo is dragged
  94096. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  94097. _this.dragBehavior.moveAttached = false;
  94098. _this._rootMesh.addBehavior(_this.dragBehavior);
  94099. var localDelta = new BABYLON.Vector3();
  94100. var tmpMatrix = new BABYLON.Matrix();
  94101. _this.dragBehavior.onDragObservable.add(function (event) {
  94102. if (_this.attachedMesh) {
  94103. // Convert delta to local translation if it has a parent
  94104. if (_this.attachedMesh.parent) {
  94105. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  94106. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  94107. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  94108. }
  94109. else {
  94110. localDelta.copyFrom(event.delta);
  94111. }
  94112. // Snapping logic
  94113. if (_this.snapDistance == 0) {
  94114. _this.attachedMesh.position.addInPlace(localDelta);
  94115. }
  94116. else {
  94117. currentSnapDragDistance += event.dragDistance;
  94118. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  94119. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  94120. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  94121. localDelta.normalizeToRef(tmpVector);
  94122. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  94123. _this.attachedMesh.position.addInPlace(tmpVector);
  94124. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  94125. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  94126. }
  94127. }
  94128. }
  94129. });
  94130. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94131. if (_this._customMeshSet) {
  94132. return;
  94133. }
  94134. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  94135. var material = isHovered ? hoverMaterial : coloredMaterial;
  94136. _this._rootMesh.getChildMeshes().forEach(function (m) {
  94137. m.material = material;
  94138. if (m.color) {
  94139. m.color = material.emissiveColor;
  94140. }
  94141. });
  94142. });
  94143. return _this;
  94144. }
  94145. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  94146. if (this.dragBehavior) {
  94147. this.dragBehavior.enabled = value ? true : false;
  94148. }
  94149. };
  94150. /**
  94151. * Disposes of the gizmo
  94152. */
  94153. AxisDragGizmo.prototype.dispose = function () {
  94154. this.onSnapObservable.clear();
  94155. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94156. this.dragBehavior.detach();
  94157. _super.prototype.dispose.call(this);
  94158. };
  94159. return AxisDragGizmo;
  94160. }(BABYLON.Gizmo));
  94161. BABYLON.AxisDragGizmo = AxisDragGizmo;
  94162. })(BABYLON || (BABYLON = {}));
  94163. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  94164. var BABYLON;
  94165. (function (BABYLON) {
  94166. /**
  94167. * Single axis scale gizmo
  94168. */
  94169. var AxisScaleGizmo = /** @class */ (function (_super) {
  94170. __extends(AxisScaleGizmo, _super);
  94171. /**
  94172. * Creates an AxisScaleGizmo
  94173. * @param gizmoLayer The utility layer the gizmo will be added to
  94174. * @param dragAxis The axis which the gizmo will be able to scale on
  94175. * @param color The color of the gizmo
  94176. */
  94177. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  94178. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94179. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94180. var _this = _super.call(this, gizmoLayer) || this;
  94181. _this._pointerObserver = null;
  94182. /**
  94183. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94184. */
  94185. _this.snapDistance = 0;
  94186. /**
  94187. * Event that fires each time the gizmo snaps to a new location.
  94188. * * snapDistance is the the change in distance
  94189. */
  94190. _this.onSnapObservable = new BABYLON.Observable();
  94191. /**
  94192. * If the scaling operation should be done on all axis (default: false)
  94193. */
  94194. _this.uniformScaling = false;
  94195. // Create Material
  94196. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94197. _this._coloredMaterial.disableLighting = true;
  94198. _this._coloredMaterial.emissiveColor = color;
  94199. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94200. hoverMaterial.disableLighting = true;
  94201. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94202. // Build mesh on root node
  94203. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94204. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  94205. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  94206. arrowTail.color = _this._coloredMaterial.emissiveColor;
  94207. arrow.addChild(arrowMesh);
  94208. arrow.addChild(arrowTail);
  94209. // Position arrow pointing in its drag axis
  94210. arrowMesh.scaling.scaleInPlace(0.1);
  94211. arrowMesh.material = _this._coloredMaterial;
  94212. arrowMesh.rotation.x = Math.PI / 2;
  94213. arrowMesh.position.z += 0.3;
  94214. arrowTail.scaling.scaleInPlace(0.26);
  94215. arrowTail.rotation.x = Math.PI / 2;
  94216. arrowTail.material = _this._coloredMaterial;
  94217. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  94218. _this._rootMesh.addChild(arrow);
  94219. arrow.scaling.scaleInPlace(1 / 3);
  94220. // Add drag behavior to handle events when the gizmo is dragged
  94221. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  94222. _this.dragBehavior.moveAttached = false;
  94223. _this._rootMesh.addBehavior(_this.dragBehavior);
  94224. var currentSnapDragDistance = 0;
  94225. var tmpVector = new BABYLON.Vector3();
  94226. var tmpSnapEvent = { snapDistance: 0 };
  94227. _this.dragBehavior.onDragObservable.add(function (event) {
  94228. if (_this.attachedMesh) {
  94229. // Snapping logic
  94230. var snapped = false;
  94231. var dragSteps = 0;
  94232. if (_this.uniformScaling) {
  94233. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  94234. if (tmpVector.y < 0) {
  94235. tmpVector.scaleInPlace(-1);
  94236. }
  94237. }
  94238. else {
  94239. tmpVector.copyFrom(dragAxis);
  94240. }
  94241. if (_this.snapDistance == 0) {
  94242. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  94243. }
  94244. else {
  94245. currentSnapDragDistance += event.dragDistance;
  94246. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  94247. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  94248. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  94249. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  94250. snapped = true;
  94251. }
  94252. else {
  94253. tmpVector.scaleInPlace(0);
  94254. }
  94255. }
  94256. _this.attachedMesh.scaling.addInPlace(tmpVector);
  94257. if (snapped) {
  94258. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  94259. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  94260. }
  94261. }
  94262. });
  94263. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94264. if (_this._customMeshSet) {
  94265. return;
  94266. }
  94267. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  94268. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  94269. _this._rootMesh.getChildMeshes().forEach(function (m) {
  94270. m.material = material;
  94271. if (m.color) {
  94272. m.color = material.emissiveColor;
  94273. }
  94274. });
  94275. });
  94276. return _this;
  94277. }
  94278. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  94279. if (this.dragBehavior) {
  94280. this.dragBehavior.enabled = value ? true : false;
  94281. }
  94282. };
  94283. /**
  94284. * Disposes of the gizmo
  94285. */
  94286. AxisScaleGizmo.prototype.dispose = function () {
  94287. this.onSnapObservable.clear();
  94288. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94289. this.dragBehavior.detach();
  94290. _super.prototype.dispose.call(this);
  94291. };
  94292. /**
  94293. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  94294. * @param mesh The mesh to replace the default mesh of the gizmo
  94295. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  94296. */
  94297. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  94298. var _this = this;
  94299. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  94300. _super.prototype.setCustomMesh.call(this, mesh);
  94301. if (useGizmoMaterial) {
  94302. this._rootMesh.getChildMeshes().forEach(function (m) {
  94303. m.material = _this._coloredMaterial;
  94304. if (m.color) {
  94305. m.color = _this._coloredMaterial.emissiveColor;
  94306. }
  94307. });
  94308. this._customMeshSet = false;
  94309. }
  94310. };
  94311. return AxisScaleGizmo;
  94312. }(BABYLON.Gizmo));
  94313. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  94314. })(BABYLON || (BABYLON = {}));
  94315. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  94316. var BABYLON;
  94317. (function (BABYLON) {
  94318. /**
  94319. * Single plane rotation gizmo
  94320. */
  94321. var PlaneRotationGizmo = /** @class */ (function (_super) {
  94322. __extends(PlaneRotationGizmo, _super);
  94323. /**
  94324. * Creates a PlaneRotationGizmo
  94325. * @param gizmoLayer The utility layer the gizmo will be added to
  94326. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  94327. * @param color The color of the gizmo
  94328. */
  94329. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  94330. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94331. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94332. var _this = _super.call(this, gizmoLayer) || this;
  94333. _this._pointerObserver = null;
  94334. /**
  94335. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  94336. */
  94337. _this.snapDistance = 0;
  94338. /**
  94339. * Event that fires each time the gizmo snaps to a new location.
  94340. * * snapDistance is the the change in distance
  94341. */
  94342. _this.onSnapObservable = new BABYLON.Observable();
  94343. // Create Material
  94344. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94345. coloredMaterial.disableLighting = true;
  94346. coloredMaterial.emissiveColor = color;
  94347. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94348. hoverMaterial.disableLighting = true;
  94349. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94350. // Build mesh on root node
  94351. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94352. // Create circle out of lines
  94353. var tessellation = 20;
  94354. var radius = 0.8;
  94355. var points = new Array();
  94356. for (var i = 0; i < tessellation; i++) {
  94357. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  94358. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  94359. }
  94360. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  94361. rotationMesh.color = coloredMaterial.emissiveColor;
  94362. // Position arrow pointing in its drag axis
  94363. rotationMesh.scaling.scaleInPlace(0.26);
  94364. rotationMesh.material = coloredMaterial;
  94365. rotationMesh.rotation.x = Math.PI / 2;
  94366. parentMesh.addChild(rotationMesh);
  94367. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  94368. _this._rootMesh.addChild(parentMesh);
  94369. parentMesh.scaling.scaleInPlace(1 / 3);
  94370. // Add drag behavior to handle events when the gizmo is dragged
  94371. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  94372. _this.dragBehavior.moveAttached = false;
  94373. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  94374. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  94375. _this._rootMesh.addBehavior(_this.dragBehavior);
  94376. var lastDragPosition = new BABYLON.Vector3();
  94377. _this.dragBehavior.onDragStartObservable.add(function (e) {
  94378. if (_this.attachedMesh) {
  94379. lastDragPosition.copyFrom(e.dragPlanePoint);
  94380. }
  94381. });
  94382. var rotationMatrix = new BABYLON.Matrix();
  94383. var planeNormalTowardsCamera = new BABYLON.Vector3();
  94384. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  94385. var tmpSnapEvent = { snapDistance: 0 };
  94386. var currentSnapDragDistance = 0;
  94387. var tmpMatrix = new BABYLON.Matrix();
  94388. var tmpVector = new BABYLON.Vector3();
  94389. var amountToRotate = new BABYLON.Quaternion();
  94390. _this.dragBehavior.onDragObservable.add(function (event) {
  94391. if (_this.attachedMesh) {
  94392. if (!_this.attachedMesh.rotationQuaternion) {
  94393. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  94394. }
  94395. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  94396. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  94397. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  94398. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  94399. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  94400. var angle = Math.atan2(cross.length(), dot);
  94401. planeNormalTowardsCamera.copyFrom(planeNormal);
  94402. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  94403. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  94404. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  94405. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  94406. }
  94407. // Flip up vector depending on which side the camera is on
  94408. if (gizmoLayer.utilityLayerScene.activeCamera) {
  94409. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  94410. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  94411. planeNormalTowardsCamera.scaleInPlace(-1);
  94412. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  94413. }
  94414. }
  94415. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  94416. if (halfCircleSide)
  94417. angle = -angle;
  94418. // Snapping logic
  94419. var snapped = false;
  94420. if (_this.snapDistance != 0) {
  94421. currentSnapDragDistance += angle;
  94422. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  94423. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  94424. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  94425. angle = _this.snapDistance * dragSteps;
  94426. snapped = true;
  94427. }
  94428. else {
  94429. angle = 0;
  94430. }
  94431. }
  94432. // If the mesh has a parent, convert needed world rotation to local rotation
  94433. tmpMatrix.reset();
  94434. if (_this.attachedMesh.parent) {
  94435. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  94436. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  94437. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  94438. }
  94439. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  94440. var quaternionCoefficient = Math.sin(angle / 2);
  94441. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  94442. // If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis
  94443. if (tmpMatrix.determinant() > 0) {
  94444. amountToRotate.toEulerAnglesToRef(tmpVector);
  94445. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  94446. }
  94447. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  94448. // Rotate selected mesh quaternion over fixed axis
  94449. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  94450. }
  94451. else {
  94452. // Rotate selected mesh quaternion over rotated axis
  94453. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  94454. }
  94455. lastDragPosition.copyFrom(event.dragPlanePoint);
  94456. if (snapped) {
  94457. tmpSnapEvent.snapDistance = angle;
  94458. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  94459. }
  94460. }
  94461. });
  94462. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94463. if (_this._customMeshSet) {
  94464. return;
  94465. }
  94466. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  94467. var material = isHovered ? hoverMaterial : coloredMaterial;
  94468. _this._rootMesh.getChildMeshes().forEach(function (m) {
  94469. m.material = material;
  94470. if (m.color) {
  94471. m.color = material.emissiveColor;
  94472. }
  94473. });
  94474. });
  94475. return _this;
  94476. }
  94477. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  94478. if (this.dragBehavior) {
  94479. this.dragBehavior.enabled = value ? true : false;
  94480. }
  94481. };
  94482. /**
  94483. * Disposes of the gizmo
  94484. */
  94485. PlaneRotationGizmo.prototype.dispose = function () {
  94486. this.onSnapObservable.clear();
  94487. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94488. this.dragBehavior.detach();
  94489. _super.prototype.dispose.call(this);
  94490. };
  94491. return PlaneRotationGizmo;
  94492. }(BABYLON.Gizmo));
  94493. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  94494. })(BABYLON || (BABYLON = {}));
  94495. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  94496. var BABYLON;
  94497. (function (BABYLON) {
  94498. /**
  94499. * Gizmo that enables dragging a mesh along 3 axis
  94500. */
  94501. var PositionGizmo = /** @class */ (function (_super) {
  94502. __extends(PositionGizmo, _super);
  94503. /**
  94504. * Creates a PositionGizmo
  94505. * @param gizmoLayer The utility layer the gizmo will be added to
  94506. */
  94507. function PositionGizmo(gizmoLayer) {
  94508. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94509. var _this = _super.call(this, gizmoLayer) || this;
  94510. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94511. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94512. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94513. _this.attachedMesh = null;
  94514. return _this;
  94515. }
  94516. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  94517. set: function (mesh) {
  94518. if (this.xGizmo) {
  94519. this.xGizmo.attachedMesh = mesh;
  94520. this.yGizmo.attachedMesh = mesh;
  94521. this.zGizmo.attachedMesh = mesh;
  94522. }
  94523. },
  94524. enumerable: true,
  94525. configurable: true
  94526. });
  94527. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94528. get: function () {
  94529. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94530. },
  94531. set: function (value) {
  94532. if (this.xGizmo) {
  94533. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94534. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94535. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94536. }
  94537. },
  94538. enumerable: true,
  94539. configurable: true
  94540. });
  94541. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  94542. get: function () {
  94543. return this.xGizmo.snapDistance;
  94544. },
  94545. /**
  94546. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94547. */
  94548. set: function (value) {
  94549. if (this.xGizmo) {
  94550. this.xGizmo.snapDistance = value;
  94551. this.yGizmo.snapDistance = value;
  94552. this.zGizmo.snapDistance = value;
  94553. }
  94554. },
  94555. enumerable: true,
  94556. configurable: true
  94557. });
  94558. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  94559. get: function () {
  94560. return this.xGizmo.scaleRatio;
  94561. },
  94562. /**
  94563. * Ratio for the scale of the gizmo (Default: 1)
  94564. */
  94565. set: function (value) {
  94566. if (this.xGizmo) {
  94567. this.xGizmo.scaleRatio = value;
  94568. this.yGizmo.scaleRatio = value;
  94569. this.zGizmo.scaleRatio = value;
  94570. }
  94571. },
  94572. enumerable: true,
  94573. configurable: true
  94574. });
  94575. /**
  94576. * Disposes of the gizmo
  94577. */
  94578. PositionGizmo.prototype.dispose = function () {
  94579. this.xGizmo.dispose();
  94580. this.yGizmo.dispose();
  94581. this.zGizmo.dispose();
  94582. };
  94583. /**
  94584. * CustomMeshes are not supported by this gizmo
  94585. * @param mesh The mesh to replace the default mesh of the gizmo
  94586. */
  94587. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  94588. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  94589. };
  94590. return PositionGizmo;
  94591. }(BABYLON.Gizmo));
  94592. BABYLON.PositionGizmo = PositionGizmo;
  94593. })(BABYLON || (BABYLON = {}));
  94594. //# sourceMappingURL=babylon.positionGizmo.js.map
  94595. var BABYLON;
  94596. (function (BABYLON) {
  94597. /**
  94598. * Gizmo that enables rotating a mesh along 3 axis
  94599. */
  94600. var RotationGizmo = /** @class */ (function (_super) {
  94601. __extends(RotationGizmo, _super);
  94602. /**
  94603. * Creates a RotationGizmo
  94604. * @param gizmoLayer The utility layer the gizmo will be added to
  94605. */
  94606. function RotationGizmo(gizmoLayer) {
  94607. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94608. var _this = _super.call(this, gizmoLayer) || this;
  94609. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94610. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94611. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94612. _this.attachedMesh = null;
  94613. return _this;
  94614. }
  94615. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  94616. set: function (mesh) {
  94617. if (this.xGizmo) {
  94618. this.xGizmo.attachedMesh = mesh;
  94619. this.yGizmo.attachedMesh = mesh;
  94620. this.zGizmo.attachedMesh = mesh;
  94621. }
  94622. },
  94623. enumerable: true,
  94624. configurable: true
  94625. });
  94626. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94627. get: function () {
  94628. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94629. },
  94630. set: function (value) {
  94631. if (this.xGizmo) {
  94632. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94633. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94634. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94635. }
  94636. },
  94637. enumerable: true,
  94638. configurable: true
  94639. });
  94640. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  94641. get: function () {
  94642. return this.xGizmo.snapDistance;
  94643. },
  94644. /**
  94645. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94646. */
  94647. set: function (value) {
  94648. if (this.xGizmo) {
  94649. this.xGizmo.snapDistance = value;
  94650. this.yGizmo.snapDistance = value;
  94651. this.zGizmo.snapDistance = value;
  94652. }
  94653. },
  94654. enumerable: true,
  94655. configurable: true
  94656. });
  94657. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  94658. get: function () {
  94659. return this.xGizmo.scaleRatio;
  94660. },
  94661. /**
  94662. * Ratio for the scale of the gizmo (Default: 1)
  94663. */
  94664. set: function (value) {
  94665. if (this.xGizmo) {
  94666. this.xGizmo.scaleRatio = value;
  94667. this.yGizmo.scaleRatio = value;
  94668. this.zGizmo.scaleRatio = value;
  94669. }
  94670. },
  94671. enumerable: true,
  94672. configurable: true
  94673. });
  94674. /**
  94675. * Disposes of the gizmo
  94676. */
  94677. RotationGizmo.prototype.dispose = function () {
  94678. this.xGizmo.dispose();
  94679. this.yGizmo.dispose();
  94680. this.zGizmo.dispose();
  94681. };
  94682. /**
  94683. * CustomMeshes are not supported by this gizmo
  94684. * @param mesh The mesh to replace the default mesh of the gizmo
  94685. */
  94686. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  94687. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  94688. };
  94689. return RotationGizmo;
  94690. }(BABYLON.Gizmo));
  94691. BABYLON.RotationGizmo = RotationGizmo;
  94692. })(BABYLON || (BABYLON = {}));
  94693. //# sourceMappingURL=babylon.rotationGizmo.js.map
  94694. var BABYLON;
  94695. (function (BABYLON) {
  94696. /**
  94697. * Gizmo that enables scaling a mesh along 3 axis
  94698. */
  94699. var ScaleGizmo = /** @class */ (function (_super) {
  94700. __extends(ScaleGizmo, _super);
  94701. /**
  94702. * Creates a ScaleGizmo
  94703. * @param gizmoLayer The utility layer the gizmo will be added to
  94704. */
  94705. function ScaleGizmo(gizmoLayer) {
  94706. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94707. var _this = _super.call(this, gizmoLayer) || this;
  94708. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94709. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94710. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94711. // Create uniform scale gizmo
  94712. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  94713. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94714. _this._uniformGizmo.uniformScaling = true;
  94715. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  94716. octahedron.scaling.scaleInPlace(0.007);
  94717. _this._uniformGizmo.setCustomMesh(octahedron, true);
  94718. _this.attachedMesh = null;
  94719. return _this;
  94720. }
  94721. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  94722. set: function (mesh) {
  94723. if (this.xGizmo) {
  94724. this.xGizmo.attachedMesh = mesh;
  94725. this.yGizmo.attachedMesh = mesh;
  94726. this.zGizmo.attachedMesh = mesh;
  94727. this._uniformGizmo.attachedMesh = mesh;
  94728. }
  94729. },
  94730. enumerable: true,
  94731. configurable: true
  94732. });
  94733. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94734. get: function () {
  94735. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94736. },
  94737. set: function (value) {
  94738. if (this.xGizmo) {
  94739. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94740. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94741. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94742. }
  94743. },
  94744. enumerable: true,
  94745. configurable: true
  94746. });
  94747. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  94748. get: function () {
  94749. return this.xGizmo.snapDistance;
  94750. },
  94751. /**
  94752. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94753. */
  94754. set: function (value) {
  94755. if (this.xGizmo) {
  94756. this.xGizmo.snapDistance = value;
  94757. this.yGizmo.snapDistance = value;
  94758. this.zGizmo.snapDistance = value;
  94759. this._uniformGizmo.snapDistance = value;
  94760. }
  94761. },
  94762. enumerable: true,
  94763. configurable: true
  94764. });
  94765. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  94766. get: function () {
  94767. return this.xGizmo.scaleRatio;
  94768. },
  94769. /**
  94770. * Ratio for the scale of the gizmo (Default: 1)
  94771. */
  94772. set: function (value) {
  94773. if (this.xGizmo) {
  94774. this.xGizmo.scaleRatio = value;
  94775. this.yGizmo.scaleRatio = value;
  94776. this.zGizmo.scaleRatio = value;
  94777. this._uniformGizmo.scaleRatio = value;
  94778. }
  94779. },
  94780. enumerable: true,
  94781. configurable: true
  94782. });
  94783. /**
  94784. * Disposes of the gizmo
  94785. */
  94786. ScaleGizmo.prototype.dispose = function () {
  94787. this.xGizmo.dispose();
  94788. this.yGizmo.dispose();
  94789. this.zGizmo.dispose();
  94790. this._uniformGizmo.dispose();
  94791. };
  94792. return ScaleGizmo;
  94793. }(BABYLON.Gizmo));
  94794. BABYLON.ScaleGizmo = ScaleGizmo;
  94795. })(BABYLON || (BABYLON = {}));
  94796. //# sourceMappingURL=babylon.scaleGizmo.js.map
  94797. var BABYLON;
  94798. (function (BABYLON) {
  94799. /**
  94800. * Bounding box gizmo
  94801. */
  94802. var BoundingBoxGizmo = /** @class */ (function (_super) {
  94803. __extends(BoundingBoxGizmo, _super);
  94804. /**
  94805. * Creates an BoundingBoxGizmo
  94806. * @param gizmoLayer The utility layer the gizmo will be added to
  94807. * @param color The color of the gizmo
  94808. */
  94809. function BoundingBoxGizmo(color, gizmoLayer) {
  94810. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94811. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  94812. var _this = _super.call(this, gizmoLayer) || this;
  94813. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  94814. _this._renderObserver = null;
  94815. _this._pointerObserver = null;
  94816. _this._scaleDragSpeed = 0.2;
  94817. _this._tmpQuaternion = new BABYLON.Quaternion();
  94818. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  94819. _this._tmpRotationMatrix = new BABYLON.Matrix();
  94820. /**
  94821. * If child meshes should be ignored when calculating the boudning box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false)
  94822. */
  94823. _this.ignoreChildren = false;
  94824. /**
  94825. * Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null)
  94826. */
  94827. _this.includeChildPredicate = null;
  94828. /**
  94829. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  94830. */
  94831. _this.rotationSphereSize = 0.1;
  94832. /**
  94833. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  94834. */
  94835. _this.scaleBoxSize = 0.1;
  94836. /**
  94837. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  94838. */
  94839. _this.fixedDragMeshScreenSize = false;
  94840. /**
  94841. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  94842. */
  94843. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  94844. /**
  94845. * Fired when a rotation sphere or scale box is dragged
  94846. */
  94847. _this.onDragStartObservable = new BABYLON.Observable();
  94848. /**
  94849. * Fired when a scale box is dragged
  94850. */
  94851. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  94852. /**
  94853. * Fired when a scale box drag is ended
  94854. */
  94855. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  94856. /**
  94857. * Fired when a rotation sphere is dragged
  94858. */
  94859. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  94860. /**
  94861. * Fired when a rotation sphere drag is ended
  94862. */
  94863. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  94864. /**
  94865. * Relative bounding box pivot used when scaling the attached mesh. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null)
  94866. */
  94867. _this.scalePivot = null;
  94868. _this._existingMeshScale = new BABYLON.Vector3();
  94869. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  94870. _this._updateScale = false;
  94871. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  94872. // Create Materials
  94873. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94874. coloredMaterial.disableLighting = true;
  94875. coloredMaterial.emissiveColor = color;
  94876. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94877. hoverColoredMaterial.disableLighting = true;
  94878. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94879. // Build bounding box out of lines
  94880. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94881. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  94882. var lines = [];
  94883. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  94884. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  94885. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94886. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  94887. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94888. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  94889. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94890. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94891. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94892. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94893. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94894. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  94895. lines.forEach(function (l) {
  94896. l.color = color;
  94897. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  94898. l.isPickable = false;
  94899. _this._lineBoundingBox.addChild(l);
  94900. });
  94901. _this._rootMesh.addChild(_this._lineBoundingBox);
  94902. // Create rotation spheres
  94903. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94904. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  94905. var _loop_1 = function (i_1) {
  94906. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  94907. sphere.rotationQuaternion = new BABYLON.Quaternion();
  94908. sphere.material = coloredMaterial;
  94909. // Drag behavior
  94910. _dragBehavior = new BABYLON.PointerDragBehavior({});
  94911. _dragBehavior.moveAttached = false;
  94912. _dragBehavior.updateDragPlane = false;
  94913. sphere.addBehavior(_dragBehavior);
  94914. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  94915. var totalTurnAmountOfDrag = 0;
  94916. _dragBehavior.onDragStartObservable.add(function (event) {
  94917. startingTurnDirection.copyFrom(sphere.forward);
  94918. totalTurnAmountOfDrag = 0;
  94919. });
  94920. _dragBehavior.onDragObservable.add(function (event) {
  94921. _this.onRotationSphereDragObservable.notifyObservers({});
  94922. if (_this.attachedMesh) {
  94923. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  94924. var worldDragDirection = startingTurnDirection;
  94925. // Project the world right on to the drag plane
  94926. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  94927. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  94928. // project drag delta on to the resulting drag axis and rotate based on that
  94929. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  94930. // Make rotation relative to size of mesh.
  94931. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  94932. // Rotate based on axis
  94933. if (!_this.attachedMesh.rotationQuaternion) {
  94934. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  94935. }
  94936. if (!_this._anchorMesh.rotationQuaternion) {
  94937. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  94938. }
  94939. // Do not allow the object to turn more than a full circle
  94940. totalTurnAmountOfDrag += projectDist;
  94941. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  94942. if (i_1 >= 8) {
  94943. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  94944. }
  94945. else if (i_1 >= 4) {
  94946. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  94947. }
  94948. else {
  94949. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  94950. }
  94951. // Rotate around center of bounding box
  94952. _this._anchorMesh.addChild(_this.attachedMesh);
  94953. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  94954. _this._anchorMesh.removeChild(_this.attachedMesh);
  94955. }
  94956. _this.updateBoundingBox();
  94957. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  94958. }
  94959. });
  94960. // Selection/deselection
  94961. _dragBehavior.onDragStartObservable.add(function () {
  94962. _this.onDragStartObservable.notifyObservers({});
  94963. _this._selectNode(sphere);
  94964. });
  94965. _dragBehavior.onDragEndObservable.add(function () {
  94966. _this.onRotationSphereDragEndObservable.notifyObservers({});
  94967. _this._selectNode(null);
  94968. });
  94969. this_1._rotateSpheresParent.addChild(sphere);
  94970. };
  94971. var this_1 = this, _dragBehavior;
  94972. for (var i_1 = 0; i_1 < 12; i_1++) {
  94973. _loop_1(i_1);
  94974. }
  94975. _this._rootMesh.addChild(_this._rotateSpheresParent);
  94976. // Create scale cubes
  94977. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94978. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  94979. for (var i = 0; i < 2; i++) {
  94980. for (var j = 0; j < 2; j++) {
  94981. var _loop_2 = function () {
  94982. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  94983. box.material = coloredMaterial;
  94984. // Dragging logic
  94985. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  94986. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  94987. _dragBehavior.moveAttached = false;
  94988. box.addBehavior(_dragBehavior);
  94989. _dragBehavior.onDragObservable.add(function (event) {
  94990. _this.onScaleBoxDragObservable.notifyObservers({});
  94991. if (_this.attachedMesh) {
  94992. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  94993. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  94994. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  94995. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  94996. _this.updateBoundingBox();
  94997. if (_this.scalePivot) {
  94998. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  94999. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  95000. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  95001. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  95002. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  95003. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  95004. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  95005. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  95006. }
  95007. else {
  95008. // Scale from the position of the opposite corner
  95009. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  95010. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  95011. }
  95012. _this._anchorMesh.addChild(_this.attachedMesh);
  95013. _this._anchorMesh.scaling.addInPlace(deltaScale);
  95014. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  95015. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  95016. }
  95017. _this._anchorMesh.removeChild(_this.attachedMesh);
  95018. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  95019. }
  95020. });
  95021. // Selection/deselection
  95022. _dragBehavior.onDragStartObservable.add(function () {
  95023. _this.onDragStartObservable.notifyObservers({});
  95024. _this._selectNode(box);
  95025. });
  95026. _dragBehavior.onDragEndObservable.add(function () {
  95027. _this.onScaleBoxDragEndObservable.notifyObservers({});
  95028. _this._selectNode(null);
  95029. });
  95030. this_2._scaleBoxesParent.addChild(box);
  95031. };
  95032. var this_2 = this, _dragBehavior;
  95033. for (var k = 0; k < 2; k++) {
  95034. _loop_2();
  95035. }
  95036. }
  95037. }
  95038. _this._rootMesh.addChild(_this._scaleBoxesParent);
  95039. // Hover color change
  95040. var pointerIds = new Array();
  95041. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  95042. if (!pointerIds[pointerInfo.event.pointerId]) {
  95043. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  95044. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  95045. pointerIds[pointerInfo.event.pointerId] = mesh;
  95046. mesh.material = hoverColoredMaterial;
  95047. }
  95048. });
  95049. }
  95050. else {
  95051. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  95052. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  95053. delete pointerIds[pointerInfo.event.pointerId];
  95054. }
  95055. }
  95056. });
  95057. // Update bounding box positions
  95058. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  95059. // Only update the bouding box if scaling has changed
  95060. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  95061. _this.updateBoundingBox();
  95062. }
  95063. });
  95064. _this.updateBoundingBox();
  95065. return _this;
  95066. }
  95067. /** @hidden */
  95068. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  95069. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  95070. // Save old pivot and set pivot to 0,0,0
  95071. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  95072. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  95073. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  95074. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  95075. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  95076. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  95077. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  95078. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  95079. }
  95080. }
  95081. BoundingBoxGizmo._PivotCached++;
  95082. };
  95083. /** @hidden */
  95084. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  95085. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  95086. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  95087. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  95088. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  95089. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  95090. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  95091. }
  95092. this._PivotCached--;
  95093. };
  95094. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  95095. if (value) {
  95096. // Reset anchor mesh to match attached mesh's scale
  95097. // This is needed to avoid invalid box/sphere position on first drag
  95098. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  95099. this._anchorMesh.addChild(value);
  95100. this._anchorMesh.removeChild(value);
  95101. BoundingBoxGizmo._RestorePivotPoint(value);
  95102. this.updateBoundingBox();
  95103. }
  95104. };
  95105. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  95106. this._rotateSpheresParent.getChildMeshes()
  95107. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  95108. m.isVisible = (!selectedMesh || m == selectedMesh);
  95109. });
  95110. };
  95111. /**
  95112. * Updates the bounding box information for the Gizmo
  95113. */
  95114. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  95115. if (this.attachedMesh) {
  95116. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  95117. this._update();
  95118. // Rotate based on axis
  95119. if (!this.attachedMesh.rotationQuaternion) {
  95120. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  95121. }
  95122. if (!this._anchorMesh.rotationQuaternion) {
  95123. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  95124. }
  95125. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  95126. // Store original position and reset mesh to origin before computing the bounding box
  95127. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  95128. this._tmpVector.copyFrom(this.attachedMesh.position);
  95129. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  95130. this.attachedMesh.position.set(0, 0, 0);
  95131. // Update bounding dimensions/positions
  95132. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  95133. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  95134. // Update gizmo to match bounding box scaling and rotation
  95135. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  95136. this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  95137. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  95138. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  95139. this._lineBoundingBox.computeWorldMatrix();
  95140. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  95141. // restore position/rotation values
  95142. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  95143. this.attachedMesh.position.copyFrom(this._tmpVector);
  95144. }
  95145. // Update rotation sphere locations
  95146. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  95147. for (var i = 0; i < 3; i++) {
  95148. for (var j = 0; j < 2; j++) {
  95149. for (var k = 0; k < 2; k++) {
  95150. var index = ((i * 4) + (j * 2)) + k;
  95151. if (i == 0) {
  95152. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  95153. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95154. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  95155. }
  95156. if (i == 1) {
  95157. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  95158. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95159. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  95160. }
  95161. if (i == 2) {
  95162. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  95163. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95164. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  95165. }
  95166. if (this.fixedDragMeshScreenSize) {
  95167. this._rootMesh.computeWorldMatrix();
  95168. this._rotateSpheresParent.computeWorldMatrix();
  95169. rotateSpheres[index].computeWorldMatrix();
  95170. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  95171. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  95172. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  95173. }
  95174. else {
  95175. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  95176. }
  95177. }
  95178. }
  95179. }
  95180. // Update scale box locations
  95181. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  95182. for (var i = 0; i < 2; i++) {
  95183. for (var j = 0; j < 2; j++) {
  95184. for (var k = 0; k < 2; k++) {
  95185. var index = ((i * 4) + (j * 2)) + k;
  95186. if (scaleBoxes[index]) {
  95187. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  95188. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95189. if (this.fixedDragMeshScreenSize) {
  95190. this._rootMesh.computeWorldMatrix();
  95191. this._scaleBoxesParent.computeWorldMatrix();
  95192. scaleBoxes[index].computeWorldMatrix();
  95193. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  95194. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  95195. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  95196. }
  95197. else {
  95198. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  95199. }
  95200. }
  95201. }
  95202. }
  95203. }
  95204. if (this.attachedMesh) {
  95205. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  95206. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  95207. }
  95208. };
  95209. /**
  95210. * Enables rotation on the specified axis and disables rotation on the others
  95211. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  95212. */
  95213. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  95214. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  95215. if (i < 4) {
  95216. m.setEnabled(axis.indexOf("x") != -1);
  95217. }
  95218. else if (i < 8) {
  95219. m.setEnabled(axis.indexOf("y") != -1);
  95220. }
  95221. else {
  95222. m.setEnabled(axis.indexOf("z") != -1);
  95223. }
  95224. });
  95225. };
  95226. /**
  95227. * Disposes of the gizmo
  95228. */
  95229. BoundingBoxGizmo.prototype.dispose = function () {
  95230. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  95231. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  95232. this._lineBoundingBox.dispose();
  95233. this._rotateSpheresParent.dispose();
  95234. this._scaleBoxesParent.dispose();
  95235. _super.prototype.dispose.call(this);
  95236. };
  95237. /**
  95238. * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
  95239. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  95240. * @returns the bounding box mesh with the passed in mesh as a child
  95241. */
  95242. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  95243. var makeNotPickable = function (root) {
  95244. root.isPickable = false;
  95245. root.getChildMeshes().forEach(function (c) {
  95246. makeNotPickable(c);
  95247. });
  95248. };
  95249. makeNotPickable(mesh);
  95250. // Reset position to get boudning box from origin with no rotation
  95251. if (!mesh.rotationQuaternion) {
  95252. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  95253. }
  95254. var oldPos = mesh.position.clone();
  95255. var oldRot = mesh.rotationQuaternion.clone();
  95256. mesh.rotationQuaternion.set(0, 0, 0, 1);
  95257. mesh.position.set(0, 0, 0);
  95258. // Update bounding dimensions/positions
  95259. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  95260. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  95261. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  95262. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  95263. // Restore original positions
  95264. mesh.addChild(box);
  95265. mesh.rotationQuaternion.copyFrom(oldRot);
  95266. mesh.position.copyFrom(oldPos);
  95267. // Reverse parenting
  95268. mesh.removeChild(box);
  95269. box.addChild(mesh);
  95270. box.visibility = 0;
  95271. return box;
  95272. };
  95273. /**
  95274. * CustomMeshes are not supported by this gizmo
  95275. * @param mesh The mesh to replace the default mesh of the gizmo
  95276. */
  95277. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  95278. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  95279. };
  95280. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  95281. // store/remove pivot point should only be applied during their outermost calls
  95282. BoundingBoxGizmo._PivotCached = 0;
  95283. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  95284. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  95285. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  95286. return BoundingBoxGizmo;
  95287. }(BABYLON.Gizmo));
  95288. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  95289. })(BABYLON || (BABYLON = {}));
  95290. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  95291. var BABYLON;
  95292. (function (BABYLON) {
  95293. /**
  95294. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  95295. */
  95296. var GizmoManager = /** @class */ (function () {
  95297. /**
  95298. * Instatiates a gizmo manager
  95299. * @param scene the scene to overlay the gizmos on top of
  95300. */
  95301. function GizmoManager(scene) {
  95302. var _this = this;
  95303. this.scene = scene;
  95304. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  95305. this._pointerObserver = null;
  95306. this._attachedMesh = null;
  95307. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  95308. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  95309. /**
  95310. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  95311. */
  95312. this.attachableMeshes = null;
  95313. /**
  95314. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  95315. */
  95316. this.usePointerToAttachGizmos = true;
  95317. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  95318. // Instatiate/dispose gizmos based on pointer actions
  95319. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  95320. if (!_this.usePointerToAttachGizmos) {
  95321. return;
  95322. }
  95323. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  95324. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  95325. var node = pointerInfo.pickInfo.pickedMesh;
  95326. if (_this.attachableMeshes == null) {
  95327. // Attach to the most parent node
  95328. while (node && node.parent != null) {
  95329. node = node.parent;
  95330. }
  95331. }
  95332. else {
  95333. // Attach to the parent node that is an attachableMesh
  95334. var found = false;
  95335. _this.attachableMeshes.forEach(function (mesh) {
  95336. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  95337. node = mesh;
  95338. found = true;
  95339. }
  95340. });
  95341. if (!found) {
  95342. node = null;
  95343. }
  95344. }
  95345. if (node instanceof BABYLON.AbstractMesh) {
  95346. _this.attachToMesh(node);
  95347. }
  95348. else {
  95349. _this.attachToMesh(null);
  95350. }
  95351. }
  95352. else {
  95353. _this.attachToMesh(null);
  95354. }
  95355. }
  95356. });
  95357. }
  95358. /**
  95359. * Attaches a set of gizmos to the specified mesh
  95360. * @param mesh The mesh the gizmo's should be attached to
  95361. */
  95362. GizmoManager.prototype.attachToMesh = function (mesh) {
  95363. if (this._attachedMesh) {
  95364. this._attachedMesh.removeBehavior(this._dragBehavior);
  95365. }
  95366. this._attachedMesh = mesh;
  95367. for (var key in this.gizmos) {
  95368. var gizmo = (this.gizmos[key]);
  95369. if (gizmo && this._gizmosEnabled[key]) {
  95370. gizmo.attachedMesh = mesh;
  95371. }
  95372. }
  95373. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  95374. this._attachedMesh.addBehavior(this._dragBehavior);
  95375. }
  95376. };
  95377. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  95378. get: function () {
  95379. return this._gizmosEnabled.positionGizmo;
  95380. },
  95381. /**
  95382. * If the position gizmo is enabled
  95383. */
  95384. set: function (value) {
  95385. if (value) {
  95386. if (!this.gizmos.positionGizmo) {
  95387. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  95388. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  95389. }
  95390. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  95391. }
  95392. else if (this.gizmos.positionGizmo) {
  95393. this.gizmos.positionGizmo.attachedMesh = null;
  95394. }
  95395. this._gizmosEnabled.positionGizmo = value;
  95396. },
  95397. enumerable: true,
  95398. configurable: true
  95399. });
  95400. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  95401. get: function () {
  95402. return this._gizmosEnabled.rotationGizmo;
  95403. },
  95404. /**
  95405. * If the rotation gizmo is enabled
  95406. */
  95407. set: function (value) {
  95408. if (value) {
  95409. if (!this.gizmos.rotationGizmo) {
  95410. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  95411. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  95412. }
  95413. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  95414. }
  95415. else if (this.gizmos.rotationGizmo) {
  95416. this.gizmos.rotationGizmo.attachedMesh = null;
  95417. }
  95418. this._gizmosEnabled.rotationGizmo = value;
  95419. },
  95420. enumerable: true,
  95421. configurable: true
  95422. });
  95423. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  95424. get: function () {
  95425. return this._gizmosEnabled.scaleGizmo;
  95426. },
  95427. /**
  95428. * If the scale gizmo is enabled
  95429. */
  95430. set: function (value) {
  95431. if (value) {
  95432. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  95433. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  95434. }
  95435. else if (this.gizmos.scaleGizmo) {
  95436. this.gizmos.scaleGizmo.attachedMesh = null;
  95437. }
  95438. this._gizmosEnabled.scaleGizmo = value;
  95439. },
  95440. enumerable: true,
  95441. configurable: true
  95442. });
  95443. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  95444. get: function () {
  95445. return this._gizmosEnabled.boundingBoxGizmo;
  95446. },
  95447. /**
  95448. * If the boundingBox gizmo is enabled
  95449. */
  95450. set: function (value) {
  95451. if (value) {
  95452. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  95453. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  95454. if (this._attachedMesh) {
  95455. this._attachedMesh.removeBehavior(this._dragBehavior);
  95456. this._attachedMesh.addBehavior(this._dragBehavior);
  95457. }
  95458. }
  95459. else if (this.gizmos.boundingBoxGizmo) {
  95460. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  95461. }
  95462. this._gizmosEnabled.boundingBoxGizmo = value;
  95463. },
  95464. enumerable: true,
  95465. configurable: true
  95466. });
  95467. /**
  95468. * Disposes of the gizmo manager
  95469. */
  95470. GizmoManager.prototype.dispose = function () {
  95471. this.scene.onPointerObservable.remove(this._pointerObserver);
  95472. for (var key in this.gizmos) {
  95473. var gizmo = (this.gizmos[key]);
  95474. if (gizmo) {
  95475. gizmo.dispose();
  95476. }
  95477. }
  95478. this._dragBehavior.detach();
  95479. };
  95480. return GizmoManager;
  95481. }());
  95482. BABYLON.GizmoManager = GizmoManager;
  95483. })(BABYLON || (BABYLON = {}));
  95484. //# sourceMappingURL=babylon.gizmoManager.js.map
  95485. var BABYLON;
  95486. (function (BABYLON) {
  95487. /**
  95488. * Defines a target to use with MorphTargetManager
  95489. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  95490. */
  95491. var MorphTarget = /** @class */ (function () {
  95492. /**
  95493. * Creates a new MorphTarget
  95494. * @param name defines the name of the target
  95495. * @param influence defines the influence to use
  95496. */
  95497. function MorphTarget(
  95498. /** defines the name of the target */
  95499. name, influence, scene) {
  95500. if (influence === void 0) { influence = 0; }
  95501. if (scene === void 0) { scene = null; }
  95502. this.name = name;
  95503. /**
  95504. * Gets or sets the list of animations
  95505. */
  95506. this.animations = new Array();
  95507. this._positions = null;
  95508. this._normals = null;
  95509. this._tangents = null;
  95510. /**
  95511. * Observable raised when the influence changes
  95512. */
  95513. this.onInfluenceChanged = new BABYLON.Observable();
  95514. this._animationPropertiesOverride = null;
  95515. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95516. this.influence = influence;
  95517. }
  95518. Object.defineProperty(MorphTarget.prototype, "influence", {
  95519. /**
  95520. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  95521. */
  95522. get: function () {
  95523. return this._influence;
  95524. },
  95525. set: function (influence) {
  95526. if (this._influence === influence) {
  95527. return;
  95528. }
  95529. var previous = this._influence;
  95530. this._influence = influence;
  95531. if (this.onInfluenceChanged.hasObservers) {
  95532. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  95533. }
  95534. },
  95535. enumerable: true,
  95536. configurable: true
  95537. });
  95538. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  95539. /**
  95540. * Gets or sets the animation properties override
  95541. */
  95542. get: function () {
  95543. if (!this._animationPropertiesOverride && this._scene) {
  95544. return this._scene.animationPropertiesOverride;
  95545. }
  95546. return this._animationPropertiesOverride;
  95547. },
  95548. set: function (value) {
  95549. this._animationPropertiesOverride = value;
  95550. },
  95551. enumerable: true,
  95552. configurable: true
  95553. });
  95554. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  95555. /**
  95556. * Gets a boolean defining if the target contains position data
  95557. */
  95558. get: function () {
  95559. return !!this._positions;
  95560. },
  95561. enumerable: true,
  95562. configurable: true
  95563. });
  95564. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  95565. /**
  95566. * Gets a boolean defining if the target contains normal data
  95567. */
  95568. get: function () {
  95569. return !!this._normals;
  95570. },
  95571. enumerable: true,
  95572. configurable: true
  95573. });
  95574. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  95575. /**
  95576. * Gets a boolean defining if the target contains tangent data
  95577. */
  95578. get: function () {
  95579. return !!this._tangents;
  95580. },
  95581. enumerable: true,
  95582. configurable: true
  95583. });
  95584. /**
  95585. * Affects position data to this target
  95586. * @param data defines the position data to use
  95587. */
  95588. MorphTarget.prototype.setPositions = function (data) {
  95589. this._positions = data;
  95590. };
  95591. /**
  95592. * Gets the position data stored in this target
  95593. * @returns a FloatArray containing the position data (or null if not present)
  95594. */
  95595. MorphTarget.prototype.getPositions = function () {
  95596. return this._positions;
  95597. };
  95598. /**
  95599. * Affects normal data to this target
  95600. * @param data defines the normal data to use
  95601. */
  95602. MorphTarget.prototype.setNormals = function (data) {
  95603. this._normals = data;
  95604. };
  95605. /**
  95606. * Gets the normal data stored in this target
  95607. * @returns a FloatArray containing the normal data (or null if not present)
  95608. */
  95609. MorphTarget.prototype.getNormals = function () {
  95610. return this._normals;
  95611. };
  95612. /**
  95613. * Affects tangent data to this target
  95614. * @param data defines the tangent data to use
  95615. */
  95616. MorphTarget.prototype.setTangents = function (data) {
  95617. this._tangents = data;
  95618. };
  95619. /**
  95620. * Gets the tangent data stored in this target
  95621. * @returns a FloatArray containing the tangent data (or null if not present)
  95622. */
  95623. MorphTarget.prototype.getTangents = function () {
  95624. return this._tangents;
  95625. };
  95626. /**
  95627. * Serializes the current target into a Serialization object
  95628. * @returns the serialized object
  95629. */
  95630. MorphTarget.prototype.serialize = function () {
  95631. var serializationObject = {};
  95632. serializationObject.name = this.name;
  95633. serializationObject.influence = this.influence;
  95634. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  95635. if (this.hasNormals) {
  95636. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  95637. }
  95638. if (this.hasTangents) {
  95639. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  95640. }
  95641. // Animations
  95642. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  95643. return serializationObject;
  95644. };
  95645. // Statics
  95646. /**
  95647. * Creates a new target from serialized data
  95648. * @param serializationObject defines the serialized data to use
  95649. * @returns a new MorphTarget
  95650. */
  95651. MorphTarget.Parse = function (serializationObject) {
  95652. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  95653. result.setPositions(serializationObject.positions);
  95654. if (serializationObject.normals) {
  95655. result.setNormals(serializationObject.normals);
  95656. }
  95657. if (serializationObject.tangents) {
  95658. result.setTangents(serializationObject.tangents);
  95659. }
  95660. // Animations
  95661. if (serializationObject.animations) {
  95662. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  95663. var parsedAnimation = serializationObject.animations[animationIndex];
  95664. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  95665. }
  95666. }
  95667. return result;
  95668. };
  95669. /**
  95670. * Creates a MorphTarget from mesh data
  95671. * @param mesh defines the source mesh
  95672. * @param name defines the name to use for the new target
  95673. * @param influence defines the influence to attach to the target
  95674. * @returns a new MorphTarget
  95675. */
  95676. MorphTarget.FromMesh = function (mesh, name, influence) {
  95677. if (!name) {
  95678. name = mesh.name;
  95679. }
  95680. var result = new MorphTarget(name, influence, mesh.getScene());
  95681. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  95682. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  95683. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  95684. }
  95685. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  95686. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  95687. }
  95688. return result;
  95689. };
  95690. return MorphTarget;
  95691. }());
  95692. BABYLON.MorphTarget = MorphTarget;
  95693. })(BABYLON || (BABYLON = {}));
  95694. //# sourceMappingURL=babylon.morphTarget.js.map
  95695. var BABYLON;
  95696. (function (BABYLON) {
  95697. /**
  95698. * This class is used to deform meshes using morphing between different targets
  95699. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  95700. */
  95701. var MorphTargetManager = /** @class */ (function () {
  95702. /**
  95703. * Creates a new MorphTargetManager
  95704. * @param scene defines the current scene
  95705. */
  95706. function MorphTargetManager(scene) {
  95707. if (scene === void 0) { scene = null; }
  95708. this._targets = new Array();
  95709. this._targetObservable = new Array();
  95710. this._activeTargets = new BABYLON.SmartArray(16);
  95711. this._supportsNormals = false;
  95712. this._supportsTangents = false;
  95713. this._vertexCount = 0;
  95714. this._uniqueId = 0;
  95715. this._tempInfluences = new Array();
  95716. if (!scene) {
  95717. scene = BABYLON.Engine.LastCreatedScene;
  95718. }
  95719. this._scene = scene;
  95720. if (this._scene) {
  95721. this._scene.morphTargetManagers.push(this);
  95722. this._uniqueId = this._scene.getUniqueId();
  95723. }
  95724. }
  95725. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  95726. /**
  95727. * Gets the unique ID of this manager
  95728. */
  95729. get: function () {
  95730. return this._uniqueId;
  95731. },
  95732. enumerable: true,
  95733. configurable: true
  95734. });
  95735. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  95736. /**
  95737. * Gets the number of vertices handled by this manager
  95738. */
  95739. get: function () {
  95740. return this._vertexCount;
  95741. },
  95742. enumerable: true,
  95743. configurable: true
  95744. });
  95745. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  95746. /**
  95747. * Gets a boolean indicating if this manager supports morphing of normals
  95748. */
  95749. get: function () {
  95750. return this._supportsNormals;
  95751. },
  95752. enumerable: true,
  95753. configurable: true
  95754. });
  95755. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  95756. /**
  95757. * Gets a boolean indicating if this manager supports morphing of tangents
  95758. */
  95759. get: function () {
  95760. return this._supportsTangents;
  95761. },
  95762. enumerable: true,
  95763. configurable: true
  95764. });
  95765. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  95766. /**
  95767. * Gets the number of targets stored in this manager
  95768. */
  95769. get: function () {
  95770. return this._targets.length;
  95771. },
  95772. enumerable: true,
  95773. configurable: true
  95774. });
  95775. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  95776. /**
  95777. * Gets the number of influencers (ie. the number of targets with influences > 0)
  95778. */
  95779. get: function () {
  95780. return this._activeTargets.length;
  95781. },
  95782. enumerable: true,
  95783. configurable: true
  95784. });
  95785. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  95786. /**
  95787. * Gets the list of influences (one per target)
  95788. */
  95789. get: function () {
  95790. return this._influences;
  95791. },
  95792. enumerable: true,
  95793. configurable: true
  95794. });
  95795. /**
  95796. * Gets the active target at specified index. An active target is a target with an influence > 0
  95797. * @param index defines the index to check
  95798. * @returns the requested target
  95799. */
  95800. MorphTargetManager.prototype.getActiveTarget = function (index) {
  95801. return this._activeTargets.data[index];
  95802. };
  95803. /**
  95804. * Gets the target at specified index
  95805. * @param index defines the index to check
  95806. * @returns the requested target
  95807. */
  95808. MorphTargetManager.prototype.getTarget = function (index) {
  95809. return this._targets[index];
  95810. };
  95811. /**
  95812. * Add a new target to this manager
  95813. * @param target defines the target to add
  95814. */
  95815. MorphTargetManager.prototype.addTarget = function (target) {
  95816. var _this = this;
  95817. this._targets.push(target);
  95818. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  95819. _this._syncActiveTargets(needUpdate);
  95820. }));
  95821. this._syncActiveTargets(true);
  95822. };
  95823. /**
  95824. * Removes a target from the manager
  95825. * @param target defines the target to remove
  95826. */
  95827. MorphTargetManager.prototype.removeTarget = function (target) {
  95828. var index = this._targets.indexOf(target);
  95829. if (index >= 0) {
  95830. this._targets.splice(index, 1);
  95831. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  95832. this._syncActiveTargets(true);
  95833. }
  95834. };
  95835. /**
  95836. * Serializes the current manager into a Serialization object
  95837. * @returns the serialized object
  95838. */
  95839. MorphTargetManager.prototype.serialize = function () {
  95840. var serializationObject = {};
  95841. serializationObject.id = this.uniqueId;
  95842. serializationObject.targets = [];
  95843. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  95844. var target = _a[_i];
  95845. serializationObject.targets.push(target.serialize());
  95846. }
  95847. return serializationObject;
  95848. };
  95849. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  95850. var influenceCount = 0;
  95851. this._activeTargets.reset();
  95852. this._supportsNormals = true;
  95853. this._supportsTangents = true;
  95854. this._vertexCount = 0;
  95855. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  95856. var target = _a[_i];
  95857. this._activeTargets.push(target);
  95858. this._tempInfluences[influenceCount++] = target.influence;
  95859. var positions = target.getPositions();
  95860. if (positions) {
  95861. this._supportsNormals = this._supportsNormals && target.hasNormals;
  95862. this._supportsTangents = this._supportsTangents && target.hasTangents;
  95863. var vertexCount = positions.length / 3;
  95864. if (this._vertexCount === 0) {
  95865. this._vertexCount = vertexCount;
  95866. }
  95867. else if (this._vertexCount !== vertexCount) {
  95868. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  95869. return;
  95870. }
  95871. }
  95872. }
  95873. if (!this._influences || this._influences.length !== influenceCount) {
  95874. this._influences = new Float32Array(influenceCount);
  95875. }
  95876. for (var index = 0; index < influenceCount; index++) {
  95877. this._influences[index] = this._tempInfluences[index];
  95878. }
  95879. if (needUpdate) {
  95880. this.synchronize();
  95881. }
  95882. };
  95883. /**
  95884. * Syncrhonize the targets with all the meshes using this morph target manager
  95885. */
  95886. MorphTargetManager.prototype.synchronize = function () {
  95887. if (!this._scene) {
  95888. return;
  95889. }
  95890. // Flag meshes as dirty to resync with the active targets
  95891. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  95892. var mesh = _a[_i];
  95893. if (mesh.morphTargetManager === this) {
  95894. mesh._syncGeometryWithMorphTargetManager();
  95895. }
  95896. }
  95897. };
  95898. // Statics
  95899. /**
  95900. * Creates a new MorphTargetManager from serialized data
  95901. * @param serializationObject defines the serialized data
  95902. * @param scene defines the hosting scene
  95903. * @returns the new MorphTargetManager
  95904. */
  95905. MorphTargetManager.Parse = function (serializationObject, scene) {
  95906. var result = new MorphTargetManager(scene);
  95907. result._uniqueId = serializationObject.id;
  95908. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  95909. var targetData = _a[_i];
  95910. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  95911. }
  95912. return result;
  95913. };
  95914. return MorphTargetManager;
  95915. }());
  95916. BABYLON.MorphTargetManager = MorphTargetManager;
  95917. })(BABYLON || (BABYLON = {}));
  95918. //# sourceMappingURL=babylon.morphTargetManager.js.map
  95919. var BABYLON;
  95920. (function (BABYLON) {
  95921. var Octree = /** @class */ (function () {
  95922. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  95923. if (maxDepth === void 0) { maxDepth = 2; }
  95924. this.maxDepth = maxDepth;
  95925. this.dynamicContent = new Array();
  95926. this._maxBlockCapacity = maxBlockCapacity || 64;
  95927. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  95928. this._creationFunc = creationFunc;
  95929. }
  95930. // Methods
  95931. Octree.prototype.update = function (worldMin, worldMax, entries) {
  95932. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  95933. };
  95934. Octree.prototype.addMesh = function (entry) {
  95935. for (var index = 0; index < this.blocks.length; index++) {
  95936. var block = this.blocks[index];
  95937. block.addEntry(entry);
  95938. }
  95939. };
  95940. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  95941. this._selectionContent.reset();
  95942. for (var index = 0; index < this.blocks.length; index++) {
  95943. var block = this.blocks[index];
  95944. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  95945. }
  95946. if (allowDuplicate) {
  95947. this._selectionContent.concat(this.dynamicContent);
  95948. }
  95949. else {
  95950. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95951. }
  95952. return this._selectionContent;
  95953. };
  95954. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  95955. this._selectionContent.reset();
  95956. for (var index = 0; index < this.blocks.length; index++) {
  95957. var block = this.blocks[index];
  95958. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  95959. }
  95960. if (allowDuplicate) {
  95961. this._selectionContent.concat(this.dynamicContent);
  95962. }
  95963. else {
  95964. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95965. }
  95966. return this._selectionContent;
  95967. };
  95968. Octree.prototype.intersectsRay = function (ray) {
  95969. this._selectionContent.reset();
  95970. for (var index = 0; index < this.blocks.length; index++) {
  95971. var block = this.blocks[index];
  95972. block.intersectsRay(ray, this._selectionContent);
  95973. }
  95974. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95975. return this._selectionContent;
  95976. };
  95977. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  95978. target.blocks = new Array();
  95979. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  95980. // Segmenting space
  95981. for (var x = 0; x < 2; x++) {
  95982. for (var y = 0; y < 2; y++) {
  95983. for (var z = 0; z < 2; z++) {
  95984. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  95985. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  95986. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  95987. block.addEntries(entries);
  95988. target.blocks.push(block);
  95989. }
  95990. }
  95991. }
  95992. };
  95993. Octree.CreationFuncForMeshes = function (entry, block) {
  95994. var boundingInfo = entry.getBoundingInfo();
  95995. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  95996. block.entries.push(entry);
  95997. }
  95998. };
  95999. Octree.CreationFuncForSubMeshes = function (entry, block) {
  96000. var boundingInfo = entry.getBoundingInfo();
  96001. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  96002. block.entries.push(entry);
  96003. }
  96004. };
  96005. return Octree;
  96006. }());
  96007. BABYLON.Octree = Octree;
  96008. })(BABYLON || (BABYLON = {}));
  96009. //# sourceMappingURL=babylon.octree.js.map
  96010. var BABYLON;
  96011. (function (BABYLON) {
  96012. var OctreeBlock = /** @class */ (function () {
  96013. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  96014. this.entries = new Array();
  96015. this._boundingVectors = new Array();
  96016. this._capacity = capacity;
  96017. this._depth = depth;
  96018. this._maxDepth = maxDepth;
  96019. this._creationFunc = creationFunc;
  96020. this._minPoint = minPoint;
  96021. this._maxPoint = maxPoint;
  96022. this._boundingVectors.push(minPoint.clone());
  96023. this._boundingVectors.push(maxPoint.clone());
  96024. this._boundingVectors.push(minPoint.clone());
  96025. this._boundingVectors[2].x = maxPoint.x;
  96026. this._boundingVectors.push(minPoint.clone());
  96027. this._boundingVectors[3].y = maxPoint.y;
  96028. this._boundingVectors.push(minPoint.clone());
  96029. this._boundingVectors[4].z = maxPoint.z;
  96030. this._boundingVectors.push(maxPoint.clone());
  96031. this._boundingVectors[5].z = minPoint.z;
  96032. this._boundingVectors.push(maxPoint.clone());
  96033. this._boundingVectors[6].x = minPoint.x;
  96034. this._boundingVectors.push(maxPoint.clone());
  96035. this._boundingVectors[7].y = minPoint.y;
  96036. }
  96037. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  96038. // Property
  96039. get: function () {
  96040. return this._capacity;
  96041. },
  96042. enumerable: true,
  96043. configurable: true
  96044. });
  96045. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  96046. get: function () {
  96047. return this._minPoint;
  96048. },
  96049. enumerable: true,
  96050. configurable: true
  96051. });
  96052. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  96053. get: function () {
  96054. return this._maxPoint;
  96055. },
  96056. enumerable: true,
  96057. configurable: true
  96058. });
  96059. // Methods
  96060. OctreeBlock.prototype.addEntry = function (entry) {
  96061. if (this.blocks) {
  96062. for (var index = 0; index < this.blocks.length; index++) {
  96063. var block = this.blocks[index];
  96064. block.addEntry(entry);
  96065. }
  96066. return;
  96067. }
  96068. this._creationFunc(entry, this);
  96069. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  96070. this.createInnerBlocks();
  96071. }
  96072. };
  96073. OctreeBlock.prototype.addEntries = function (entries) {
  96074. for (var index = 0; index < entries.length; index++) {
  96075. var mesh = entries[index];
  96076. this.addEntry(mesh);
  96077. }
  96078. };
  96079. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  96080. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  96081. if (this.blocks) {
  96082. for (var index = 0; index < this.blocks.length; index++) {
  96083. var block = this.blocks[index];
  96084. block.select(frustumPlanes, selection, allowDuplicate);
  96085. }
  96086. return;
  96087. }
  96088. if (allowDuplicate) {
  96089. selection.concat(this.entries);
  96090. }
  96091. else {
  96092. selection.concatWithNoDuplicate(this.entries);
  96093. }
  96094. }
  96095. };
  96096. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  96097. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  96098. if (this.blocks) {
  96099. for (var index = 0; index < this.blocks.length; index++) {
  96100. var block = this.blocks[index];
  96101. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  96102. }
  96103. return;
  96104. }
  96105. if (allowDuplicate) {
  96106. selection.concat(this.entries);
  96107. }
  96108. else {
  96109. selection.concatWithNoDuplicate(this.entries);
  96110. }
  96111. }
  96112. };
  96113. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  96114. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  96115. if (this.blocks) {
  96116. for (var index = 0; index < this.blocks.length; index++) {
  96117. var block = this.blocks[index];
  96118. block.intersectsRay(ray, selection);
  96119. }
  96120. return;
  96121. }
  96122. selection.concatWithNoDuplicate(this.entries);
  96123. }
  96124. };
  96125. OctreeBlock.prototype.createInnerBlocks = function () {
  96126. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  96127. };
  96128. return OctreeBlock;
  96129. }());
  96130. BABYLON.OctreeBlock = OctreeBlock;
  96131. })(BABYLON || (BABYLON = {}));
  96132. //# sourceMappingURL=babylon.octreeBlock.js.map
  96133. var BABYLON;
  96134. (function (BABYLON) {
  96135. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  96136. if (maxCapacity === void 0) { maxCapacity = 64; }
  96137. if (maxDepth === void 0) { maxDepth = 2; }
  96138. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  96139. if (!component) {
  96140. component = new OctreeSceneComponent(this);
  96141. this._addComponent(component);
  96142. }
  96143. if (!this._selectionOctree) {
  96144. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  96145. }
  96146. var worldExtends = this.getWorldExtends();
  96147. // Update octree
  96148. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  96149. return this._selectionOctree;
  96150. };
  96151. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  96152. get: function () {
  96153. return this._selectionOctree;
  96154. },
  96155. enumerable: true,
  96156. configurable: true
  96157. });
  96158. /**
  96159. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  96160. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  96161. * @param maxCapacity defines the maximum size of each block (64 by default)
  96162. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  96163. * @returns the new octree
  96164. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  96165. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  96166. */
  96167. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  96168. if (maxCapacity === void 0) { maxCapacity = 64; }
  96169. if (maxDepth === void 0) { maxDepth = 2; }
  96170. var scene = this.getScene();
  96171. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  96172. if (!component) {
  96173. component = new OctreeSceneComponent(scene);
  96174. scene._addComponent(component);
  96175. }
  96176. if (!this._submeshesOctree) {
  96177. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  96178. }
  96179. this.computeWorldMatrix(true);
  96180. var boundingInfo = this.getBoundingInfo();
  96181. // Update octree
  96182. var bbox = boundingInfo.boundingBox;
  96183. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  96184. return this._submeshesOctree;
  96185. };
  96186. /**
  96187. * Defines the octree scene component responsible to manage any octrees
  96188. * in a given scene.
  96189. */
  96190. var OctreeSceneComponent = /** @class */ (function () {
  96191. /**
  96192. * Creates a new instance of the component for the given scene
  96193. * @param scene Defines the scene to register the component in
  96194. */
  96195. function OctreeSceneComponent(scene) {
  96196. /**
  96197. * The component name helpfull to identify the component in the list of scene components.
  96198. */
  96199. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  96200. /**
  96201. * Indicates if the meshes have been checked to make sure they are isEnabled()
  96202. */
  96203. this.checksIsEnabled = true;
  96204. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  96205. this.scene = scene;
  96206. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  96207. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  96208. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  96209. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  96210. }
  96211. /**
  96212. * Registers the component in a given scene
  96213. */
  96214. OctreeSceneComponent.prototype.register = function () {
  96215. var _this = this;
  96216. this.scene.onMeshRemovedObservable.add(function (mesh) {
  96217. var sceneOctree = _this.scene.selectionOctree;
  96218. if (sceneOctree !== undefined && sceneOctree !== null) {
  96219. var index = sceneOctree.dynamicContent.indexOf(mesh);
  96220. if (index !== -1) {
  96221. sceneOctree.dynamicContent.splice(index, 1);
  96222. }
  96223. }
  96224. });
  96225. this.scene.onMeshImportedObservable.add(function (mesh) {
  96226. var sceneOctree = _this.scene.selectionOctree;
  96227. if (sceneOctree !== undefined && sceneOctree !== null) {
  96228. sceneOctree.addMesh(mesh);
  96229. }
  96230. });
  96231. };
  96232. /**
  96233. * Return the list of active meshes
  96234. * @returns the list of active meshes
  96235. */
  96236. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  96237. if (this.scene._selectionOctree) {
  96238. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  96239. return selection;
  96240. }
  96241. return this.scene._getDefaultMeshCandidates();
  96242. };
  96243. /**
  96244. * Return the list of active sub meshes
  96245. * @param mesh The mesh to get the candidates sub meshes from
  96246. * @returns the list of active sub meshes
  96247. */
  96248. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  96249. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  96250. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  96251. return intersections;
  96252. }
  96253. return this.scene._getDefaultSubMeshCandidates(mesh);
  96254. };
  96255. /**
  96256. * Return the list of sub meshes intersecting with a given local ray
  96257. * @param mesh defines the mesh to find the submesh for
  96258. * @param localRay defines the ray in local space
  96259. * @returns the list of intersecting sub meshes
  96260. */
  96261. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  96262. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  96263. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  96264. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  96265. return intersections;
  96266. }
  96267. return this.scene._getDefaultSubMeshCandidates(mesh);
  96268. };
  96269. /**
  96270. * Return the list of sub meshes colliding with a collider
  96271. * @param mesh defines the mesh to find the submesh for
  96272. * @param collider defines the collider to evaluate the collision against
  96273. * @returns the list of colliding sub meshes
  96274. */
  96275. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  96276. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  96277. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  96278. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  96279. return intersections;
  96280. }
  96281. return this.scene._getDefaultSubMeshCandidates(mesh);
  96282. };
  96283. /**
  96284. * Rebuilds the elements related to this component in case of
  96285. * context lost for instance.
  96286. */
  96287. OctreeSceneComponent.prototype.rebuild = function () {
  96288. // Nothing to do here.
  96289. };
  96290. /**
  96291. * Disposes the component and the associated ressources.
  96292. */
  96293. OctreeSceneComponent.prototype.dispose = function () {
  96294. // Nothing to do here.
  96295. };
  96296. return OctreeSceneComponent;
  96297. }());
  96298. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  96299. })(BABYLON || (BABYLON = {}));
  96300. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  96301. var BABYLON;
  96302. (function (BABYLON) {
  96303. /**
  96304. * Postprocess used to generate anaglyphic rendering
  96305. */
  96306. var AnaglyphPostProcess = /** @class */ (function (_super) {
  96307. __extends(AnaglyphPostProcess, _super);
  96308. /**
  96309. * Creates a new AnaglyphPostProcess
  96310. * @param name defines postprocess name
  96311. * @param options defines creation options or target ratio scale
  96312. * @param rigCameras defines cameras using this postprocess
  96313. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  96314. * @param engine defines hosting engine
  96315. * @param reusable defines if the postprocess will be reused multiple times per frame
  96316. */
  96317. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  96318. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  96319. _this._passedProcess = rigCameras[0]._rigPostProcess;
  96320. _this.onApplyObservable.add(function (effect) {
  96321. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  96322. });
  96323. return _this;
  96324. }
  96325. return AnaglyphPostProcess;
  96326. }(BABYLON.PostProcess));
  96327. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  96328. })(BABYLON || (BABYLON = {}));
  96329. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  96330. var BABYLON;
  96331. (function (BABYLON) {
  96332. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  96333. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96334. });
  96335. /**
  96336. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  96337. */
  96338. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  96339. __extends(AnaglyphArcRotateCamera, _super);
  96340. /**
  96341. * Creates a new AnaglyphArcRotateCamera
  96342. * @param name defines camera name
  96343. * @param alpha defines alpha angle (in radians)
  96344. * @param beta defines beta angle (in radians)
  96345. * @param radius defines radius
  96346. * @param target defines camera target
  96347. * @param interaxialDistance defines distance between each color axis
  96348. * @param scene defines the hosting scene
  96349. */
  96350. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  96351. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  96352. _this.interaxialDistance = interaxialDistance;
  96353. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96354. return _this;
  96355. }
  96356. /**
  96357. * Gets camera class name
  96358. * @returns AnaglyphArcRotateCamera
  96359. */
  96360. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  96361. return "AnaglyphArcRotateCamera";
  96362. };
  96363. return AnaglyphArcRotateCamera;
  96364. }(BABYLON.ArcRotateCamera));
  96365. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  96366. })(BABYLON || (BABYLON = {}));
  96367. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  96368. var BABYLON;
  96369. (function (BABYLON) {
  96370. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  96371. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96372. });
  96373. /**
  96374. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  96375. */
  96376. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  96377. __extends(AnaglyphFreeCamera, _super);
  96378. /**
  96379. * Creates a new AnaglyphFreeCamera
  96380. * @param name defines camera name
  96381. * @param position defines initial position
  96382. * @param interaxialDistance defines distance between each color axis
  96383. * @param scene defines the hosting scene
  96384. */
  96385. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  96386. var _this = _super.call(this, name, position, scene) || this;
  96387. _this.interaxialDistance = interaxialDistance;
  96388. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96389. return _this;
  96390. }
  96391. /**
  96392. * Gets camera class name
  96393. * @returns AnaglyphFreeCamera
  96394. */
  96395. AnaglyphFreeCamera.prototype.getClassName = function () {
  96396. return "AnaglyphFreeCamera";
  96397. };
  96398. return AnaglyphFreeCamera;
  96399. }(BABYLON.FreeCamera));
  96400. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  96401. })(BABYLON || (BABYLON = {}));
  96402. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  96403. var BABYLON;
  96404. (function (BABYLON) {
  96405. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  96406. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96407. });
  96408. /**
  96409. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  96410. */
  96411. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  96412. __extends(AnaglyphGamepadCamera, _super);
  96413. /**
  96414. * Creates a new AnaglyphGamepadCamera
  96415. * @param name defines camera name
  96416. * @param position defines initial position
  96417. * @param interaxialDistance defines distance between each color axis
  96418. * @param scene defines the hosting scene
  96419. */
  96420. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  96421. var _this = _super.call(this, name, position, scene) || this;
  96422. _this.interaxialDistance = interaxialDistance;
  96423. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96424. return _this;
  96425. }
  96426. /**
  96427. * Gets camera class name
  96428. * @returns AnaglyphGamepadCamera
  96429. */
  96430. AnaglyphGamepadCamera.prototype.getClassName = function () {
  96431. return "AnaglyphGamepadCamera";
  96432. };
  96433. return AnaglyphGamepadCamera;
  96434. }(BABYLON.GamepadCamera));
  96435. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  96436. })(BABYLON || (BABYLON = {}));
  96437. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  96438. var BABYLON;
  96439. (function (BABYLON) {
  96440. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  96441. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96442. });
  96443. /**
  96444. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  96445. */
  96446. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  96447. __extends(AnaglyphUniversalCamera, _super);
  96448. /**
  96449. * Creates a new AnaglyphUniversalCamera
  96450. * @param name defines camera name
  96451. * @param position defines initial position
  96452. * @param interaxialDistance defines distance between each color axis
  96453. * @param scene defines the hosting scene
  96454. */
  96455. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  96456. var _this = _super.call(this, name, position, scene) || this;
  96457. _this.interaxialDistance = interaxialDistance;
  96458. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96459. return _this;
  96460. }
  96461. /**
  96462. * Gets camera class name
  96463. * @returns AnaglyphUniversalCamera
  96464. */
  96465. AnaglyphUniversalCamera.prototype.getClassName = function () {
  96466. return "AnaglyphUniversalCamera";
  96467. };
  96468. return AnaglyphUniversalCamera;
  96469. }(BABYLON.UniversalCamera));
  96470. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  96471. })(BABYLON || (BABYLON = {}));
  96472. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  96473. var BABYLON;
  96474. (function (BABYLON) {
  96475. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  96476. __extends(StereoscopicInterlacePostProcess, _super);
  96477. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  96478. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  96479. _this._passedProcess = rigCameras[0]._rigPostProcess;
  96480. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  96481. _this.onSizeChangedObservable.add(function () {
  96482. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  96483. });
  96484. _this.onApplyObservable.add(function (effect) {
  96485. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  96486. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  96487. });
  96488. return _this;
  96489. }
  96490. return StereoscopicInterlacePostProcess;
  96491. }(BABYLON.PostProcess));
  96492. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  96493. })(BABYLON || (BABYLON = {}));
  96494. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  96495. var BABYLON;
  96496. (function (BABYLON) {
  96497. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  96498. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96499. });
  96500. /**
  96501. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  96502. */
  96503. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  96504. __extends(StereoscopicArcRotateCamera, _super);
  96505. /**
  96506. * Creates a new StereoscopicArcRotateCamera
  96507. * @param name defines camera name
  96508. * @param alpha defines alpha angle (in radians)
  96509. * @param beta defines beta angle (in radians)
  96510. * @param radius defines radius
  96511. * @param target defines camera target
  96512. * @param interaxialDistance defines distance between each color axis
  96513. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96514. * @param scene defines the hosting scene
  96515. */
  96516. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  96517. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  96518. _this.interaxialDistance = interaxialDistance;
  96519. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96520. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96521. return _this;
  96522. }
  96523. /**
  96524. * Gets camera class name
  96525. * @returns StereoscopicArcRotateCamera
  96526. */
  96527. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  96528. return "StereoscopicArcRotateCamera";
  96529. };
  96530. return StereoscopicArcRotateCamera;
  96531. }(BABYLON.ArcRotateCamera));
  96532. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  96533. })(BABYLON || (BABYLON = {}));
  96534. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  96535. var BABYLON;
  96536. (function (BABYLON) {
  96537. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  96538. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96539. });
  96540. /**
  96541. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  96542. */
  96543. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  96544. __extends(StereoscopicFreeCamera, _super);
  96545. /**
  96546. * Creates a new StereoscopicFreeCamera
  96547. * @param name defines camera name
  96548. * @param position defines initial position
  96549. * @param interaxialDistance defines distance between each color axis
  96550. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96551. * @param scene defines the hosting scene
  96552. */
  96553. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96554. var _this = _super.call(this, name, position, scene) || this;
  96555. _this.interaxialDistance = interaxialDistance;
  96556. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96557. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96558. return _this;
  96559. }
  96560. /**
  96561. * Gets camera class name
  96562. * @returns StereoscopicFreeCamera
  96563. */
  96564. StereoscopicFreeCamera.prototype.getClassName = function () {
  96565. return "StereoscopicFreeCamera";
  96566. };
  96567. return StereoscopicFreeCamera;
  96568. }(BABYLON.FreeCamera));
  96569. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  96570. })(BABYLON || (BABYLON = {}));
  96571. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  96572. var BABYLON;
  96573. (function (BABYLON) {
  96574. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  96575. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96576. });
  96577. /**
  96578. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  96579. */
  96580. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  96581. __extends(StereoscopicGamepadCamera, _super);
  96582. /**
  96583. * Creates a new StereoscopicGamepadCamera
  96584. * @param name defines camera name
  96585. * @param position defines initial position
  96586. * @param interaxialDistance defines distance between each color axis
  96587. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96588. * @param scene defines the hosting scene
  96589. */
  96590. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96591. var _this = _super.call(this, name, position, scene) || this;
  96592. _this.interaxialDistance = interaxialDistance;
  96593. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96594. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96595. return _this;
  96596. }
  96597. /**
  96598. * Gets camera class name
  96599. * @returns StereoscopicGamepadCamera
  96600. */
  96601. StereoscopicGamepadCamera.prototype.getClassName = function () {
  96602. return "StereoscopicGamepadCamera";
  96603. };
  96604. return StereoscopicGamepadCamera;
  96605. }(BABYLON.GamepadCamera));
  96606. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  96607. })(BABYLON || (BABYLON = {}));
  96608. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  96609. var BABYLON;
  96610. (function (BABYLON) {
  96611. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  96612. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96613. });
  96614. /**
  96615. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  96616. */
  96617. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  96618. __extends(StereoscopicUniversalCamera, _super);
  96619. /**
  96620. * Creates a new StereoscopicUniversalCamera
  96621. * @param name defines camera name
  96622. * @param position defines initial position
  96623. * @param interaxialDistance defines distance between each color axis
  96624. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96625. * @param scene defines the hosting scene
  96626. */
  96627. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96628. var _this = _super.call(this, name, position, scene) || this;
  96629. _this.interaxialDistance = interaxialDistance;
  96630. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96631. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96632. return _this;
  96633. }
  96634. /**
  96635. * Gets camera class name
  96636. * @returns StereoscopicUniversalCamera
  96637. */
  96638. StereoscopicUniversalCamera.prototype.getClassName = function () {
  96639. return "StereoscopicUniversalCamera";
  96640. };
  96641. return StereoscopicUniversalCamera;
  96642. }(BABYLON.UniversalCamera));
  96643. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  96644. })(BABYLON || (BABYLON = {}));
  96645. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  96646. var BABYLON;
  96647. (function (BABYLON) {
  96648. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  96649. __extends(VRDistortionCorrectionPostProcess, _super);
  96650. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  96651. var _this = _super.call(this, name, "vrDistortionCorrection", [
  96652. 'LensCenter',
  96653. 'Scale',
  96654. 'ScaleIn',
  96655. 'HmdWarpParam'
  96656. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  96657. _this._isRightEye = isRightEye;
  96658. _this._distortionFactors = vrMetrics.distortionK;
  96659. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  96660. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  96661. _this.adaptScaleToCurrentViewport = true;
  96662. _this.onSizeChangedObservable.add(function () {
  96663. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  96664. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  96665. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  96666. });
  96667. _this.onApplyObservable.add(function (effect) {
  96668. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  96669. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  96670. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  96671. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  96672. });
  96673. return _this;
  96674. }
  96675. return VRDistortionCorrectionPostProcess;
  96676. }(BABYLON.PostProcess));
  96677. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  96678. })(BABYLON || (BABYLON = {}));
  96679. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  96680. var BABYLON;
  96681. (function (BABYLON) {
  96682. /**
  96683. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  96684. * Screen rotation is taken into account.
  96685. */
  96686. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  96687. function FreeCameraDeviceOrientationInput() {
  96688. var _this = this;
  96689. this._screenOrientationAngle = 0;
  96690. this._screenQuaternion = new BABYLON.Quaternion();
  96691. this._alpha = 0;
  96692. this._beta = 0;
  96693. this._gamma = 0;
  96694. this._orientationChanged = function () {
  96695. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  96696. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  96697. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  96698. };
  96699. this._deviceOrientation = function (evt) {
  96700. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  96701. _this._beta = evt.beta !== null ? evt.beta : 0;
  96702. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  96703. };
  96704. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  96705. this._orientationChanged();
  96706. }
  96707. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  96708. get: function () {
  96709. return this._camera;
  96710. },
  96711. set: function (camera) {
  96712. this._camera = camera;
  96713. if (this._camera != null && !this._camera.rotationQuaternion) {
  96714. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  96715. }
  96716. },
  96717. enumerable: true,
  96718. configurable: true
  96719. });
  96720. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  96721. window.addEventListener("orientationchange", this._orientationChanged);
  96722. window.addEventListener("deviceorientation", this._deviceOrientation);
  96723. //In certain cases, the attach control is called AFTER orientation was changed,
  96724. //So this is needed.
  96725. this._orientationChanged();
  96726. };
  96727. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  96728. window.removeEventListener("orientationchange", this._orientationChanged);
  96729. window.removeEventListener("deviceorientation", this._deviceOrientation);
  96730. };
  96731. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  96732. //if no device orientation provided, don't update the rotation.
  96733. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  96734. if (!this._alpha)
  96735. return;
  96736. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  96737. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  96738. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  96739. //Mirror on XY Plane
  96740. this._camera.rotationQuaternion.z *= -1;
  96741. this._camera.rotationQuaternion.w *= -1;
  96742. };
  96743. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  96744. return "FreeCameraDeviceOrientationInput";
  96745. };
  96746. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  96747. return "deviceOrientation";
  96748. };
  96749. return FreeCameraDeviceOrientationInput;
  96750. }());
  96751. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  96752. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  96753. })(BABYLON || (BABYLON = {}));
  96754. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  96755. var BABYLON;
  96756. (function (BABYLON) {
  96757. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  96758. function ArcRotateCameraVRDeviceOrientationInput() {
  96759. this.alphaCorrection = 1;
  96760. this.betaCorrection = 1;
  96761. this.gammaCorrection = 1;
  96762. this._alpha = 0;
  96763. this._gamma = 0;
  96764. this._dirty = false;
  96765. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  96766. }
  96767. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  96768. this.camera.attachControl(element, noPreventDefault);
  96769. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  96770. };
  96771. /** @hidden */
  96772. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  96773. if (evt.alpha !== null) {
  96774. this._alpha = +evt.alpha | 0;
  96775. }
  96776. if (evt.gamma !== null) {
  96777. this._gamma = +evt.gamma | 0;
  96778. }
  96779. this._dirty = true;
  96780. };
  96781. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  96782. if (this._dirty) {
  96783. this._dirty = false;
  96784. if (this._gamma < 0) {
  96785. this._gamma = 180 + this._gamma;
  96786. }
  96787. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  96788. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  96789. }
  96790. };
  96791. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  96792. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  96793. };
  96794. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  96795. return "ArcRotateCameraVRDeviceOrientationInput";
  96796. };
  96797. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  96798. return "VRDeviceOrientation";
  96799. };
  96800. return ArcRotateCameraVRDeviceOrientationInput;
  96801. }());
  96802. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  96803. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  96804. })(BABYLON || (BABYLON = {}));
  96805. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  96806. var BABYLON;
  96807. (function (BABYLON) {
  96808. var VRCameraMetrics = /** @class */ (function () {
  96809. function VRCameraMetrics() {
  96810. this.compensateDistortion = true;
  96811. }
  96812. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  96813. get: function () {
  96814. return this.hResolution / (2 * this.vResolution);
  96815. },
  96816. enumerable: true,
  96817. configurable: true
  96818. });
  96819. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  96820. get: function () {
  96821. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  96822. },
  96823. enumerable: true,
  96824. configurable: true
  96825. });
  96826. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  96827. get: function () {
  96828. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  96829. var h = (4 * meters) / this.hScreenSize;
  96830. return BABYLON.Matrix.Translation(h, 0, 0);
  96831. },
  96832. enumerable: true,
  96833. configurable: true
  96834. });
  96835. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  96836. get: function () {
  96837. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  96838. var h = (4 * meters) / this.hScreenSize;
  96839. return BABYLON.Matrix.Translation(-h, 0, 0);
  96840. },
  96841. enumerable: true,
  96842. configurable: true
  96843. });
  96844. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  96845. get: function () {
  96846. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  96847. },
  96848. enumerable: true,
  96849. configurable: true
  96850. });
  96851. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  96852. get: function () {
  96853. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  96854. },
  96855. enumerable: true,
  96856. configurable: true
  96857. });
  96858. VRCameraMetrics.GetDefault = function () {
  96859. var result = new VRCameraMetrics();
  96860. result.hResolution = 1280;
  96861. result.vResolution = 800;
  96862. result.hScreenSize = 0.149759993;
  96863. result.vScreenSize = 0.0935999975;
  96864. result.vScreenCenter = 0.0467999987;
  96865. result.eyeToScreenDistance = 0.0410000011;
  96866. result.lensSeparationDistance = 0.0635000020;
  96867. result.interpupillaryDistance = 0.0640000030;
  96868. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  96869. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  96870. result.postProcessScaleFactor = 1.714605507808412;
  96871. result.lensCenterOffset = 0.151976421;
  96872. return result;
  96873. };
  96874. return VRCameraMetrics;
  96875. }());
  96876. BABYLON.VRCameraMetrics = VRCameraMetrics;
  96877. })(BABYLON || (BABYLON = {}));
  96878. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  96879. var BABYLON;
  96880. (function (BABYLON) {
  96881. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  96882. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  96883. });
  96884. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  96885. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  96886. });
  96887. /**
  96888. * This represents a WebVR camera.
  96889. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  96890. * @example http://doc.babylonjs.com/how_to/webvr_camera
  96891. */
  96892. var WebVRFreeCamera = /** @class */ (function (_super) {
  96893. __extends(WebVRFreeCamera, _super);
  96894. /**
  96895. * Instantiates a WebVRFreeCamera.
  96896. * @param name The name of the WebVRFreeCamera
  96897. * @param position The starting anchor position for the camera
  96898. * @param scene The scene the camera belongs to
  96899. * @param webVROptions a set of customizable options for the webVRCamera
  96900. */
  96901. function WebVRFreeCamera(name, position, scene, webVROptions) {
  96902. if (webVROptions === void 0) { webVROptions = {}; }
  96903. var _this = _super.call(this, name, position, scene) || this;
  96904. _this.webVROptions = webVROptions;
  96905. /**
  96906. * @hidden
  96907. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  96908. */
  96909. _this._vrDevice = null;
  96910. /**
  96911. * The rawPose of the vrDevice.
  96912. */
  96913. _this.rawPose = null;
  96914. _this._specsVersion = "1.1";
  96915. _this._attached = false;
  96916. _this._descendants = [];
  96917. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  96918. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  96919. /** @hidden */
  96920. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  96921. _this._standingMatrix = null;
  96922. /**
  96923. * Represents device position in babylon space.
  96924. */
  96925. _this.devicePosition = BABYLON.Vector3.Zero();
  96926. /**
  96927. * Represents device rotation in babylon space.
  96928. */
  96929. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  96930. /**
  96931. * The scale of the device to be used when translating from device space to babylon space.
  96932. */
  96933. _this.deviceScaleFactor = 1;
  96934. _this._deviceToWorld = BABYLON.Matrix.Identity();
  96935. _this._worldToDevice = BABYLON.Matrix.Identity();
  96936. /**
  96937. * References to the webVR controllers for the vrDevice.
  96938. */
  96939. _this.controllers = [];
  96940. /**
  96941. * Emits an event when a controller is attached.
  96942. */
  96943. _this.onControllersAttachedObservable = new BABYLON.Observable();
  96944. /**
  96945. * Emits an event when a controller's mesh has been loaded;
  96946. */
  96947. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  96948. /**
  96949. * Emits an event when the HMD's pose has been updated.
  96950. */
  96951. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  96952. _this._poseSet = false;
  96953. /**
  96954. * If the rig cameras be used as parent instead of this camera.
  96955. */
  96956. _this.rigParenting = true;
  96957. _this._defaultHeight = undefined;
  96958. _this._htmlElementAttached = null;
  96959. _this._detachIfAttached = function () {
  96960. var vrDisplay = _this.getEngine().getVRDevice();
  96961. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  96962. _this.detachControl(_this._htmlElementAttached);
  96963. }
  96964. };
  96965. _this._workingVector = BABYLON.Vector3.Zero();
  96966. _this._oneVector = BABYLON.Vector3.One();
  96967. _this._workingMatrix = BABYLON.Matrix.Identity();
  96968. _this._tmpMatrix = new BABYLON.Matrix();
  96969. _this._cache.position = BABYLON.Vector3.Zero();
  96970. if (webVROptions.defaultHeight) {
  96971. _this._defaultHeight = webVROptions.defaultHeight;
  96972. _this.position.y = _this._defaultHeight;
  96973. }
  96974. _this.minZ = 0.1;
  96975. //legacy support - the compensation boolean was removed.
  96976. if (arguments.length === 5) {
  96977. _this.webVROptions = arguments[4];
  96978. }
  96979. // default webVR options
  96980. if (_this.webVROptions.trackPosition == undefined) {
  96981. _this.webVROptions.trackPosition = true;
  96982. }
  96983. if (_this.webVROptions.controllerMeshes == undefined) {
  96984. _this.webVROptions.controllerMeshes = true;
  96985. }
  96986. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  96987. _this.webVROptions.defaultLightingOnControllers = true;
  96988. }
  96989. _this.rotationQuaternion = new BABYLON.Quaternion();
  96990. if (_this.webVROptions && _this.webVROptions.positionScale) {
  96991. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  96992. }
  96993. //enable VR
  96994. var engine = _this.getEngine();
  96995. _this._onVREnabled = function (success) { if (success) {
  96996. _this.initControllers();
  96997. } };
  96998. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  96999. engine.initWebVR().add(function (event) {
  97000. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  97001. return;
  97002. }
  97003. _this._vrDevice = event.vrDisplay;
  97004. //reset the rig parameters.
  97005. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  97006. if (_this._attached) {
  97007. _this.getEngine().enableVR();
  97008. }
  97009. });
  97010. if (typeof (VRFrameData) !== "undefined")
  97011. _this._frameData = new VRFrameData();
  97012. /**
  97013. * The idea behind the following lines:
  97014. * objects that have the camera as parent should actually have the rig cameras as a parent.
  97015. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  97016. * the second will not show it correctly.
  97017. *
  97018. * To solve this - each object that has the camera as parent will be added to a protected array.
  97019. * When the rig camera renders, it will take this array and set all of those to be its children.
  97020. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  97021. * Amazing!
  97022. */
  97023. scene.onBeforeCameraRenderObservable.add(function (camera) {
  97024. if (camera.parent === _this && _this.rigParenting) {
  97025. _this._descendants = _this.getDescendants(true, function (n) {
  97026. // don't take the cameras or the controllers!
  97027. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  97028. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  97029. return !isController && !isRigCamera;
  97030. });
  97031. _this._descendants.forEach(function (node) {
  97032. node.parent = camera;
  97033. });
  97034. }
  97035. });
  97036. scene.onAfterCameraRenderObservable.add(function (camera) {
  97037. if (camera.parent === _this && _this.rigParenting) {
  97038. _this._descendants.forEach(function (node) {
  97039. node.parent = _this;
  97040. });
  97041. }
  97042. });
  97043. return _this;
  97044. }
  97045. /**
  97046. * Gets the device distance from the ground in meters.
  97047. * @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.
  97048. */
  97049. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  97050. if (this._standingMatrix) {
  97051. // Add standing matrix offset to get real offset from ground in room
  97052. this._standingMatrix.getTranslationToRef(this._workingVector);
  97053. return this._deviceRoomPosition.y + this._workingVector.y;
  97054. }
  97055. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  97056. return this._defaultHeight || 0;
  97057. };
  97058. /**
  97059. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  97060. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  97061. */
  97062. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  97063. var _this = this;
  97064. if (callback === void 0) { callback = function (bool) { }; }
  97065. // Use standing matrix if available
  97066. this.getEngine().initWebVRAsync().then(function (result) {
  97067. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  97068. callback(false);
  97069. }
  97070. else {
  97071. _this._standingMatrix = new BABYLON.Matrix();
  97072. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  97073. if (!_this.getScene().useRightHandedSystem) {
  97074. [2, 6, 8, 9, 14].forEach(function (num) {
  97075. if (_this._standingMatrix) {
  97076. _this._standingMatrix.m[num] *= -1;
  97077. }
  97078. });
  97079. }
  97080. callback(true);
  97081. }
  97082. });
  97083. };
  97084. /**
  97085. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  97086. * @returns A promise with a boolean set to if the standing matrix is supported.
  97087. */
  97088. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  97089. var _this = this;
  97090. return new Promise(function (res, rej) {
  97091. _this.useStandingMatrix(function (supported) {
  97092. res(supported);
  97093. });
  97094. });
  97095. };
  97096. /**
  97097. * Disposes the camera
  97098. */
  97099. WebVRFreeCamera.prototype.dispose = function () {
  97100. this._detachIfAttached();
  97101. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  97102. _super.prototype.dispose.call(this);
  97103. };
  97104. /**
  97105. * Gets a vrController by name.
  97106. * @param name The name of the controller to retreive
  97107. * @returns the controller matching the name specified or null if not found
  97108. */
  97109. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  97110. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  97111. var gp = _a[_i];
  97112. if (gp.hand === name) {
  97113. return gp;
  97114. }
  97115. }
  97116. return null;
  97117. };
  97118. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  97119. /**
  97120. * The controller corrisponding to the users left hand.
  97121. */
  97122. get: function () {
  97123. if (!this._leftController) {
  97124. this._leftController = this.getControllerByName("left");
  97125. }
  97126. return this._leftController;
  97127. },
  97128. enumerable: true,
  97129. configurable: true
  97130. });
  97131. ;
  97132. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  97133. /**
  97134. * The controller corrisponding to the users right hand.
  97135. */
  97136. get: function () {
  97137. if (!this._rightController) {
  97138. this._rightController = this.getControllerByName("right");
  97139. }
  97140. return this._rightController;
  97141. },
  97142. enumerable: true,
  97143. configurable: true
  97144. });
  97145. ;
  97146. /**
  97147. * Casts a ray forward from the vrCamera's gaze.
  97148. * @param length Length of the ray (default: 100)
  97149. * @returns the ray corrisponding to the gaze
  97150. */
  97151. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  97152. if (length === void 0) { length = 100; }
  97153. if (this.leftCamera) {
  97154. // Use left eye to avoid computation to compute center on every call
  97155. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  97156. }
  97157. else {
  97158. return _super.prototype.getForwardRay.call(this, length);
  97159. }
  97160. };
  97161. /**
  97162. * @hidden
  97163. * Updates the camera based on device's frame data
  97164. */
  97165. WebVRFreeCamera.prototype._checkInputs = function () {
  97166. if (this._vrDevice && this._vrDevice.isPresenting) {
  97167. this._vrDevice.getFrameData(this._frameData);
  97168. this.updateFromDevice(this._frameData.pose);
  97169. }
  97170. _super.prototype._checkInputs.call(this);
  97171. };
  97172. /**
  97173. * Updates the poseControlled values based on the input device pose.
  97174. * @param poseData Pose coming from the device
  97175. */
  97176. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  97177. if (poseData && poseData.orientation) {
  97178. this.rawPose = poseData;
  97179. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  97180. if (this.getScene().useRightHandedSystem) {
  97181. this._deviceRoomRotationQuaternion.z *= -1;
  97182. this._deviceRoomRotationQuaternion.w *= -1;
  97183. }
  97184. if (this.webVROptions.trackPosition && this.rawPose.position) {
  97185. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  97186. if (this.getScene().useRightHandedSystem) {
  97187. this._deviceRoomPosition.z *= -1;
  97188. }
  97189. }
  97190. this._poseSet = true;
  97191. }
  97192. };
  97193. /**
  97194. * WebVR's attach control will start broadcasting frames to the device.
  97195. * Note that in certain browsers (chrome for example) this function must be called
  97196. * within a user-interaction callback. Example:
  97197. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  97198. *
  97199. * @param element html element to attach the vrDevice to
  97200. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  97201. */
  97202. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  97203. _super.prototype.attachControl.call(this, element, noPreventDefault);
  97204. this._attached = true;
  97205. this._htmlElementAttached = element;
  97206. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  97207. if (this._vrDevice) {
  97208. this.getEngine().enableVR();
  97209. }
  97210. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  97211. };
  97212. /**
  97213. * Detaches the camera from the html element and disables VR
  97214. *
  97215. * @param element html element to detach from
  97216. */
  97217. WebVRFreeCamera.prototype.detachControl = function (element) {
  97218. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  97219. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  97220. _super.prototype.detachControl.call(this, element);
  97221. this._attached = false;
  97222. this.getEngine().disableVR();
  97223. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  97224. };
  97225. /**
  97226. * @returns the name of this class
  97227. */
  97228. WebVRFreeCamera.prototype.getClassName = function () {
  97229. return "WebVRFreeCamera";
  97230. };
  97231. /**
  97232. * Calls resetPose on the vrDisplay
  97233. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  97234. */
  97235. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  97236. //uses the vrDisplay's "resetPose()".
  97237. //pitch and roll won't be affected.
  97238. this._vrDevice.resetPose();
  97239. };
  97240. /**
  97241. * @hidden
  97242. * Updates the rig cameras (left and right eye)
  97243. */
  97244. WebVRFreeCamera.prototype._updateRigCameras = function () {
  97245. var camLeft = this._rigCameras[0];
  97246. var camRight = this._rigCameras[1];
  97247. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  97248. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  97249. camLeft.position.copyFrom(this._deviceRoomPosition);
  97250. camRight.position.copyFrom(this._deviceRoomPosition);
  97251. };
  97252. // Remove translation from 6dof headset if trackposition is set to false
  97253. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  97254. if (isViewMatrix === void 0) { isViewMatrix = false; }
  97255. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  97256. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  97257. if (!isViewMatrix) {
  97258. this._tmpMatrix.invert();
  97259. }
  97260. this._tmpMatrix.multiplyToRef(matrix, matrix);
  97261. }
  97262. };
  97263. /**
  97264. * @hidden
  97265. * Updates the cached values of the camera
  97266. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  97267. */
  97268. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  97269. var _this = this;
  97270. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  97271. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  97272. if (!this.updateCacheCalled) {
  97273. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  97274. this.updateCacheCalled = true;
  97275. this.update();
  97276. }
  97277. // Set working vector to the device position in room space rotated by the new rotation
  97278. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  97279. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  97280. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  97281. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  97282. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  97283. // Add translation from anchor position
  97284. this._deviceToWorld.getTranslationToRef(this._workingVector);
  97285. this._workingVector.addInPlace(this.position);
  97286. this._workingVector.subtractInPlace(this._cache.position);
  97287. this._deviceToWorld.setTranslation(this._workingVector);
  97288. // Set an inverted matrix to be used when updating the camera
  97289. this._deviceToWorld.invertToRef(this._worldToDevice);
  97290. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  97291. this.controllers.forEach(function (controller) {
  97292. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  97293. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  97294. controller.update();
  97295. });
  97296. }
  97297. if (!ignoreParentClass) {
  97298. _super.prototype._updateCache.call(this);
  97299. }
  97300. this.updateCacheCalled = false;
  97301. };
  97302. /**
  97303. * Updates the current device position and rotation in the babylon world
  97304. */
  97305. WebVRFreeCamera.prototype.update = function () {
  97306. // Get current device position in babylon world
  97307. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  97308. // Get current device rotation in babylon world
  97309. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  97310. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  97311. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  97312. if (this._poseSet) {
  97313. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  97314. }
  97315. _super.prototype.update.call(this);
  97316. };
  97317. /**
  97318. * @hidden
  97319. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  97320. * @returns an identity matrix
  97321. */
  97322. WebVRFreeCamera.prototype._getViewMatrix = function () {
  97323. return BABYLON.Matrix.Identity();
  97324. };
  97325. /**
  97326. * This function is called by the two RIG cameras.
  97327. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  97328. */
  97329. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  97330. var _this = this;
  97331. // Update the parent camera prior to using a child camera to avoid desynchronization
  97332. var parentCamera = this._cameraRigParams["parentCamera"];
  97333. parentCamera._updateCache();
  97334. //WebVR 1.1
  97335. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  97336. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  97337. if (!this.getScene().useRightHandedSystem) {
  97338. [2, 6, 8, 9, 14].forEach(function (num) {
  97339. _this._webvrViewMatrix.m[num] *= -1;
  97340. });
  97341. }
  97342. // update the camera rotation matrix
  97343. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  97344. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  97345. // Computing target and final matrix
  97346. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  97347. // should the view matrix be updated with scale and position offset?
  97348. if (parentCamera.deviceScaleFactor !== 1) {
  97349. this._webvrViewMatrix.invert();
  97350. // scale the position, if set
  97351. if (parentCamera.deviceScaleFactor) {
  97352. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  97353. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  97354. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  97355. }
  97356. this._webvrViewMatrix.invert();
  97357. }
  97358. // Remove translation from 6dof headset if trackposition is set to false
  97359. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  97360. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  97361. // Compute global position
  97362. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  97363. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  97364. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  97365. this._workingMatrix.getTranslationToRef(this._globalPosition);
  97366. this._markSyncedWithParent();
  97367. return this._webvrViewMatrix;
  97368. };
  97369. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  97370. var _this = this;
  97371. var parentCamera = this.parent;
  97372. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  97373. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  97374. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  97375. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  97376. //babylon compatible matrix
  97377. if (!this.getScene().useRightHandedSystem) {
  97378. [8, 9, 10, 11].forEach(function (num) {
  97379. _this._projectionMatrix.m[num] *= -1;
  97380. });
  97381. }
  97382. return this._projectionMatrix;
  97383. };
  97384. /**
  97385. * Initializes the controllers and their meshes
  97386. */
  97387. WebVRFreeCamera.prototype.initControllers = function () {
  97388. var _this = this;
  97389. this.controllers = [];
  97390. var manager = this.getScene().gamepadManager;
  97391. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  97392. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  97393. var webVrController = gamepad;
  97394. if (webVrController.defaultModel) {
  97395. webVrController.defaultModel.setEnabled(false);
  97396. }
  97397. if (webVrController.hand === "right") {
  97398. _this._rightController = null;
  97399. }
  97400. if (webVrController.hand === "left") {
  97401. _this._leftController = null;
  97402. }
  97403. var controllerIndex = _this.controllers.indexOf(webVrController);
  97404. if (controllerIndex !== -1) {
  97405. _this.controllers.splice(controllerIndex, 1);
  97406. }
  97407. }
  97408. });
  97409. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  97410. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  97411. var webVrController_1 = gamepad;
  97412. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  97413. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  97414. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  97415. if (_this.webVROptions.controllerMeshes) {
  97416. if (webVrController_1.defaultModel) {
  97417. webVrController_1.defaultModel.setEnabled(true);
  97418. }
  97419. else {
  97420. // Load the meshes
  97421. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  97422. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  97423. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  97424. if (_this.webVROptions.defaultLightingOnControllers) {
  97425. if (!_this._lightOnControllers) {
  97426. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  97427. }
  97428. var activateLightOnSubMeshes_1 = function (mesh, light) {
  97429. var children = mesh.getChildren();
  97430. if (children && children.length !== 0) {
  97431. children.forEach(function (mesh) {
  97432. light.includedOnlyMeshes.push(mesh);
  97433. activateLightOnSubMeshes_1(mesh, light);
  97434. });
  97435. }
  97436. };
  97437. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  97438. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  97439. }
  97440. });
  97441. }
  97442. }
  97443. webVrController_1.attachToPoseControlledCamera(_this);
  97444. // since this is async - sanity check. Is the controller already stored?
  97445. if (_this.controllers.indexOf(webVrController_1) === -1) {
  97446. //add to the controllers array
  97447. _this.controllers.push(webVrController_1);
  97448. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  97449. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  97450. // So we're overriding setting left & right manually to be sure
  97451. var firstViveWandDetected = false;
  97452. for (var i = 0; i < _this.controllers.length; i++) {
  97453. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  97454. if (!firstViveWandDetected) {
  97455. firstViveWandDetected = true;
  97456. _this.controllers[i].hand = "left";
  97457. }
  97458. else {
  97459. _this.controllers[i].hand = "right";
  97460. }
  97461. }
  97462. }
  97463. //did we find enough controllers? Great! let the developer know.
  97464. if (_this.controllers.length >= 2) {
  97465. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  97466. }
  97467. }
  97468. }
  97469. });
  97470. };
  97471. return WebVRFreeCamera;
  97472. }(BABYLON.FreeCamera));
  97473. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  97474. })(BABYLON || (BABYLON = {}));
  97475. //# sourceMappingURL=babylon.webVRCamera.js.map
  97476. var BABYLON;
  97477. (function (BABYLON) {
  97478. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  97479. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  97480. });
  97481. // We're mainly based on the logic defined into the FreeCamera code
  97482. /**
  97483. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  97484. * being tilted forward or back and left or right.
  97485. */
  97486. var DeviceOrientationCamera = /** @class */ (function (_super) {
  97487. __extends(DeviceOrientationCamera, _super);
  97488. /**
  97489. * Creates a new device orientation camera
  97490. * @param name The name of the camera
  97491. * @param position The start position camera
  97492. * @param scene The scene the camera belongs to
  97493. */
  97494. function DeviceOrientationCamera(name, position, scene) {
  97495. var _this = _super.call(this, name, position, scene) || this;
  97496. _this._quaternionCache = new BABYLON.Quaternion();
  97497. _this.inputs.addDeviceOrientation();
  97498. return _this;
  97499. }
  97500. /**
  97501. * Gets the current instance class name ("DeviceOrientationCamera").
  97502. * This helps avoiding instanceof at run time.
  97503. * @returns the class name
  97504. */
  97505. DeviceOrientationCamera.prototype.getClassName = function () {
  97506. return "DeviceOrientationCamera";
  97507. };
  97508. /**
  97509. * @hidden
  97510. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  97511. */
  97512. DeviceOrientationCamera.prototype._checkInputs = function () {
  97513. _super.prototype._checkInputs.call(this);
  97514. this._quaternionCache.copyFrom(this.rotationQuaternion);
  97515. if (this._initialQuaternion) {
  97516. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  97517. }
  97518. };
  97519. /**
  97520. * Reset the camera to its default orientation on the specified axis only.
  97521. * @param axis The axis to reset
  97522. */
  97523. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  97524. var _this = this;
  97525. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  97526. //can only work if this camera has a rotation quaternion already.
  97527. if (!this.rotationQuaternion)
  97528. return;
  97529. if (!this._initialQuaternion) {
  97530. this._initialQuaternion = new BABYLON.Quaternion();
  97531. }
  97532. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  97533. ['x', 'y', 'z'].forEach(function (axisName) {
  97534. if (!axis[axisName]) {
  97535. _this._initialQuaternion[axisName] = 0;
  97536. }
  97537. else {
  97538. _this._initialQuaternion[axisName] *= -1;
  97539. }
  97540. });
  97541. this._initialQuaternion.normalize();
  97542. //force rotation update
  97543. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  97544. };
  97545. return DeviceOrientationCamera;
  97546. }(BABYLON.FreeCamera));
  97547. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  97548. })(BABYLON || (BABYLON = {}));
  97549. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  97550. var BABYLON;
  97551. (function (BABYLON) {
  97552. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  97553. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  97554. });
  97555. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  97556. __extends(VRDeviceOrientationFreeCamera, _super);
  97557. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  97558. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97559. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97560. var _this = _super.call(this, name, position, scene) || this;
  97561. vrCameraMetrics.compensateDistortion = compensateDistortion;
  97562. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  97563. return _this;
  97564. }
  97565. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  97566. return "VRDeviceOrientationFreeCamera";
  97567. };
  97568. return VRDeviceOrientationFreeCamera;
  97569. }(BABYLON.DeviceOrientationCamera));
  97570. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  97571. })(BABYLON || (BABYLON = {}));
  97572. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  97573. var BABYLON;
  97574. (function (BABYLON) {
  97575. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  97576. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  97577. });
  97578. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  97579. __extends(VRDeviceOrientationArcRotateCamera, _super);
  97580. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  97581. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97582. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97583. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  97584. vrCameraMetrics.compensateDistortion = compensateDistortion;
  97585. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  97586. _this.inputs.addVRDeviceOrientation();
  97587. return _this;
  97588. }
  97589. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  97590. return "VRDeviceOrientationArcRotateCamera";
  97591. };
  97592. return VRDeviceOrientationArcRotateCamera;
  97593. }(BABYLON.ArcRotateCamera));
  97594. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  97595. })(BABYLON || (BABYLON = {}));
  97596. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  97597. var BABYLON;
  97598. (function (BABYLON) {
  97599. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  97600. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  97601. });
  97602. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  97603. __extends(VRDeviceOrientationGamepadCamera, _super);
  97604. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  97605. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97606. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97607. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  97608. _this.inputs.addGamepad();
  97609. return _this;
  97610. }
  97611. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  97612. return "VRDeviceOrientationGamepadCamera";
  97613. };
  97614. return VRDeviceOrientationGamepadCamera;
  97615. }(BABYLON.VRDeviceOrientationFreeCamera));
  97616. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  97617. })(BABYLON || (BABYLON = {}));
  97618. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  97619. var BABYLON;
  97620. (function (BABYLON) {
  97621. var VRExperienceHelperGazer = /** @class */ (function () {
  97622. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  97623. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  97624. this.scene = scene;
  97625. /** @hidden */
  97626. this._pointerDownOnMeshAsked = false;
  97627. /** @hidden */
  97628. this._isActionableMesh = false;
  97629. /** @hidden */
  97630. this._teleportationRequestInitiated = false;
  97631. /** @hidden */
  97632. this._teleportationBackRequestInitiated = false;
  97633. /** @hidden */
  97634. this._rotationRightAsked = false;
  97635. /** @hidden */
  97636. this._rotationLeftAsked = false;
  97637. /** @hidden */
  97638. this._dpadPressed = true;
  97639. /** @hidden */
  97640. this._activePointer = false;
  97641. this._id = VRExperienceHelperGazer._idCounter++;
  97642. // Gaze tracker
  97643. if (!gazeTrackerToClone) {
  97644. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  97645. this._gazeTracker.bakeCurrentTransformIntoVertices();
  97646. this._gazeTracker.isPickable = false;
  97647. this._gazeTracker.isVisible = false;
  97648. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  97649. targetMat.specularColor = BABYLON.Color3.Black();
  97650. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  97651. targetMat.backFaceCulling = false;
  97652. this._gazeTracker.material = targetMat;
  97653. }
  97654. else {
  97655. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  97656. }
  97657. }
  97658. /** @hidden */
  97659. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  97660. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  97661. };
  97662. /** @hidden */
  97663. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  97664. this._pointerDownOnMeshAsked = true;
  97665. if (this._currentHit) {
  97666. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  97667. }
  97668. };
  97669. /** @hidden */
  97670. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  97671. if (this._currentHit) {
  97672. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  97673. }
  97674. this._pointerDownOnMeshAsked = false;
  97675. };
  97676. /** @hidden */
  97677. VRExperienceHelperGazer.prototype._activatePointer = function () {
  97678. this._activePointer = true;
  97679. };
  97680. /** @hidden */
  97681. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  97682. this._activePointer = false;
  97683. };
  97684. /** @hidden */
  97685. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  97686. if (distance === void 0) { distance = 100; }
  97687. };
  97688. VRExperienceHelperGazer.prototype.dispose = function () {
  97689. this._interactionsEnabled = false;
  97690. this._teleportationEnabled = false;
  97691. if (this._gazeTracker) {
  97692. this._gazeTracker.dispose();
  97693. }
  97694. };
  97695. VRExperienceHelperGazer._idCounter = 0;
  97696. return VRExperienceHelperGazer;
  97697. }());
  97698. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  97699. __extends(VRExperienceHelperControllerGazer, _super);
  97700. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  97701. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  97702. _this.webVRController = webVRController;
  97703. // Laser pointer
  97704. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  97705. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  97706. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  97707. laserPointerMaterial.alpha = 0.6;
  97708. _this._laserPointer.material = laserPointerMaterial;
  97709. _this._laserPointer.rotation.x = Math.PI / 2;
  97710. _this._laserPointer.position.z = -0.5;
  97711. _this._laserPointer.isVisible = false;
  97712. _this._laserPointer.isPickable = false;
  97713. if (!webVRController.mesh) {
  97714. // Create an empty mesh that is used prior to loading the high quality model
  97715. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  97716. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  97717. preloadPointerPose.rotation.x = -0.7;
  97718. preloadMesh.addChild(preloadPointerPose);
  97719. webVRController.attachToMesh(preloadMesh);
  97720. }
  97721. _this._setLaserPointerParent(webVRController.mesh);
  97722. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  97723. _this._setLaserPointerParent(mesh);
  97724. });
  97725. return _this;
  97726. }
  97727. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  97728. return this.webVRController.getForwardRay(length);
  97729. };
  97730. /** @hidden */
  97731. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  97732. _super.prototype._activatePointer.call(this);
  97733. this._laserPointer.isVisible = true;
  97734. };
  97735. /** @hidden */
  97736. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  97737. _super.prototype._deactivatePointer.call(this);
  97738. this._laserPointer.isVisible = false;
  97739. };
  97740. /** @hidden */
  97741. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  97742. this._laserPointer.material.emissiveColor = color;
  97743. };
  97744. /** @hidden */
  97745. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  97746. var makeNotPick = function (root) {
  97747. root.isPickable = false;
  97748. root.getChildMeshes().forEach(function (c) {
  97749. makeNotPick(c);
  97750. });
  97751. };
  97752. makeNotPick(mesh);
  97753. var childMeshes = mesh.getChildMeshes();
  97754. this.webVRController._pointingPoseNode = null;
  97755. for (var i = 0; i < childMeshes.length; i++) {
  97756. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  97757. mesh = childMeshes[i];
  97758. this.webVRController._pointingPoseNode = mesh;
  97759. break;
  97760. }
  97761. }
  97762. this._laserPointer.parent = mesh;
  97763. };
  97764. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  97765. if (distance === void 0) { distance = 100; }
  97766. this._laserPointer.scaling.y = distance;
  97767. this._laserPointer.position.z = -distance / 2;
  97768. };
  97769. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  97770. _super.prototype.dispose.call(this);
  97771. this._laserPointer.dispose();
  97772. if (this._meshAttachedObserver) {
  97773. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  97774. }
  97775. };
  97776. return VRExperienceHelperControllerGazer;
  97777. }(VRExperienceHelperGazer));
  97778. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  97779. __extends(VRExperienceHelperCameraGazer, _super);
  97780. function VRExperienceHelperCameraGazer(getCamera, scene) {
  97781. var _this = _super.call(this, scene) || this;
  97782. _this.getCamera = getCamera;
  97783. return _this;
  97784. }
  97785. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  97786. var camera = this.getCamera();
  97787. if (camera) {
  97788. return camera.getForwardRay(length);
  97789. }
  97790. else {
  97791. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  97792. }
  97793. };
  97794. return VRExperienceHelperCameraGazer;
  97795. }(VRExperienceHelperGazer));
  97796. /**
  97797. * Helps to quickly add VR support to an existing scene.
  97798. * See http://doc.babylonjs.com/how_to/webvr_helper
  97799. */
  97800. var VRExperienceHelper = /** @class */ (function () {
  97801. /**
  97802. * Instantiates a VRExperienceHelper.
  97803. * Helps to quickly add VR support to an existing scene.
  97804. * @param scene The scene the VRExperienceHelper belongs to.
  97805. * @param webVROptions Options to modify the vr experience helper's behavior.
  97806. */
  97807. function VRExperienceHelper(scene,
  97808. /** Options to modify the vr experience helper's behavior. */
  97809. webVROptions) {
  97810. if (webVROptions === void 0) { webVROptions = {}; }
  97811. var _this = this;
  97812. this.webVROptions = webVROptions;
  97813. // Can the system support WebVR, even if a headset isn't plugged in?
  97814. this._webVRsupported = false;
  97815. // If WebVR is supported, is a headset plugged in and are we ready to present?
  97816. this._webVRready = false;
  97817. // Are we waiting for the requestPresent callback to complete?
  97818. this._webVRrequesting = false;
  97819. // Are we presenting to the headset right now? (this is the vrDevice state)
  97820. this._webVRpresenting = false;
  97821. // Are we presenting in the fullscreen fallback?
  97822. this._fullscreenVRpresenting = false;
  97823. /**
  97824. * Observable raised when entering VR.
  97825. */
  97826. this.onEnteringVRObservable = new BABYLON.Observable();
  97827. /**
  97828. * Observable raised when exiting VR.
  97829. */
  97830. this.onExitingVRObservable = new BABYLON.Observable();
  97831. /**
  97832. * Observable raised when controller mesh is loaded.
  97833. */
  97834. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  97835. this._useCustomVRButton = false;
  97836. this._teleportationRequested = false;
  97837. this._teleportActive = false;
  97838. this._floorMeshesCollection = [];
  97839. this._rotationAllowed = true;
  97840. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  97841. this._isDefaultTeleportationTarget = true;
  97842. this._teleportationFillColor = "#444444";
  97843. this._teleportationBorderColor = "#FFFFFF";
  97844. this._rotationAngle = 0;
  97845. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  97846. this._padSensibilityUp = 0.65;
  97847. this._padSensibilityDown = 0.35;
  97848. this._leftController = null;
  97849. this._rightController = null;
  97850. /**
  97851. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  97852. */
  97853. this.onNewMeshSelected = new BABYLON.Observable();
  97854. /**
  97855. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  97856. */
  97857. this.onNewMeshPicked = new BABYLON.Observable();
  97858. /**
  97859. * Observable raised before camera teleportation
  97860. */
  97861. this.onBeforeCameraTeleport = new BABYLON.Observable();
  97862. /**
  97863. * Observable raised after camera teleportation
  97864. */
  97865. this.onAfterCameraTeleport = new BABYLON.Observable();
  97866. /**
  97867. * Observable raised when current selected mesh gets unselected
  97868. */
  97869. this.onSelectedMeshUnselected = new BABYLON.Observable();
  97870. /**
  97871. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  97872. */
  97873. this.teleportationEnabled = true;
  97874. this._teleportationInitialized = false;
  97875. this._interactionsEnabled = false;
  97876. this._interactionsRequested = false;
  97877. this._displayGaze = true;
  97878. this._displayLaserPointer = true;
  97879. /**
  97880. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  97881. */
  97882. this.updateGazeTrackerScale = true;
  97883. this._onResize = function () {
  97884. _this.moveButtonToBottomRight();
  97885. if (_this._fullscreenVRpresenting && _this._webVRready) {
  97886. _this.exitVR();
  97887. }
  97888. };
  97889. this._onFullscreenChange = function () {
  97890. if (document.fullscreen !== undefined) {
  97891. _this._fullscreenVRpresenting = document.fullscreen;
  97892. }
  97893. else if (document.mozFullScreen !== undefined) {
  97894. _this._fullscreenVRpresenting = document.mozFullScreen;
  97895. }
  97896. else if (document.webkitIsFullScreen !== undefined) {
  97897. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  97898. }
  97899. else if (document.msIsFullScreen !== undefined) {
  97900. _this._fullscreenVRpresenting = document.msIsFullScreen;
  97901. }
  97902. else if (document.msFullscreenElement !== undefined) {
  97903. _this._fullscreenVRpresenting = document.msFullscreenElement;
  97904. }
  97905. if (!_this._fullscreenVRpresenting && _this._canvas) {
  97906. _this.exitVR();
  97907. if (!_this._useCustomVRButton) {
  97908. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  97909. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  97910. }
  97911. }
  97912. };
  97913. this.beforeRender = function () {
  97914. if (_this._leftController && _this._leftController._activePointer) {
  97915. _this._castRayAndSelectObject(_this._leftController);
  97916. }
  97917. if (_this._rightController && _this._rightController._activePointer) {
  97918. _this._castRayAndSelectObject(_this._rightController);
  97919. }
  97920. if (_this._noControllerIsActive) {
  97921. _this._castRayAndSelectObject(_this._cameraGazer);
  97922. }
  97923. else {
  97924. _this._cameraGazer._gazeTracker.isVisible = false;
  97925. }
  97926. };
  97927. this._onNewGamepadConnected = function (gamepad) {
  97928. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  97929. if (gamepad.leftStick) {
  97930. gamepad.onleftstickchanged(function (stickValues) {
  97931. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  97932. // Listening to classic/xbox gamepad only if no VR controller is active
  97933. if ((!_this._leftController && !_this._rightController) ||
  97934. ((_this._leftController && !_this._leftController._activePointer) &&
  97935. (_this._rightController && !_this._rightController._activePointer))) {
  97936. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  97937. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  97938. }
  97939. }
  97940. });
  97941. }
  97942. if (gamepad.rightStick) {
  97943. gamepad.onrightstickchanged(function (stickValues) {
  97944. if (_this._teleportationInitialized) {
  97945. _this._checkRotate(stickValues, _this._cameraGazer);
  97946. }
  97947. });
  97948. }
  97949. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  97950. gamepad.onbuttondown(function (buttonPressed) {
  97951. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  97952. _this._cameraGazer._selectionPointerDown();
  97953. }
  97954. });
  97955. gamepad.onbuttonup(function (buttonPressed) {
  97956. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  97957. _this._cameraGazer._selectionPointerUp();
  97958. }
  97959. });
  97960. }
  97961. }
  97962. else {
  97963. var webVRController = gamepad;
  97964. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  97965. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  97966. _this._rightController = controller;
  97967. }
  97968. else {
  97969. _this._leftController = controller;
  97970. }
  97971. _this._tryEnableInteractionOnController(controller);
  97972. }
  97973. };
  97974. // 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
  97975. this._tryEnableInteractionOnController = function (controller) {
  97976. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  97977. _this._enableInteractionOnController(controller);
  97978. }
  97979. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  97980. _this._enableTeleportationOnController(controller);
  97981. }
  97982. };
  97983. this._onNewGamepadDisconnected = function (gamepad) {
  97984. if (gamepad instanceof BABYLON.WebVRController) {
  97985. if (gamepad.hand === "left" && _this._leftController != null) {
  97986. _this._leftController.dispose();
  97987. _this._leftController = null;
  97988. }
  97989. if (gamepad.hand === "right" && _this._rightController != null) {
  97990. _this._rightController.dispose();
  97991. _this._rightController = null;
  97992. }
  97993. }
  97994. };
  97995. this._workingVector = BABYLON.Vector3.Zero();
  97996. this._workingQuaternion = BABYLON.Quaternion.Identity();
  97997. this._workingMatrix = BABYLON.Matrix.Identity();
  97998. this._scene = scene;
  97999. this._canvas = scene.getEngine().getRenderingCanvas();
  98000. // Parse options
  98001. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  98002. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  98003. }
  98004. if (webVROptions.createDeviceOrientationCamera === undefined) {
  98005. webVROptions.createDeviceOrientationCamera = true;
  98006. }
  98007. if (webVROptions.laserToggle === undefined) {
  98008. webVROptions.laserToggle = true;
  98009. }
  98010. if (webVROptions.defaultHeight === undefined) {
  98011. webVROptions.defaultHeight = 1.7;
  98012. }
  98013. if (webVROptions.useCustomVRButton) {
  98014. this._useCustomVRButton = true;
  98015. if (webVROptions.customVRButton) {
  98016. this._btnVR = webVROptions.customVRButton;
  98017. }
  98018. }
  98019. if (webVROptions.rayLength) {
  98020. this._rayLength = webVROptions.rayLength;
  98021. }
  98022. this._defaultHeight = webVROptions.defaultHeight;
  98023. if (webVROptions.positionScale) {
  98024. this._rayLength *= webVROptions.positionScale;
  98025. this._defaultHeight *= webVROptions.positionScale;
  98026. }
  98027. this._hasEnteredVR = false;
  98028. // Set position
  98029. if (this._scene.activeCamera) {
  98030. this._position = this._scene.activeCamera.position.clone();
  98031. }
  98032. else {
  98033. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  98034. }
  98035. // Set non-vr camera
  98036. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  98037. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  98038. // Copy data from existing camera
  98039. if (this._scene.activeCamera) {
  98040. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  98041. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  98042. // Set rotation from previous camera
  98043. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  98044. var targetCamera = this._scene.activeCamera;
  98045. if (targetCamera.rotationQuaternion) {
  98046. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  98047. }
  98048. else {
  98049. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  98050. }
  98051. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  98052. }
  98053. }
  98054. this._scene.activeCamera = this._deviceOrientationCamera;
  98055. if (this._canvas) {
  98056. this._scene.activeCamera.attachControl(this._canvas);
  98057. }
  98058. }
  98059. else {
  98060. this._existingCamera = this._scene.activeCamera;
  98061. }
  98062. // Create VR cameras
  98063. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  98064. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  98065. }
  98066. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  98067. this._webVRCamera.useStandingMatrix();
  98068. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  98069. // Create default button
  98070. if (!this._useCustomVRButton) {
  98071. this._btnVR = document.createElement("BUTTON");
  98072. this._btnVR.className = "babylonVRicon";
  98073. this._btnVR.id = "babylonVRiconbtn";
  98074. this._btnVR.title = "Click to switch to VR";
  98075. 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) }";
  98076. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  98077. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  98078. // css += ".babylonVRicon.vrdisplaysupported { }";
  98079. // css += ".babylonVRicon.vrdisplayready { }";
  98080. // css += ".babylonVRicon.vrdisplayrequesting { }";
  98081. var style = document.createElement('style');
  98082. style.appendChild(document.createTextNode(css));
  98083. document.getElementsByTagName('head')[0].appendChild(style);
  98084. this.moveButtonToBottomRight();
  98085. }
  98086. // VR button click event
  98087. if (this._btnVR) {
  98088. this._btnVR.addEventListener("click", function () {
  98089. if (!_this.isInVRMode) {
  98090. _this.enterVR();
  98091. }
  98092. else {
  98093. _this.exitVR();
  98094. }
  98095. });
  98096. }
  98097. // Window events
  98098. window.addEventListener("resize", this._onResize);
  98099. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  98100. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  98101. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  98102. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  98103. document.onmsfullscreenchange = this._onFullscreenChange;
  98104. // Display vr button when headset is connected
  98105. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  98106. this.displayVRButton();
  98107. }
  98108. else {
  98109. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  98110. if (e.vrDisplay) {
  98111. _this.displayVRButton();
  98112. }
  98113. });
  98114. }
  98115. // Exiting VR mode using 'ESC' key on desktop
  98116. this._onKeyDown = function (event) {
  98117. if (event.keyCode === 27 && _this.isInVRMode) {
  98118. _this.exitVR();
  98119. }
  98120. };
  98121. document.addEventListener("keydown", this._onKeyDown);
  98122. // Exiting VR mode double tapping the touch screen
  98123. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  98124. if (_this.isInVRMode) {
  98125. _this.exitVR();
  98126. if (_this._fullscreenVRpresenting) {
  98127. _this._scene.getEngine().switchFullscreen(true);
  98128. }
  98129. }
  98130. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  98131. // Listen for WebVR display changes
  98132. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  98133. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  98134. this._onVRRequestPresentStart = function () {
  98135. _this._webVRrequesting = true;
  98136. _this.updateButtonVisibility();
  98137. };
  98138. this._onVRRequestPresentComplete = function (success) {
  98139. _this._webVRrequesting = false;
  98140. _this.updateButtonVisibility();
  98141. };
  98142. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  98143. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  98144. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  98145. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  98146. scene.onDisposeObservable.add(function () {
  98147. _this.dispose();
  98148. });
  98149. // Gamepad connection events
  98150. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  98151. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  98152. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  98153. this.updateButtonVisibility();
  98154. //create easing functions
  98155. this._circleEase = new BABYLON.CircleEase();
  98156. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  98157. if (this.webVROptions.floorMeshes) {
  98158. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  98159. }
  98160. }
  98161. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  98162. /** Return this.onEnteringVRObservable
  98163. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  98164. */
  98165. get: function () {
  98166. return this.onEnteringVRObservable;
  98167. },
  98168. enumerable: true,
  98169. configurable: true
  98170. });
  98171. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  98172. /** Return this.onExitingVRObservable
  98173. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  98174. */
  98175. get: function () {
  98176. return this.onExitingVRObservable;
  98177. },
  98178. enumerable: true,
  98179. configurable: true
  98180. });
  98181. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  98182. /** Return this.onControllerMeshLoadedObservable
  98183. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  98184. */
  98185. get: function () {
  98186. return this.onControllerMeshLoadedObservable;
  98187. },
  98188. enumerable: true,
  98189. configurable: true
  98190. });
  98191. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  98192. /**
  98193. * The mesh used to display where the user is going to teleport.
  98194. */
  98195. get: function () {
  98196. return this._teleportationTarget;
  98197. },
  98198. /**
  98199. * Sets the mesh to be used to display where the user is going to teleport.
  98200. */
  98201. set: function (value) {
  98202. if (value) {
  98203. value.name = "teleportationTarget";
  98204. this._isDefaultTeleportationTarget = false;
  98205. this._teleportationTarget = value;
  98206. }
  98207. },
  98208. enumerable: true,
  98209. configurable: true
  98210. });
  98211. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  98212. /**
  98213. * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller
  98214. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  98215. * See http://doc.babylonjs.com/resources/baking_transformations
  98216. */
  98217. get: function () {
  98218. return this._cameraGazer._gazeTracker;
  98219. },
  98220. set: function (value) {
  98221. if (value) {
  98222. // Dispose of existing meshes
  98223. if (this._cameraGazer._gazeTracker) {
  98224. this._cameraGazer._gazeTracker.dispose();
  98225. }
  98226. if (this._leftController && this._leftController._gazeTracker) {
  98227. this._leftController._gazeTracker.dispose();
  98228. }
  98229. if (this._rightController && this._rightController._gazeTracker) {
  98230. this._rightController._gazeTracker.dispose();
  98231. }
  98232. // Set and create gaze trackers on head and controllers
  98233. this._cameraGazer._gazeTracker = value;
  98234. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  98235. this._cameraGazer._gazeTracker.isPickable = false;
  98236. this._cameraGazer._gazeTracker.isVisible = false;
  98237. this._cameraGazer._gazeTracker.name = "gazeTracker";
  98238. if (this._leftController) {
  98239. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  98240. }
  98241. if (this._rightController) {
  98242. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  98243. }
  98244. }
  98245. },
  98246. enumerable: true,
  98247. configurable: true
  98248. });
  98249. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  98250. /**
  98251. * The gaze tracking mesh corresponding to the left controller
  98252. */
  98253. get: function () {
  98254. if (this._leftController) {
  98255. return this._leftController._gazeTracker;
  98256. }
  98257. return null;
  98258. },
  98259. enumerable: true,
  98260. configurable: true
  98261. });
  98262. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  98263. /**
  98264. * The gaze tracking mesh corresponding to the right controller
  98265. */
  98266. get: function () {
  98267. if (this._rightController) {
  98268. return this._rightController._gazeTracker;
  98269. }
  98270. return null;
  98271. },
  98272. enumerable: true,
  98273. configurable: true
  98274. });
  98275. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  98276. /**
  98277. * If the ray of the gaze should be displayed.
  98278. */
  98279. get: function () {
  98280. return this._displayGaze;
  98281. },
  98282. /**
  98283. * Sets if the ray of the gaze should be displayed.
  98284. */
  98285. set: function (value) {
  98286. this._displayGaze = value;
  98287. if (!value) {
  98288. this._cameraGazer._gazeTracker.isVisible = false;
  98289. if (this._leftController) {
  98290. this._leftController._gazeTracker.isVisible = false;
  98291. }
  98292. if (this._rightController) {
  98293. this._rightController._gazeTracker.isVisible = false;
  98294. }
  98295. }
  98296. },
  98297. enumerable: true,
  98298. configurable: true
  98299. });
  98300. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  98301. /**
  98302. * If the ray of the LaserPointer should be displayed.
  98303. */
  98304. get: function () {
  98305. return this._displayLaserPointer;
  98306. },
  98307. /**
  98308. * Sets if the ray of the LaserPointer should be displayed.
  98309. */
  98310. set: function (value) {
  98311. this._displayLaserPointer = value;
  98312. if (!value) {
  98313. if (this._rightController) {
  98314. this._rightController._deactivatePointer();
  98315. this._rightController._gazeTracker.isVisible = false;
  98316. }
  98317. if (this._leftController) {
  98318. this._leftController._deactivatePointer();
  98319. this._leftController._gazeTracker.isVisible = false;
  98320. }
  98321. }
  98322. else {
  98323. if (this._rightController) {
  98324. this._rightController._activatePointer();
  98325. }
  98326. if (this._leftController) {
  98327. this._leftController._activatePointer();
  98328. }
  98329. }
  98330. },
  98331. enumerable: true,
  98332. configurable: true
  98333. });
  98334. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  98335. /**
  98336. * The deviceOrientationCamera used as the camera when not in VR.
  98337. */
  98338. get: function () {
  98339. return this._deviceOrientationCamera;
  98340. },
  98341. enumerable: true,
  98342. configurable: true
  98343. });
  98344. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  98345. /**
  98346. * Based on the current WebVR support, returns the current VR camera used.
  98347. */
  98348. get: function () {
  98349. if (this._webVRready) {
  98350. return this._webVRCamera;
  98351. }
  98352. else {
  98353. return this._scene.activeCamera;
  98354. }
  98355. },
  98356. enumerable: true,
  98357. configurable: true
  98358. });
  98359. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  98360. /**
  98361. * The webVRCamera which is used when in VR.
  98362. */
  98363. get: function () {
  98364. return this._webVRCamera;
  98365. },
  98366. enumerable: true,
  98367. configurable: true
  98368. });
  98369. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  98370. /**
  98371. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  98372. */
  98373. get: function () {
  98374. return this._vrDeviceOrientationCamera;
  98375. },
  98376. enumerable: true,
  98377. configurable: true
  98378. });
  98379. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  98380. get: function () {
  98381. var result = this._cameraGazer._teleportationRequestInitiated
  98382. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  98383. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  98384. return result;
  98385. },
  98386. enumerable: true,
  98387. configurable: true
  98388. });
  98389. // Raised when one of the controller has loaded successfully its associated default mesh
  98390. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  98391. if (this._leftController && this._leftController.webVRController == webVRController) {
  98392. if (webVRController.mesh) {
  98393. this._leftController._setLaserPointerParent(webVRController.mesh);
  98394. }
  98395. }
  98396. if (this._rightController && this._rightController.webVRController == webVRController) {
  98397. if (webVRController.mesh) {
  98398. this._rightController._setLaserPointerParent(webVRController.mesh);
  98399. }
  98400. }
  98401. try {
  98402. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  98403. }
  98404. catch (err) {
  98405. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  98406. }
  98407. };
  98408. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  98409. /**
  98410. * Gets a value indicating if we are currently in VR mode.
  98411. */
  98412. get: function () {
  98413. return this._webVRpresenting || this._fullscreenVRpresenting;
  98414. },
  98415. enumerable: true,
  98416. configurable: true
  98417. });
  98418. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  98419. var vrDisplay = this._scene.getEngine().getVRDevice();
  98420. if (vrDisplay) {
  98421. var wasPresenting = this._webVRpresenting;
  98422. this._webVRpresenting = vrDisplay.isPresenting;
  98423. if (wasPresenting && !this._webVRpresenting)
  98424. this.exitVR();
  98425. }
  98426. else {
  98427. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  98428. }
  98429. this.updateButtonVisibility();
  98430. };
  98431. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  98432. this._webVRsupported = eventArgs.vrSupported;
  98433. this._webVRready = !!eventArgs.vrDisplay;
  98434. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  98435. this.updateButtonVisibility();
  98436. };
  98437. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  98438. if (this._canvas && !this._useCustomVRButton) {
  98439. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  98440. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  98441. }
  98442. };
  98443. VRExperienceHelper.prototype.displayVRButton = function () {
  98444. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  98445. document.body.appendChild(this._btnVR);
  98446. this._btnVRDisplayed = true;
  98447. }
  98448. };
  98449. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  98450. if (!this._btnVR || this._useCustomVRButton) {
  98451. return;
  98452. }
  98453. this._btnVR.className = "babylonVRicon";
  98454. if (this.isInVRMode) {
  98455. this._btnVR.className += " vrdisplaypresenting";
  98456. }
  98457. else {
  98458. if (this._webVRready)
  98459. this._btnVR.className += " vrdisplayready";
  98460. if (this._webVRsupported)
  98461. this._btnVR.className += " vrdisplaysupported";
  98462. if (this._webVRrequesting)
  98463. this._btnVR.className += " vrdisplayrequesting";
  98464. }
  98465. };
  98466. /**
  98467. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  98468. * Otherwise, will use the fullscreen API.
  98469. */
  98470. VRExperienceHelper.prototype.enterVR = function () {
  98471. if (this.onEnteringVRObservable) {
  98472. try {
  98473. this.onEnteringVRObservable.notifyObservers(this);
  98474. }
  98475. catch (err) {
  98476. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  98477. }
  98478. }
  98479. if (this._scene.activeCamera) {
  98480. this._position = this._scene.activeCamera.position.clone();
  98481. // make sure that we return to the last active camera
  98482. this._existingCamera = this._scene.activeCamera;
  98483. }
  98484. if (this._webVRrequesting)
  98485. return;
  98486. // If WebVR is supported and a headset is connected
  98487. if (this._webVRready) {
  98488. if (!this._webVRpresenting) {
  98489. this._webVRCamera.position = this._position;
  98490. this._scene.activeCamera = this._webVRCamera;
  98491. }
  98492. }
  98493. else if (this._vrDeviceOrientationCamera) {
  98494. this._vrDeviceOrientationCamera.position = this._position;
  98495. if (this._scene.activeCamera) {
  98496. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  98497. }
  98498. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  98499. this._scene.getEngine().switchFullscreen(true);
  98500. this.updateButtonVisibility();
  98501. }
  98502. if (this._scene.activeCamera && this._canvas) {
  98503. this._scene.activeCamera.attachControl(this._canvas);
  98504. }
  98505. if (this._interactionsEnabled) {
  98506. this._scene.registerBeforeRender(this.beforeRender);
  98507. }
  98508. this._hasEnteredVR = true;
  98509. };
  98510. /**
  98511. * Attempt to exit VR, or fullscreen.
  98512. */
  98513. VRExperienceHelper.prototype.exitVR = function () {
  98514. if (this._hasEnteredVR) {
  98515. if (this.onExitingVRObservable) {
  98516. try {
  98517. this.onExitingVRObservable.notifyObservers(this);
  98518. }
  98519. catch (err) {
  98520. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  98521. }
  98522. }
  98523. if (this._webVRpresenting) {
  98524. this._scene.getEngine().disableVR();
  98525. }
  98526. if (this._scene.activeCamera) {
  98527. this._position = this._scene.activeCamera.position.clone();
  98528. }
  98529. if (this._deviceOrientationCamera) {
  98530. this._deviceOrientationCamera.position = this._position;
  98531. this._scene.activeCamera = this._deviceOrientationCamera;
  98532. if (this._canvas) {
  98533. this._scene.activeCamera.attachControl(this._canvas);
  98534. }
  98535. }
  98536. else if (this._existingCamera) {
  98537. this._existingCamera.position = this._position;
  98538. this._scene.activeCamera = this._existingCamera;
  98539. }
  98540. this.updateButtonVisibility();
  98541. if (this._interactionsEnabled) {
  98542. this._scene.unregisterBeforeRender(this.beforeRender);
  98543. this._cameraGazer._gazeTracker.isVisible = false;
  98544. if (this._leftController) {
  98545. this._leftController._gazeTracker.isVisible = false;
  98546. }
  98547. if (this._rightController) {
  98548. this._rightController._gazeTracker.isVisible = false;
  98549. }
  98550. }
  98551. // resize to update width and height when exiting vr exits fullscreen
  98552. this._scene.getEngine().resize();
  98553. this._hasEnteredVR = false;
  98554. }
  98555. };
  98556. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  98557. /**
  98558. * The position of the vr experience helper.
  98559. */
  98560. get: function () {
  98561. return this._position;
  98562. },
  98563. /**
  98564. * Sets the position of the vr experience helper.
  98565. */
  98566. set: function (value) {
  98567. this._position = value;
  98568. if (this._scene.activeCamera) {
  98569. this._scene.activeCamera.position = value;
  98570. }
  98571. },
  98572. enumerable: true,
  98573. configurable: true
  98574. });
  98575. /**
  98576. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  98577. */
  98578. VRExperienceHelper.prototype.enableInteractions = function () {
  98579. var _this = this;
  98580. if (!this._interactionsEnabled) {
  98581. this._interactionsRequested = true;
  98582. if (this._leftController) {
  98583. this._enableInteractionOnController(this._leftController);
  98584. }
  98585. if (this._rightController) {
  98586. this._enableInteractionOnController(this._rightController);
  98587. }
  98588. this.raySelectionPredicate = function (mesh) {
  98589. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  98590. };
  98591. this.meshSelectionPredicate = function (mesh) {
  98592. return true;
  98593. };
  98594. this._raySelectionPredicate = function (mesh) {
  98595. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  98596. && mesh.name.indexOf("teleportationTarget") === -1
  98597. && mesh.name.indexOf("torusTeleportation") === -1)) {
  98598. return _this.raySelectionPredicate(mesh);
  98599. }
  98600. return false;
  98601. };
  98602. this._interactionsEnabled = true;
  98603. }
  98604. };
  98605. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  98606. get: function () {
  98607. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  98608. },
  98609. enumerable: true,
  98610. configurable: true
  98611. });
  98612. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  98613. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  98614. if (this._floorMeshesCollection[i].id === mesh.id) {
  98615. return true;
  98616. }
  98617. }
  98618. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  98619. return true;
  98620. }
  98621. return false;
  98622. };
  98623. /**
  98624. * Adds a floor mesh to be used for teleportation.
  98625. * @param floorMesh the mesh to be used for teleportation.
  98626. */
  98627. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  98628. if (!this._floorMeshesCollection) {
  98629. return;
  98630. }
  98631. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  98632. return;
  98633. }
  98634. this._floorMeshesCollection.push(floorMesh);
  98635. };
  98636. /**
  98637. * Removes a floor mesh from being used for teleportation.
  98638. * @param floorMesh the mesh to be removed.
  98639. */
  98640. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  98641. if (!this._floorMeshesCollection) {
  98642. return;
  98643. }
  98644. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  98645. if (meshIndex !== -1) {
  98646. this._floorMeshesCollection.splice(meshIndex, 1);
  98647. }
  98648. };
  98649. /**
  98650. * Enables interactions and teleportation using the VR controllers and gaze.
  98651. * @param vrTeleportationOptions options to modify teleportation behavior.
  98652. */
  98653. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  98654. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  98655. if (!this._teleportationInitialized) {
  98656. this._teleportationRequested = true;
  98657. this.enableInteractions();
  98658. if (vrTeleportationOptions.floorMeshName) {
  98659. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  98660. }
  98661. if (vrTeleportationOptions.floorMeshes) {
  98662. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  98663. }
  98664. if (this._leftController != null) {
  98665. this._enableTeleportationOnController(this._leftController);
  98666. }
  98667. if (this._rightController != null) {
  98668. this._enableTeleportationOnController(this._rightController);
  98669. }
  98670. // Creates an image processing post process for the vignette not relying
  98671. // on the main scene configuration for image processing to reduce setup and spaces
  98672. // (gamma/linear) conflicts.
  98673. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  98674. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  98675. imageProcessingConfiguration.vignetteEnabled = true;
  98676. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  98677. this._webVRCamera.detachPostProcess(this._postProcessMove);
  98678. this._teleportationInitialized = true;
  98679. if (this._isDefaultTeleportationTarget) {
  98680. this._createTeleportationCircles();
  98681. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  98682. }
  98683. }
  98684. };
  98685. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  98686. var _this = this;
  98687. var controllerMesh = controller.webVRController.mesh;
  98688. if (controllerMesh) {
  98689. controller._interactionsEnabled = true;
  98690. controller._activatePointer();
  98691. if (this.webVROptions.laserToggle) {
  98692. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  98693. // Enabling / disabling laserPointer
  98694. if (_this._displayLaserPointer && stateObject.value === 1) {
  98695. if (controller._activePointer) {
  98696. controller._deactivatePointer();
  98697. }
  98698. else {
  98699. controller._activatePointer();
  98700. }
  98701. if (_this.displayGaze) {
  98702. controller._gazeTracker.isVisible = controller._activePointer;
  98703. }
  98704. }
  98705. });
  98706. }
  98707. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  98708. var gazer = controller;
  98709. if (_this._noControllerIsActive) {
  98710. gazer = _this._cameraGazer;
  98711. }
  98712. if (!gazer._pointerDownOnMeshAsked) {
  98713. if (stateObject.value > _this._padSensibilityUp) {
  98714. gazer._selectionPointerDown();
  98715. }
  98716. }
  98717. else if (stateObject.value < _this._padSensibilityDown) {
  98718. gazer._selectionPointerUp();
  98719. }
  98720. });
  98721. }
  98722. };
  98723. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  98724. // Dont teleport if another gaze already requested teleportation
  98725. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  98726. return;
  98727. }
  98728. if (!gazer._teleportationRequestInitiated) {
  98729. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  98730. gazer._activatePointer();
  98731. gazer._teleportationRequestInitiated = true;
  98732. }
  98733. }
  98734. else {
  98735. // Listening to the proper controller values changes to confirm teleportation
  98736. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  98737. if (this._teleportActive) {
  98738. this.teleportCamera(this._haloCenter);
  98739. }
  98740. gazer._teleportationRequestInitiated = false;
  98741. }
  98742. }
  98743. };
  98744. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  98745. // Only rotate when user is not currently selecting a teleportation location
  98746. if (gazer._teleportationRequestInitiated) {
  98747. return;
  98748. }
  98749. if (!gazer._rotationLeftAsked) {
  98750. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  98751. gazer._rotationLeftAsked = true;
  98752. if (this._rotationAllowed) {
  98753. this._rotateCamera(false);
  98754. }
  98755. }
  98756. }
  98757. else {
  98758. if (stateObject.x > -this._padSensibilityDown) {
  98759. gazer._rotationLeftAsked = false;
  98760. }
  98761. }
  98762. if (!gazer._rotationRightAsked) {
  98763. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  98764. gazer._rotationRightAsked = true;
  98765. if (this._rotationAllowed) {
  98766. this._rotateCamera(true);
  98767. }
  98768. }
  98769. }
  98770. else {
  98771. if (stateObject.x < this._padSensibilityDown) {
  98772. gazer._rotationRightAsked = false;
  98773. }
  98774. }
  98775. };
  98776. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  98777. // Only teleport backwards when user is not currently selecting a teleportation location
  98778. if (gazer._teleportationRequestInitiated) {
  98779. return;
  98780. }
  98781. // Teleport backwards
  98782. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  98783. if (!gazer._teleportationBackRequestInitiated) {
  98784. if (!this.currentVRCamera) {
  98785. return;
  98786. }
  98787. // Get rotation and position of the current camera
  98788. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  98789. var position = this.currentVRCamera.position;
  98790. // If the camera has device position, use that instead
  98791. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  98792. rotation = this.currentVRCamera.deviceRotationQuaternion;
  98793. position = this.currentVRCamera.devicePosition;
  98794. }
  98795. // Get matrix with only the y rotation of the device rotation
  98796. rotation.toEulerAnglesToRef(this._workingVector);
  98797. this._workingVector.z = 0;
  98798. this._workingVector.x = 0;
  98799. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  98800. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  98801. // Rotate backwards ray by device rotation to cast at the ground behind the user
  98802. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  98803. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  98804. var ray = new BABYLON.Ray(position, this._workingVector);
  98805. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  98806. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  98807. this.teleportCamera(hit.pickedPoint);
  98808. }
  98809. gazer._teleportationBackRequestInitiated = true;
  98810. }
  98811. }
  98812. else {
  98813. gazer._teleportationBackRequestInitiated = false;
  98814. }
  98815. };
  98816. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  98817. var _this = this;
  98818. var controllerMesh = controller.webVRController.mesh;
  98819. if (controllerMesh) {
  98820. if (!controller._interactionsEnabled) {
  98821. this._enableInteractionOnController(controller);
  98822. }
  98823. controller._interactionsEnabled = true;
  98824. controller._teleportationEnabled = true;
  98825. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  98826. controller._dpadPressed = false;
  98827. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  98828. controller._dpadPressed = stateObject.pressed;
  98829. if (!controller._dpadPressed) {
  98830. controller._rotationLeftAsked = false;
  98831. controller._rotationRightAsked = false;
  98832. controller._teleportationBackRequestInitiated = false;
  98833. }
  98834. });
  98835. }
  98836. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  98837. if (_this.teleportationEnabled) {
  98838. _this._checkTeleportBackwards(stateObject, controller);
  98839. _this._checkTeleportWithRay(stateObject, controller);
  98840. }
  98841. _this._checkRotate(stateObject, controller);
  98842. });
  98843. }
  98844. };
  98845. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  98846. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  98847. this._teleportationTarget.isPickable = false;
  98848. var length = 512;
  98849. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  98850. dynamicTexture.hasAlpha = true;
  98851. var context = dynamicTexture.getContext();
  98852. var centerX = length / 2;
  98853. var centerY = length / 2;
  98854. var radius = 200;
  98855. context.beginPath();
  98856. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  98857. context.fillStyle = this._teleportationFillColor;
  98858. context.fill();
  98859. context.lineWidth = 10;
  98860. context.strokeStyle = this._teleportationBorderColor;
  98861. context.stroke();
  98862. context.closePath();
  98863. dynamicTexture.update();
  98864. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  98865. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  98866. this._teleportationTarget.material = teleportationCircleMaterial;
  98867. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  98868. torus.isPickable = false;
  98869. torus.parent = this._teleportationTarget;
  98870. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  98871. var keys = [];
  98872. keys.push({
  98873. frame: 0,
  98874. value: 0
  98875. });
  98876. keys.push({
  98877. frame: 30,
  98878. value: 0.4
  98879. });
  98880. keys.push({
  98881. frame: 60,
  98882. value: 0
  98883. });
  98884. animationInnerCircle.setKeys(keys);
  98885. var easingFunction = new BABYLON.SineEase();
  98886. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  98887. animationInnerCircle.setEasingFunction(easingFunction);
  98888. torus.animations = [];
  98889. torus.animations.push(animationInnerCircle);
  98890. this._scene.beginAnimation(torus, 0, 60, true);
  98891. this._hideTeleportationTarget();
  98892. };
  98893. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  98894. this._teleportActive = true;
  98895. if (this._teleportationInitialized) {
  98896. this._teleportationTarget.isVisible = true;
  98897. if (this._isDefaultTeleportationTarget) {
  98898. this._teleportationTarget.getChildren()[0].isVisible = true;
  98899. }
  98900. }
  98901. };
  98902. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  98903. this._teleportActive = false;
  98904. if (this._teleportationInitialized) {
  98905. this._teleportationTarget.isVisible = false;
  98906. if (this._isDefaultTeleportationTarget) {
  98907. this._teleportationTarget.getChildren()[0].isVisible = false;
  98908. }
  98909. }
  98910. };
  98911. VRExperienceHelper.prototype._rotateCamera = function (right) {
  98912. var _this = this;
  98913. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  98914. return;
  98915. }
  98916. if (right) {
  98917. this._rotationAngle++;
  98918. }
  98919. else {
  98920. this._rotationAngle--;
  98921. }
  98922. this.currentVRCamera.animations = [];
  98923. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  98924. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98925. var animationRotationKeys = [];
  98926. animationRotationKeys.push({
  98927. frame: 0,
  98928. value: this.currentVRCamera.rotationQuaternion
  98929. });
  98930. animationRotationKeys.push({
  98931. frame: 6,
  98932. value: target
  98933. });
  98934. animationRotation.setKeys(animationRotationKeys);
  98935. animationRotation.setEasingFunction(this._circleEase);
  98936. this.currentVRCamera.animations.push(animationRotation);
  98937. this._postProcessMove.animations = [];
  98938. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98939. var vignetteWeightKeys = [];
  98940. vignetteWeightKeys.push({
  98941. frame: 0,
  98942. value: 0
  98943. });
  98944. vignetteWeightKeys.push({
  98945. frame: 3,
  98946. value: 4
  98947. });
  98948. vignetteWeightKeys.push({
  98949. frame: 6,
  98950. value: 0
  98951. });
  98952. animationPP.setKeys(vignetteWeightKeys);
  98953. animationPP.setEasingFunction(this._circleEase);
  98954. this._postProcessMove.animations.push(animationPP);
  98955. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98956. var vignetteStretchKeys = [];
  98957. vignetteStretchKeys.push({
  98958. frame: 0,
  98959. value: 0
  98960. });
  98961. vignetteStretchKeys.push({
  98962. frame: 3,
  98963. value: 10
  98964. });
  98965. vignetteStretchKeys.push({
  98966. frame: 6,
  98967. value: 0
  98968. });
  98969. animationPP2.setKeys(vignetteStretchKeys);
  98970. animationPP2.setEasingFunction(this._circleEase);
  98971. this._postProcessMove.animations.push(animationPP2);
  98972. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  98973. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  98974. this._postProcessMove.samples = 4;
  98975. this._webVRCamera.attachPostProcess(this._postProcessMove);
  98976. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  98977. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  98978. });
  98979. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  98980. };
  98981. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  98982. if (hit.pickedPoint) {
  98983. if (gazer._teleportationRequestInitiated) {
  98984. this._displayTeleportationTarget();
  98985. this._haloCenter.copyFrom(hit.pickedPoint);
  98986. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  98987. }
  98988. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  98989. if (pickNormal) {
  98990. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  98991. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  98992. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  98993. }
  98994. this._teleportationTarget.position.y += 0.1;
  98995. }
  98996. };
  98997. /**
  98998. * Teleports the users feet to the desired location
  98999. * @param location The location where the user's feet should be placed
  99000. */
  99001. VRExperienceHelper.prototype.teleportCamera = function (location) {
  99002. var _this = this;
  99003. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  99004. return;
  99005. }
  99006. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  99007. // offset of the headset from the anchor.
  99008. if (this.webVRCamera.leftCamera) {
  99009. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  99010. this._workingVector.subtractInPlace(this.webVRCamera.position);
  99011. location.subtractToRef(this._workingVector, this._workingVector);
  99012. }
  99013. else {
  99014. this._workingVector.copyFrom(location);
  99015. }
  99016. // Add height to account for user's height offset
  99017. if (this.isInVRMode) {
  99018. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  99019. }
  99020. else {
  99021. this._workingVector.y += this._defaultHeight;
  99022. }
  99023. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  99024. // Create animation from the camera's position to the new location
  99025. this.currentVRCamera.animations = [];
  99026. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99027. var animationCameraTeleportationKeys = [{
  99028. frame: 0,
  99029. value: this.currentVRCamera.position
  99030. },
  99031. {
  99032. frame: 11,
  99033. value: this._workingVector
  99034. }
  99035. ];
  99036. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  99037. animationCameraTeleportation.setEasingFunction(this._circleEase);
  99038. this.currentVRCamera.animations.push(animationCameraTeleportation);
  99039. this._postProcessMove.animations = [];
  99040. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99041. var vignetteWeightKeys = [];
  99042. vignetteWeightKeys.push({
  99043. frame: 0,
  99044. value: 0
  99045. });
  99046. vignetteWeightKeys.push({
  99047. frame: 5,
  99048. value: 8
  99049. });
  99050. vignetteWeightKeys.push({
  99051. frame: 11,
  99052. value: 0
  99053. });
  99054. animationPP.setKeys(vignetteWeightKeys);
  99055. this._postProcessMove.animations.push(animationPP);
  99056. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99057. var vignetteStretchKeys = [];
  99058. vignetteStretchKeys.push({
  99059. frame: 0,
  99060. value: 0
  99061. });
  99062. vignetteStretchKeys.push({
  99063. frame: 5,
  99064. value: 10
  99065. });
  99066. vignetteStretchKeys.push({
  99067. frame: 11,
  99068. value: 0
  99069. });
  99070. animationPP2.setKeys(vignetteStretchKeys);
  99071. this._postProcessMove.animations.push(animationPP2);
  99072. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  99073. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  99074. this._webVRCamera.attachPostProcess(this._postProcessMove);
  99075. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  99076. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  99077. });
  99078. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  99079. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  99080. });
  99081. this._hideTeleportationTarget();
  99082. };
  99083. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  99084. if (normal) {
  99085. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  99086. if (angle < Math.PI / 2) {
  99087. normal.scaleInPlace(-1);
  99088. }
  99089. }
  99090. return normal;
  99091. };
  99092. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  99093. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  99094. return;
  99095. }
  99096. var ray = gazer._getForwardRay(this._rayLength);
  99097. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  99098. if (hit) {
  99099. // Populate the contrllers mesh that can be used for drag/drop
  99100. if (gazer._laserPointer) {
  99101. hit.originMesh = gazer._laserPointer.parent;
  99102. }
  99103. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  99104. }
  99105. gazer._currentHit = hit;
  99106. // Moving the gazeTracker on the mesh face targetted
  99107. if (hit && hit.pickedPoint) {
  99108. if (this._displayGaze) {
  99109. var multiplier = 1;
  99110. gazer._gazeTracker.isVisible = true;
  99111. if (gazer._isActionableMesh) {
  99112. multiplier = 3;
  99113. }
  99114. if (this.updateGazeTrackerScale) {
  99115. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  99116. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  99117. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  99118. }
  99119. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  99120. // To avoid z-fighting
  99121. var deltaFighting = 0.002;
  99122. if (pickNormal) {
  99123. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  99124. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  99125. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  99126. }
  99127. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  99128. if (gazer._gazeTracker.position.x < 0) {
  99129. gazer._gazeTracker.position.x += deltaFighting;
  99130. }
  99131. else {
  99132. gazer._gazeTracker.position.x -= deltaFighting;
  99133. }
  99134. if (gazer._gazeTracker.position.y < 0) {
  99135. gazer._gazeTracker.position.y += deltaFighting;
  99136. }
  99137. else {
  99138. gazer._gazeTracker.position.y -= deltaFighting;
  99139. }
  99140. if (gazer._gazeTracker.position.z < 0) {
  99141. gazer._gazeTracker.position.z += deltaFighting;
  99142. }
  99143. else {
  99144. gazer._gazeTracker.position.z -= deltaFighting;
  99145. }
  99146. }
  99147. // Changing the size of the laser pointer based on the distance from the targetted point
  99148. gazer._updatePointerDistance(hit.distance);
  99149. }
  99150. else {
  99151. gazer._updatePointerDistance();
  99152. gazer._gazeTracker.isVisible = false;
  99153. }
  99154. if (hit && hit.pickedMesh) {
  99155. // The object selected is the floor, we're in a teleportation scenario
  99156. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  99157. // Moving the teleportation area to this targetted point
  99158. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  99159. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  99160. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  99161. }
  99162. gazer._currentMeshSelected = null;
  99163. if (gazer._teleportationRequestInitiated) {
  99164. this._moveTeleportationSelectorTo(hit, gazer, ray);
  99165. }
  99166. return;
  99167. }
  99168. // If not, we're in a selection scenario
  99169. //this._teleportationAllowed = false;
  99170. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  99171. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  99172. this.onNewMeshPicked.notifyObservers(hit);
  99173. gazer._currentMeshSelected = hit.pickedMesh;
  99174. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  99175. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  99176. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  99177. gazer._isActionableMesh = true;
  99178. }
  99179. else {
  99180. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99181. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99182. gazer._isActionableMesh = false;
  99183. }
  99184. try {
  99185. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  99186. }
  99187. catch (err) {
  99188. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  99189. }
  99190. }
  99191. else {
  99192. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  99193. gazer._currentMeshSelected = null;
  99194. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99195. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99196. }
  99197. }
  99198. }
  99199. else {
  99200. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  99201. gazer._currentMeshSelected = null;
  99202. //this._teleportationAllowed = false;
  99203. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99204. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99205. }
  99206. };
  99207. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  99208. if (mesh) {
  99209. this.onSelectedMeshUnselected.notifyObservers(mesh);
  99210. }
  99211. };
  99212. /**
  99213. * Sets the color of the laser ray from the vr controllers.
  99214. * @param color new color for the ray.
  99215. */
  99216. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  99217. if (this._leftController) {
  99218. this._leftController._setLaserPointerColor(color);
  99219. }
  99220. if (this._rightController) {
  99221. this._rightController._setLaserPointerColor(color);
  99222. }
  99223. };
  99224. /**
  99225. * Sets the color of the ray from the vr headsets gaze.
  99226. * @param color new color for the ray.
  99227. */
  99228. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  99229. if (!this._cameraGazer._gazeTracker.material) {
  99230. return;
  99231. }
  99232. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  99233. if (this._leftController) {
  99234. this._leftController._gazeTracker.material.emissiveColor = color;
  99235. }
  99236. if (this._rightController) {
  99237. this._rightController._gazeTracker.material.emissiveColor = color;
  99238. }
  99239. };
  99240. /**
  99241. * Exits VR and disposes of the vr experience helper
  99242. */
  99243. VRExperienceHelper.prototype.dispose = function () {
  99244. if (this.isInVRMode) {
  99245. this.exitVR();
  99246. }
  99247. if (this._postProcessMove) {
  99248. this._postProcessMove.dispose();
  99249. }
  99250. if (this._webVRCamera) {
  99251. this._webVRCamera.dispose();
  99252. }
  99253. if (this._vrDeviceOrientationCamera) {
  99254. this._vrDeviceOrientationCamera.dispose();
  99255. }
  99256. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  99257. document.body.removeChild(this._btnVR);
  99258. }
  99259. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  99260. this._deviceOrientationCamera.dispose();
  99261. }
  99262. if (this._cameraGazer) {
  99263. this._cameraGazer.dispose();
  99264. }
  99265. if (this._leftController) {
  99266. this._leftController.dispose();
  99267. }
  99268. if (this._rightController) {
  99269. this._rightController.dispose();
  99270. }
  99271. if (this._teleportationTarget) {
  99272. this._teleportationTarget.dispose();
  99273. }
  99274. this._floorMeshesCollection = [];
  99275. document.removeEventListener("keydown", this._onKeyDown);
  99276. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  99277. window.removeEventListener("resize", this._onResize);
  99278. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  99279. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  99280. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  99281. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  99282. document.onmsfullscreenchange = null;
  99283. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  99284. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  99285. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  99286. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  99287. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  99288. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  99289. this._scene.unregisterBeforeRender(this.beforeRender);
  99290. };
  99291. /**
  99292. * Gets the name of the VRExperienceHelper class
  99293. * @returns "VRExperienceHelper"
  99294. */
  99295. VRExperienceHelper.prototype.getClassName = function () {
  99296. return "VRExperienceHelper";
  99297. };
  99298. return VRExperienceHelper;
  99299. }());
  99300. BABYLON.VRExperienceHelper = VRExperienceHelper;
  99301. })(BABYLON || (BABYLON = {}));
  99302. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  99303. // Mainly based on these 2 articles :
  99304. // 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
  99305. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  99306. var BABYLON;
  99307. (function (BABYLON) {
  99308. /**
  99309. * Defines the potential axis of a Joystick
  99310. */
  99311. var JoystickAxis;
  99312. (function (JoystickAxis) {
  99313. /** X axis */
  99314. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  99315. /** Y axis */
  99316. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  99317. /** Z axis */
  99318. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  99319. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  99320. /**
  99321. * Class used to define virtual joystick (used in touch mode)
  99322. */
  99323. var VirtualJoystick = /** @class */ (function () {
  99324. /**
  99325. * Creates a new virtual joystick
  99326. * @param leftJoystick defines that the joystick is for left hand (false by default)
  99327. */
  99328. function VirtualJoystick(leftJoystick) {
  99329. var _this = this;
  99330. if (leftJoystick) {
  99331. this._leftJoystick = true;
  99332. }
  99333. else {
  99334. this._leftJoystick = false;
  99335. }
  99336. VirtualJoystick._globalJoystickIndex++;
  99337. // By default left & right arrow keys are moving the X
  99338. // and up & down keys are moving the Y
  99339. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  99340. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  99341. this.reverseLeftRight = false;
  99342. this.reverseUpDown = false;
  99343. // collections of pointers
  99344. this._touches = new BABYLON.StringDictionary();
  99345. this.deltaPosition = BABYLON.Vector3.Zero();
  99346. this._joystickSensibility = 25;
  99347. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  99348. this._onResize = function (evt) {
  99349. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  99350. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  99351. if (VirtualJoystick.vjCanvas) {
  99352. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  99353. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  99354. }
  99355. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  99356. };
  99357. // injecting a canvas element on top of the canvas 3D game
  99358. if (!VirtualJoystick.vjCanvas) {
  99359. window.addEventListener("resize", this._onResize, false);
  99360. VirtualJoystick.vjCanvas = document.createElement("canvas");
  99361. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  99362. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  99363. VirtualJoystick.vjCanvas.width = window.innerWidth;
  99364. VirtualJoystick.vjCanvas.height = window.innerHeight;
  99365. VirtualJoystick.vjCanvas.style.width = "100%";
  99366. VirtualJoystick.vjCanvas.style.height = "100%";
  99367. VirtualJoystick.vjCanvas.style.position = "absolute";
  99368. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  99369. VirtualJoystick.vjCanvas.style.top = "0px";
  99370. VirtualJoystick.vjCanvas.style.left = "0px";
  99371. VirtualJoystick.vjCanvas.style.zIndex = "5";
  99372. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  99373. // Support for jQuery PEP polyfill
  99374. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  99375. var context = VirtualJoystick.vjCanvas.getContext('2d');
  99376. if (!context) {
  99377. throw new Error("Unable to create canvas for virtual joystick");
  99378. }
  99379. VirtualJoystick.vjCanvasContext = context;
  99380. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  99381. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  99382. document.body.appendChild(VirtualJoystick.vjCanvas);
  99383. }
  99384. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  99385. this.pressed = false;
  99386. // default joystick color
  99387. this._joystickColor = "cyan";
  99388. this._joystickPointerID = -1;
  99389. // current joystick position
  99390. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  99391. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  99392. // origin joystick position
  99393. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  99394. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  99395. this._onPointerDownHandlerRef = function (evt) {
  99396. _this._onPointerDown(evt);
  99397. };
  99398. this._onPointerMoveHandlerRef = function (evt) {
  99399. _this._onPointerMove(evt);
  99400. };
  99401. this._onPointerUpHandlerRef = function (evt) {
  99402. _this._onPointerUp(evt);
  99403. };
  99404. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  99405. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  99406. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  99407. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  99408. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  99409. evt.preventDefault(); // Disables system menu
  99410. }, false);
  99411. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  99412. }
  99413. /**
  99414. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  99415. * @param newJoystickSensibility defines the new sensibility
  99416. */
  99417. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  99418. this._joystickSensibility = newJoystickSensibility;
  99419. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  99420. };
  99421. VirtualJoystick.prototype._onPointerDown = function (e) {
  99422. var positionOnScreenCondition;
  99423. e.preventDefault();
  99424. if (this._leftJoystick === true) {
  99425. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  99426. }
  99427. else {
  99428. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  99429. }
  99430. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  99431. // First contact will be dedicated to the virtual joystick
  99432. this._joystickPointerID = e.pointerId;
  99433. this._joystickPointerStartPos.x = e.clientX;
  99434. this._joystickPointerStartPos.y = e.clientY;
  99435. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  99436. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  99437. this._deltaJoystickVector.x = 0;
  99438. this._deltaJoystickVector.y = 0;
  99439. this.pressed = true;
  99440. this._touches.add(e.pointerId.toString(), e);
  99441. }
  99442. else {
  99443. // You can only trigger the action buttons with a joystick declared
  99444. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  99445. this._action();
  99446. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  99447. }
  99448. }
  99449. };
  99450. VirtualJoystick.prototype._onPointerMove = function (e) {
  99451. // If the current pointer is the one associated to the joystick (first touch contact)
  99452. if (this._joystickPointerID == e.pointerId) {
  99453. this._joystickPointerPos.x = e.clientX;
  99454. this._joystickPointerPos.y = e.clientY;
  99455. this._deltaJoystickVector = this._joystickPointerPos.clone();
  99456. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  99457. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  99458. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  99459. switch (this._axisTargetedByLeftAndRight) {
  99460. case JoystickAxis.X:
  99461. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  99462. break;
  99463. case JoystickAxis.Y:
  99464. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  99465. break;
  99466. case JoystickAxis.Z:
  99467. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  99468. break;
  99469. }
  99470. var directionUpDown = this.reverseUpDown ? 1 : -1;
  99471. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  99472. switch (this._axisTargetedByUpAndDown) {
  99473. case JoystickAxis.X:
  99474. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  99475. break;
  99476. case JoystickAxis.Y:
  99477. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  99478. break;
  99479. case JoystickAxis.Z:
  99480. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  99481. break;
  99482. }
  99483. }
  99484. else {
  99485. var data = this._touches.get(e.pointerId.toString());
  99486. if (data) {
  99487. data.x = e.clientX;
  99488. data.y = e.clientY;
  99489. }
  99490. }
  99491. };
  99492. VirtualJoystick.prototype._onPointerUp = function (e) {
  99493. if (this._joystickPointerID == e.pointerId) {
  99494. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  99495. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  99496. this._joystickPointerID = -1;
  99497. this.pressed = false;
  99498. }
  99499. else {
  99500. var touch = this._touches.get(e.pointerId.toString());
  99501. if (touch) {
  99502. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  99503. }
  99504. }
  99505. this._deltaJoystickVector.x = 0;
  99506. this._deltaJoystickVector.y = 0;
  99507. this._touches.remove(e.pointerId.toString());
  99508. };
  99509. /**
  99510. * Change the color of the virtual joystick
  99511. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  99512. */
  99513. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  99514. this._joystickColor = newColor;
  99515. };
  99516. /**
  99517. * Defines a callback to call when the joystick is touched
  99518. * @param action defines the callback
  99519. */
  99520. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  99521. this._action = action;
  99522. };
  99523. /**
  99524. * Defines which axis you'd like to control for left & right
  99525. * @param axis defines the axis to use
  99526. */
  99527. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  99528. switch (axis) {
  99529. case JoystickAxis.X:
  99530. case JoystickAxis.Y:
  99531. case JoystickAxis.Z:
  99532. this._axisTargetedByLeftAndRight = axis;
  99533. break;
  99534. default:
  99535. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  99536. break;
  99537. }
  99538. };
  99539. /**
  99540. * Defines which axis you'd like to control for up & down
  99541. * @param axis defines the axis to use
  99542. */
  99543. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  99544. switch (axis) {
  99545. case JoystickAxis.X:
  99546. case JoystickAxis.Y:
  99547. case JoystickAxis.Z:
  99548. this._axisTargetedByUpAndDown = axis;
  99549. break;
  99550. default:
  99551. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  99552. break;
  99553. }
  99554. };
  99555. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  99556. var _this = this;
  99557. if (this.pressed) {
  99558. this._touches.forEach(function (key, touch) {
  99559. if (touch.pointerId === _this._joystickPointerID) {
  99560. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  99561. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  99562. VirtualJoystick.vjCanvasContext.beginPath();
  99563. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  99564. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99565. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  99566. VirtualJoystick.vjCanvasContext.stroke();
  99567. VirtualJoystick.vjCanvasContext.closePath();
  99568. VirtualJoystick.vjCanvasContext.beginPath();
  99569. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99570. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  99571. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  99572. VirtualJoystick.vjCanvasContext.stroke();
  99573. VirtualJoystick.vjCanvasContext.closePath();
  99574. VirtualJoystick.vjCanvasContext.beginPath();
  99575. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99576. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  99577. VirtualJoystick.vjCanvasContext.stroke();
  99578. VirtualJoystick.vjCanvasContext.closePath();
  99579. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  99580. }
  99581. else {
  99582. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  99583. VirtualJoystick.vjCanvasContext.beginPath();
  99584. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  99585. VirtualJoystick.vjCanvasContext.beginPath();
  99586. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  99587. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  99588. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  99589. VirtualJoystick.vjCanvasContext.stroke();
  99590. VirtualJoystick.vjCanvasContext.closePath();
  99591. touch.prevX = touch.x;
  99592. touch.prevY = touch.y;
  99593. }
  99594. ;
  99595. });
  99596. }
  99597. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  99598. };
  99599. /**
  99600. * Release internal HTML canvas
  99601. */
  99602. VirtualJoystick.prototype.releaseCanvas = function () {
  99603. if (VirtualJoystick.vjCanvas) {
  99604. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  99605. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  99606. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  99607. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  99608. window.removeEventListener("resize", this._onResize);
  99609. document.body.removeChild(VirtualJoystick.vjCanvas);
  99610. VirtualJoystick.vjCanvas = null;
  99611. }
  99612. };
  99613. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  99614. VirtualJoystick._globalJoystickIndex = 0;
  99615. return VirtualJoystick;
  99616. }());
  99617. BABYLON.VirtualJoystick = VirtualJoystick;
  99618. })(BABYLON || (BABYLON = {}));
  99619. //# sourceMappingURL=babylon.virtualJoystick.js.map
  99620. var BABYLON;
  99621. (function (BABYLON) {
  99622. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  99623. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  99624. });
  99625. // We're mainly based on the logic defined into the FreeCamera code
  99626. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  99627. __extends(VirtualJoysticksCamera, _super);
  99628. function VirtualJoysticksCamera(name, position, scene) {
  99629. var _this = _super.call(this, name, position, scene) || this;
  99630. _this.inputs.addVirtualJoystick();
  99631. return _this;
  99632. }
  99633. VirtualJoysticksCamera.prototype.getClassName = function () {
  99634. return "VirtualJoysticksCamera";
  99635. };
  99636. return VirtualJoysticksCamera;
  99637. }(BABYLON.FreeCamera));
  99638. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  99639. })(BABYLON || (BABYLON = {}));
  99640. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  99641. var BABYLON;
  99642. (function (BABYLON) {
  99643. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  99644. function FreeCameraVirtualJoystickInput() {
  99645. }
  99646. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  99647. return this._leftjoystick;
  99648. };
  99649. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  99650. return this._rightjoystick;
  99651. };
  99652. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  99653. if (this._leftjoystick) {
  99654. var camera = this.camera;
  99655. var speed = camera._computeLocalCameraSpeed() * 50;
  99656. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  99657. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  99658. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  99659. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  99660. if (!this._leftjoystick.pressed) {
  99661. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  99662. }
  99663. if (!this._rightjoystick.pressed) {
  99664. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  99665. }
  99666. }
  99667. };
  99668. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  99669. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  99670. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  99671. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  99672. this._leftjoystick.setJoystickSensibility(0.15);
  99673. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  99674. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  99675. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  99676. this._rightjoystick.reverseUpDown = true;
  99677. this._rightjoystick.setJoystickSensibility(0.05);
  99678. this._rightjoystick.setJoystickColor("yellow");
  99679. };
  99680. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  99681. this._leftjoystick.releaseCanvas();
  99682. this._rightjoystick.releaseCanvas();
  99683. };
  99684. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  99685. return "FreeCameraVirtualJoystickInput";
  99686. };
  99687. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  99688. return "virtualJoystick";
  99689. };
  99690. return FreeCameraVirtualJoystickInput;
  99691. }());
  99692. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  99693. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  99694. })(BABYLON || (BABYLON = {}));
  99695. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  99696. var BABYLON;
  99697. (function (BABYLON) {
  99698. var SimplificationSettings = /** @class */ (function () {
  99699. function SimplificationSettings(quality, distance, optimizeMesh) {
  99700. this.quality = quality;
  99701. this.distance = distance;
  99702. this.optimizeMesh = optimizeMesh;
  99703. }
  99704. return SimplificationSettings;
  99705. }());
  99706. BABYLON.SimplificationSettings = SimplificationSettings;
  99707. var SimplificationQueue = /** @class */ (function () {
  99708. function SimplificationQueue() {
  99709. this.running = false;
  99710. this._simplificationArray = [];
  99711. }
  99712. SimplificationQueue.prototype.addTask = function (task) {
  99713. this._simplificationArray.push(task);
  99714. };
  99715. SimplificationQueue.prototype.executeNext = function () {
  99716. var task = this._simplificationArray.pop();
  99717. if (task) {
  99718. this.running = true;
  99719. this.runSimplification(task);
  99720. }
  99721. else {
  99722. this.running = false;
  99723. }
  99724. };
  99725. SimplificationQueue.prototype.runSimplification = function (task) {
  99726. var _this = this;
  99727. if (task.parallelProcessing) {
  99728. //parallel simplifier
  99729. task.settings.forEach(function (setting) {
  99730. var simplifier = _this.getSimplifier(task);
  99731. simplifier.simplify(setting, function (newMesh) {
  99732. task.mesh.addLODLevel(setting.distance, newMesh);
  99733. newMesh.isVisible = true;
  99734. //check if it is the last
  99735. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  99736. //all done, run the success callback.
  99737. task.successCallback();
  99738. }
  99739. _this.executeNext();
  99740. });
  99741. });
  99742. }
  99743. else {
  99744. //single simplifier.
  99745. var simplifier = this.getSimplifier(task);
  99746. var runDecimation = function (setting, callback) {
  99747. simplifier.simplify(setting, function (newMesh) {
  99748. task.mesh.addLODLevel(setting.distance, newMesh);
  99749. newMesh.isVisible = true;
  99750. //run the next quality level
  99751. callback();
  99752. });
  99753. };
  99754. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  99755. runDecimation(task.settings[loop.index], function () {
  99756. loop.executeNext();
  99757. });
  99758. }, function () {
  99759. //execution ended, run the success callback.
  99760. if (task.successCallback) {
  99761. task.successCallback();
  99762. }
  99763. _this.executeNext();
  99764. });
  99765. }
  99766. };
  99767. SimplificationQueue.prototype.getSimplifier = function (task) {
  99768. switch (task.simplificationType) {
  99769. case SimplificationType.QUADRATIC:
  99770. default:
  99771. return new QuadraticErrorSimplification(task.mesh);
  99772. }
  99773. };
  99774. return SimplificationQueue;
  99775. }());
  99776. BABYLON.SimplificationQueue = SimplificationQueue;
  99777. /**
  99778. * The implemented types of simplification
  99779. * At the moment only Quadratic Error Decimation is implemented
  99780. */
  99781. var SimplificationType;
  99782. (function (SimplificationType) {
  99783. /** Quadratic error decimation */
  99784. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  99785. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  99786. var DecimationTriangle = /** @class */ (function () {
  99787. function DecimationTriangle(vertices) {
  99788. this.vertices = vertices;
  99789. this.error = new Array(4);
  99790. this.deleted = false;
  99791. this.isDirty = false;
  99792. this.deletePending = false;
  99793. this.borderFactor = 0;
  99794. }
  99795. return DecimationTriangle;
  99796. }());
  99797. BABYLON.DecimationTriangle = DecimationTriangle;
  99798. var DecimationVertex = /** @class */ (function () {
  99799. function DecimationVertex(position, id) {
  99800. this.position = position;
  99801. this.id = id;
  99802. this.isBorder = true;
  99803. this.q = new QuadraticMatrix();
  99804. this.triangleCount = 0;
  99805. this.triangleStart = 0;
  99806. this.originalOffsets = [];
  99807. }
  99808. DecimationVertex.prototype.updatePosition = function (newPosition) {
  99809. this.position.copyFrom(newPosition);
  99810. };
  99811. return DecimationVertex;
  99812. }());
  99813. BABYLON.DecimationVertex = DecimationVertex;
  99814. var QuadraticMatrix = /** @class */ (function () {
  99815. function QuadraticMatrix(data) {
  99816. this.data = new Array(10);
  99817. for (var i = 0; i < 10; ++i) {
  99818. if (data && data[i]) {
  99819. this.data[i] = data[i];
  99820. }
  99821. else {
  99822. this.data[i] = 0;
  99823. }
  99824. }
  99825. }
  99826. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  99827. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  99828. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  99829. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  99830. return det;
  99831. };
  99832. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  99833. for (var i = 0; i < 10; ++i) {
  99834. this.data[i] += matrix.data[i];
  99835. }
  99836. };
  99837. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  99838. for (var i = 0; i < 10; ++i) {
  99839. this.data[i] += data[i];
  99840. }
  99841. };
  99842. QuadraticMatrix.prototype.add = function (matrix) {
  99843. var m = new QuadraticMatrix();
  99844. for (var i = 0; i < 10; ++i) {
  99845. m.data[i] = this.data[i] + matrix.data[i];
  99846. }
  99847. return m;
  99848. };
  99849. QuadraticMatrix.FromData = function (a, b, c, d) {
  99850. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  99851. };
  99852. //returning an array to avoid garbage collection
  99853. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  99854. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  99855. };
  99856. return QuadraticMatrix;
  99857. }());
  99858. BABYLON.QuadraticMatrix = QuadraticMatrix;
  99859. var Reference = /** @class */ (function () {
  99860. function Reference(vertexId, triangleId) {
  99861. this.vertexId = vertexId;
  99862. this.triangleId = triangleId;
  99863. }
  99864. return Reference;
  99865. }());
  99866. BABYLON.Reference = Reference;
  99867. /**
  99868. * An implementation of the Quadratic Error simplification algorithm.
  99869. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  99870. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  99871. * @author RaananW
  99872. */
  99873. var QuadraticErrorSimplification = /** @class */ (function () {
  99874. function QuadraticErrorSimplification(_mesh) {
  99875. this._mesh = _mesh;
  99876. this.syncIterations = 5000;
  99877. this.aggressiveness = 7;
  99878. this.decimationIterations = 100;
  99879. this.boundingBoxEpsilon = BABYLON.Epsilon;
  99880. }
  99881. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  99882. var _this = this;
  99883. this.initDecimatedMesh();
  99884. //iterating through the submeshes array, one after the other.
  99885. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  99886. _this.initWithMesh(loop.index, function () {
  99887. _this.runDecimation(settings, loop.index, function () {
  99888. loop.executeNext();
  99889. });
  99890. }, settings.optimizeMesh);
  99891. }, function () {
  99892. setTimeout(function () {
  99893. successCallback(_this._reconstructedMesh);
  99894. }, 0);
  99895. });
  99896. };
  99897. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  99898. var _this = this;
  99899. var targetCount = ~~(this.triangles.length * settings.quality);
  99900. var deletedTriangles = 0;
  99901. var triangleCount = this.triangles.length;
  99902. var iterationFunction = function (iteration, callback) {
  99903. setTimeout(function () {
  99904. if (iteration % 5 === 0) {
  99905. _this.updateMesh(iteration === 0);
  99906. }
  99907. for (var i = 0; i < _this.triangles.length; ++i) {
  99908. _this.triangles[i].isDirty = false;
  99909. }
  99910. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  99911. var trianglesIterator = function (i) {
  99912. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  99913. var t = _this.triangles[tIdx];
  99914. if (!t)
  99915. return;
  99916. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  99917. return;
  99918. }
  99919. for (var j = 0; j < 3; ++j) {
  99920. if (t.error[j] < threshold) {
  99921. var deleted0 = [];
  99922. var deleted1 = [];
  99923. var v0 = t.vertices[j];
  99924. var v1 = t.vertices[(j + 1) % 3];
  99925. if (v0.isBorder || v1.isBorder)
  99926. continue;
  99927. var p = BABYLON.Vector3.Zero();
  99928. var n = BABYLON.Vector3.Zero();
  99929. var uv = BABYLON.Vector2.Zero();
  99930. var color = new BABYLON.Color4(0, 0, 0, 1);
  99931. _this.calculateError(v0, v1, p, n, uv, color);
  99932. var delTr = new Array();
  99933. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  99934. continue;
  99935. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  99936. continue;
  99937. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  99938. continue;
  99939. var uniqueArray = new Array();
  99940. delTr.forEach(function (deletedT) {
  99941. if (uniqueArray.indexOf(deletedT) === -1) {
  99942. deletedT.deletePending = true;
  99943. uniqueArray.push(deletedT);
  99944. }
  99945. });
  99946. if (uniqueArray.length % 2 !== 0) {
  99947. continue;
  99948. }
  99949. v0.q = v1.q.add(v0.q);
  99950. v0.updatePosition(p);
  99951. var tStart = _this.references.length;
  99952. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  99953. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  99954. var tCount = _this.references.length - tStart;
  99955. if (tCount <= v0.triangleCount) {
  99956. if (tCount) {
  99957. for (var c = 0; c < tCount; c++) {
  99958. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  99959. }
  99960. }
  99961. }
  99962. else {
  99963. v0.triangleStart = tStart;
  99964. }
  99965. v0.triangleCount = tCount;
  99966. break;
  99967. }
  99968. }
  99969. };
  99970. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  99971. }, 0);
  99972. };
  99973. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  99974. if (triangleCount - deletedTriangles <= targetCount)
  99975. loop.breakLoop();
  99976. else {
  99977. iterationFunction(loop.index, function () {
  99978. loop.executeNext();
  99979. });
  99980. }
  99981. }, function () {
  99982. setTimeout(function () {
  99983. //reconstruct this part of the mesh
  99984. _this.reconstructMesh(submeshIndex);
  99985. successCallback();
  99986. }, 0);
  99987. });
  99988. };
  99989. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  99990. var _this = this;
  99991. this.vertices = [];
  99992. this.triangles = [];
  99993. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  99994. var indices = this._mesh.getIndices();
  99995. var submesh = this._mesh.subMeshes[submeshIndex];
  99996. var findInVertices = function (positionToSearch) {
  99997. if (optimizeMesh) {
  99998. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  99999. if (_this.vertices[ii].position.equals(positionToSearch)) {
  100000. return _this.vertices[ii];
  100001. }
  100002. }
  100003. }
  100004. return null;
  100005. };
  100006. var vertexReferences = [];
  100007. var vertexInit = function (i) {
  100008. if (!positionData) {
  100009. return;
  100010. }
  100011. var offset = i + submesh.verticesStart;
  100012. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  100013. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  100014. vertex.originalOffsets.push(offset);
  100015. if (vertex.id === _this.vertices.length) {
  100016. _this.vertices.push(vertex);
  100017. }
  100018. vertexReferences.push(vertex.id);
  100019. };
  100020. //var totalVertices = mesh.getTotalVertices();
  100021. var totalVertices = submesh.verticesCount;
  100022. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  100023. var indicesInit = function (i) {
  100024. if (!indices) {
  100025. return;
  100026. }
  100027. var offset = (submesh.indexStart / 3) + i;
  100028. var pos = (offset * 3);
  100029. var i0 = indices[pos + 0];
  100030. var i1 = indices[pos + 1];
  100031. var i2 = indices[pos + 2];
  100032. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  100033. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  100034. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  100035. var triangle = new DecimationTriangle([v0, v1, v2]);
  100036. triangle.originalOffset = pos;
  100037. _this.triangles.push(triangle);
  100038. };
  100039. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  100040. _this.init(callback);
  100041. });
  100042. });
  100043. };
  100044. QuadraticErrorSimplification.prototype.init = function (callback) {
  100045. var _this = this;
  100046. var triangleInit1 = function (i) {
  100047. var t = _this.triangles[i];
  100048. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  100049. for (var j = 0; j < 3; j++) {
  100050. 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))));
  100051. }
  100052. };
  100053. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  100054. var triangleInit2 = function (i) {
  100055. var t = _this.triangles[i];
  100056. for (var j = 0; j < 3; ++j) {
  100057. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  100058. }
  100059. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  100060. };
  100061. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  100062. callback();
  100063. });
  100064. });
  100065. };
  100066. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  100067. var newTriangles = [];
  100068. var i;
  100069. for (i = 0; i < this.vertices.length; ++i) {
  100070. this.vertices[i].triangleCount = 0;
  100071. }
  100072. var t;
  100073. var j;
  100074. for (i = 0; i < this.triangles.length; ++i) {
  100075. if (!this.triangles[i].deleted) {
  100076. t = this.triangles[i];
  100077. for (j = 0; j < 3; ++j) {
  100078. t.vertices[j].triangleCount = 1;
  100079. }
  100080. newTriangles.push(t);
  100081. }
  100082. }
  100083. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  100084. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  100085. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  100086. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  100087. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  100088. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  100089. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  100090. var vertexCount = 0;
  100091. for (i = 0; i < this.vertices.length; ++i) {
  100092. var vertex = this.vertices[i];
  100093. vertex.id = vertexCount;
  100094. if (vertex.triangleCount) {
  100095. vertex.originalOffsets.forEach(function (originalOffset) {
  100096. if (!normalData) {
  100097. return;
  100098. }
  100099. newPositionData.push(vertex.position.x);
  100100. newPositionData.push(vertex.position.y);
  100101. newPositionData.push(vertex.position.z);
  100102. newNormalData.push(normalData[originalOffset * 3]);
  100103. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  100104. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  100105. if (uvs && uvs.length) {
  100106. newUVsData.push(uvs[(originalOffset * 2)]);
  100107. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  100108. }
  100109. else if (colorsData && colorsData.length) {
  100110. newColorsData.push(colorsData[(originalOffset * 4)]);
  100111. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  100112. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  100113. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  100114. }
  100115. ++vertexCount;
  100116. });
  100117. }
  100118. }
  100119. var startingIndex = this._reconstructedMesh.getTotalIndices();
  100120. var startingVertex = this._reconstructedMesh.getTotalVertices();
  100121. var submeshesArray = this._reconstructedMesh.subMeshes;
  100122. this._reconstructedMesh.subMeshes = [];
  100123. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  100124. var originalIndices = this._mesh.getIndices();
  100125. for (i = 0; i < newTriangles.length; ++i) {
  100126. t = newTriangles[i]; //now get the new referencing point for each vertex
  100127. [0, 1, 2].forEach(function (idx) {
  100128. var id = originalIndices[t.originalOffset + idx];
  100129. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  100130. if (offset < 0)
  100131. offset = 0;
  100132. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  100133. });
  100134. }
  100135. //overwriting the old vertex buffers and indices.
  100136. this._reconstructedMesh.setIndices(newIndicesArray);
  100137. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  100138. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  100139. if (newUVsData.length > 0)
  100140. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  100141. if (newColorsData.length > 0)
  100142. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  100143. //create submesh
  100144. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  100145. if (submeshIndex > 0) {
  100146. this._reconstructedMesh.subMeshes = [];
  100147. submeshesArray.forEach(function (submesh) {
  100148. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  100149. });
  100150. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  100151. }
  100152. };
  100153. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  100154. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  100155. this._reconstructedMesh.material = this._mesh.material;
  100156. this._reconstructedMesh.parent = this._mesh.parent;
  100157. this._reconstructedMesh.isVisible = false;
  100158. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  100159. };
  100160. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  100161. for (var i = 0; i < vertex1.triangleCount; ++i) {
  100162. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  100163. if (t.deleted)
  100164. continue;
  100165. var s = this.references[vertex1.triangleStart + i].vertexId;
  100166. var v1 = t.vertices[(s + 1) % 3];
  100167. var v2 = t.vertices[(s + 2) % 3];
  100168. if ((v1 === vertex2 || v2 === vertex2)) {
  100169. deletedArray[i] = true;
  100170. delTr.push(t);
  100171. continue;
  100172. }
  100173. var d1 = v1.position.subtract(point);
  100174. d1 = d1.normalize();
  100175. var d2 = v2.position.subtract(point);
  100176. d2 = d2.normalize();
  100177. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  100178. return true;
  100179. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  100180. deletedArray[i] = false;
  100181. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  100182. return true;
  100183. }
  100184. return false;
  100185. };
  100186. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  100187. var newDeleted = deletedTriangles;
  100188. for (var i = 0; i < vertex.triangleCount; ++i) {
  100189. var ref = this.references[vertex.triangleStart + i];
  100190. var t = this.triangles[ref.triangleId];
  100191. if (t.deleted)
  100192. continue;
  100193. if (deletedArray[i] && t.deletePending) {
  100194. t.deleted = true;
  100195. newDeleted++;
  100196. continue;
  100197. }
  100198. t.vertices[ref.vertexId] = origVertex;
  100199. t.isDirty = true;
  100200. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  100201. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  100202. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  100203. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  100204. this.references.push(ref);
  100205. }
  100206. return newDeleted;
  100207. };
  100208. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  100209. for (var i = 0; i < this.vertices.length; ++i) {
  100210. var vCount = [];
  100211. var vId = [];
  100212. var v = this.vertices[i];
  100213. var j;
  100214. for (j = 0; j < v.triangleCount; ++j) {
  100215. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  100216. for (var ii = 0; ii < 3; ii++) {
  100217. var ofs = 0;
  100218. var vv = triangle.vertices[ii];
  100219. while (ofs < vCount.length) {
  100220. if (vId[ofs] === vv.id)
  100221. break;
  100222. ++ofs;
  100223. }
  100224. if (ofs === vCount.length) {
  100225. vCount.push(1);
  100226. vId.push(vv.id);
  100227. }
  100228. else {
  100229. vCount[ofs]++;
  100230. }
  100231. }
  100232. }
  100233. for (j = 0; j < vCount.length; ++j) {
  100234. if (vCount[j] === 1) {
  100235. this.vertices[vId[j]].isBorder = true;
  100236. }
  100237. else {
  100238. this.vertices[vId[j]].isBorder = false;
  100239. }
  100240. }
  100241. }
  100242. };
  100243. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  100244. if (identifyBorders === void 0) { identifyBorders = false; }
  100245. var i;
  100246. if (!identifyBorders) {
  100247. var newTrianglesVector = [];
  100248. for (i = 0; i < this.triangles.length; ++i) {
  100249. if (!this.triangles[i].deleted) {
  100250. newTrianglesVector.push(this.triangles[i]);
  100251. }
  100252. }
  100253. this.triangles = newTrianglesVector;
  100254. }
  100255. for (i = 0; i < this.vertices.length; ++i) {
  100256. this.vertices[i].triangleCount = 0;
  100257. this.vertices[i].triangleStart = 0;
  100258. }
  100259. var t;
  100260. var j;
  100261. var v;
  100262. for (i = 0; i < this.triangles.length; ++i) {
  100263. t = this.triangles[i];
  100264. for (j = 0; j < 3; ++j) {
  100265. v = t.vertices[j];
  100266. v.triangleCount++;
  100267. }
  100268. }
  100269. var tStart = 0;
  100270. for (i = 0; i < this.vertices.length; ++i) {
  100271. this.vertices[i].triangleStart = tStart;
  100272. tStart += this.vertices[i].triangleCount;
  100273. this.vertices[i].triangleCount = 0;
  100274. }
  100275. var newReferences = new Array(this.triangles.length * 3);
  100276. for (i = 0; i < this.triangles.length; ++i) {
  100277. t = this.triangles[i];
  100278. for (j = 0; j < 3; ++j) {
  100279. v = t.vertices[j];
  100280. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  100281. v.triangleCount++;
  100282. }
  100283. }
  100284. this.references = newReferences;
  100285. if (identifyBorders) {
  100286. this.identifyBorder();
  100287. }
  100288. };
  100289. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  100290. var x = point.x;
  100291. var y = point.y;
  100292. var z = point.z;
  100293. 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
  100294. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  100295. };
  100296. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  100297. var q = vertex1.q.add(vertex2.q);
  100298. var border = vertex1.isBorder && vertex2.isBorder;
  100299. var error = 0;
  100300. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  100301. if (qDet !== 0 && !border) {
  100302. if (!pointResult) {
  100303. pointResult = BABYLON.Vector3.Zero();
  100304. }
  100305. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  100306. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  100307. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  100308. error = this.vertexError(q, pointResult);
  100309. }
  100310. else {
  100311. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  100312. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  100313. var error1 = this.vertexError(q, vertex1.position);
  100314. var error2 = this.vertexError(q, vertex2.position);
  100315. var error3 = this.vertexError(q, p3);
  100316. error = Math.min(error1, error2, error3);
  100317. if (error === error1) {
  100318. if (pointResult) {
  100319. pointResult.copyFrom(vertex1.position);
  100320. }
  100321. }
  100322. else if (error === error2) {
  100323. if (pointResult) {
  100324. pointResult.copyFrom(vertex2.position);
  100325. }
  100326. }
  100327. else {
  100328. if (pointResult) {
  100329. pointResult.copyFrom(p3);
  100330. }
  100331. }
  100332. }
  100333. return error;
  100334. };
  100335. return QuadraticErrorSimplification;
  100336. }());
  100337. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  100338. })(BABYLON || (BABYLON = {}));
  100339. //# sourceMappingURL=babylon.meshSimplification.js.map
  100340. var BABYLON;
  100341. (function (BABYLON) {
  100342. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  100343. get: function () {
  100344. if (!this._simplificationQueue) {
  100345. this._simplificationQueue = new BABYLON.SimplificationQueue();
  100346. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  100347. if (!component) {
  100348. component = new SimplicationQueueSceneComponent(this);
  100349. this._addComponent(component);
  100350. }
  100351. }
  100352. return this._simplificationQueue;
  100353. },
  100354. set: function (value) {
  100355. this._simplificationQueue = value;
  100356. },
  100357. enumerable: true,
  100358. configurable: true
  100359. });
  100360. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  100361. if (parallelProcessing === void 0) { parallelProcessing = true; }
  100362. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  100363. this.getScene().simplificationQueue.addTask({
  100364. settings: settings,
  100365. parallelProcessing: parallelProcessing,
  100366. mesh: this,
  100367. simplificationType: simplificationType,
  100368. successCallback: successCallback
  100369. });
  100370. return this;
  100371. };
  100372. /**
  100373. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  100374. * created in a scene
  100375. */
  100376. var SimplicationQueueSceneComponent = /** @class */ (function () {
  100377. /**
  100378. * Creates a new instance of the component for the given scene
  100379. * @param scene Defines the scene to register the component in
  100380. */
  100381. function SimplicationQueueSceneComponent(scene) {
  100382. /**
  100383. * The component name helpfull to identify the component in the list of scene components.
  100384. */
  100385. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  100386. this.scene = scene;
  100387. }
  100388. /**
  100389. * Registers the component in a given scene
  100390. */
  100391. SimplicationQueueSceneComponent.prototype.register = function () {
  100392. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  100393. };
  100394. /**
  100395. * Rebuilds the elements related to this component in case of
  100396. * context lost for instance.
  100397. */
  100398. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  100399. // Nothing to do for this component
  100400. };
  100401. /**
  100402. * Disposes the component and the associated ressources
  100403. */
  100404. SimplicationQueueSceneComponent.prototype.dispose = function () {
  100405. // Nothing to do for this component
  100406. };
  100407. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  100408. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  100409. this.scene._simplificationQueue.executeNext();
  100410. }
  100411. };
  100412. return SimplicationQueueSceneComponent;
  100413. }());
  100414. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  100415. })(BABYLON || (BABYLON = {}));
  100416. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  100417. var BABYLON;
  100418. (function (BABYLON) {
  100419. var MeshLODLevel = /** @class */ (function () {
  100420. function MeshLODLevel(distance, mesh) {
  100421. this.distance = distance;
  100422. this.mesh = mesh;
  100423. }
  100424. return MeshLODLevel;
  100425. }());
  100426. BABYLON.MeshLODLevel = MeshLODLevel;
  100427. })(BABYLON || (BABYLON = {}));
  100428. //# sourceMappingURL=babylon.meshLODLevel.js.map
  100429. var BABYLON;
  100430. (function (BABYLON) {
  100431. /**
  100432. * Defines the root class used to create scene optimization to use with SceneOptimizer
  100433. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100434. */
  100435. var SceneOptimization = /** @class */ (function () {
  100436. /**
  100437. * Creates the SceneOptimization object
  100438. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100439. * @param desc defines the description associated with the optimization
  100440. */
  100441. function SceneOptimization(
  100442. /**
  100443. * Defines the priority of this optimization (0 by default which means first in the list)
  100444. */
  100445. priority) {
  100446. if (priority === void 0) { priority = 0; }
  100447. this.priority = priority;
  100448. }
  100449. /**
  100450. * Gets a string describing the action executed by the current optimization
  100451. * @returns description string
  100452. */
  100453. SceneOptimization.prototype.getDescription = function () {
  100454. return "";
  100455. };
  100456. /**
  100457. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100458. * @param scene defines the current scene where to apply this optimization
  100459. * @param optimizer defines the current optimizer
  100460. * @returns true if everything that can be done was applied
  100461. */
  100462. SceneOptimization.prototype.apply = function (scene, optimizer) {
  100463. return true;
  100464. };
  100465. ;
  100466. return SceneOptimization;
  100467. }());
  100468. BABYLON.SceneOptimization = SceneOptimization;
  100469. /**
  100470. * Defines an optimization used to reduce the size of render target textures
  100471. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100472. */
  100473. var TextureOptimization = /** @class */ (function (_super) {
  100474. __extends(TextureOptimization, _super);
  100475. /**
  100476. * Creates the TextureOptimization object
  100477. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100478. * @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
  100479. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  100480. */
  100481. function TextureOptimization(
  100482. /**
  100483. * Defines the priority of this optimization (0 by default which means first in the list)
  100484. */
  100485. priority,
  100486. /**
  100487. * 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
  100488. */
  100489. maximumSize,
  100490. /**
  100491. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  100492. */
  100493. step) {
  100494. if (priority === void 0) { priority = 0; }
  100495. if (maximumSize === void 0) { maximumSize = 1024; }
  100496. if (step === void 0) { step = 0.5; }
  100497. var _this = _super.call(this, priority) || this;
  100498. _this.priority = priority;
  100499. _this.maximumSize = maximumSize;
  100500. _this.step = step;
  100501. return _this;
  100502. }
  100503. /**
  100504. * Gets a string describing the action executed by the current optimization
  100505. * @returns description string
  100506. */
  100507. TextureOptimization.prototype.getDescription = function () {
  100508. return "Reducing render target texture size to " + this.maximumSize;
  100509. };
  100510. /**
  100511. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100512. * @param scene defines the current scene where to apply this optimization
  100513. * @param optimizer defines the current optimizer
  100514. * @returns true if everything that can be done was applied
  100515. */
  100516. TextureOptimization.prototype.apply = function (scene, optimizer) {
  100517. var allDone = true;
  100518. for (var index = 0; index < scene.textures.length; index++) {
  100519. var texture = scene.textures[index];
  100520. if (!texture.canRescale || texture.getContext) {
  100521. continue;
  100522. }
  100523. var currentSize = texture.getSize();
  100524. var maxDimension = Math.max(currentSize.width, currentSize.height);
  100525. if (maxDimension > this.maximumSize) {
  100526. texture.scale(this.step);
  100527. allDone = false;
  100528. }
  100529. }
  100530. return allDone;
  100531. };
  100532. return TextureOptimization;
  100533. }(SceneOptimization));
  100534. BABYLON.TextureOptimization = TextureOptimization;
  100535. /**
  100536. * Defines an optimization used to increase or decrease the rendering resolution
  100537. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100538. */
  100539. var HardwareScalingOptimization = /** @class */ (function (_super) {
  100540. __extends(HardwareScalingOptimization, _super);
  100541. /**
  100542. * Creates the HardwareScalingOptimization object
  100543. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100544. * @param maximumScale defines the maximum scale to use (2 by default)
  100545. * @param step defines the step to use between two passes (0.5 by default)
  100546. */
  100547. function HardwareScalingOptimization(
  100548. /**
  100549. * Defines the priority of this optimization (0 by default which means first in the list)
  100550. */
  100551. priority,
  100552. /**
  100553. * Defines the maximum scale to use (2 by default)
  100554. */
  100555. maximumScale,
  100556. /**
  100557. * Defines the step to use between two passes (0.5 by default)
  100558. */
  100559. step) {
  100560. if (priority === void 0) { priority = 0; }
  100561. if (maximumScale === void 0) { maximumScale = 2; }
  100562. if (step === void 0) { step = 0.25; }
  100563. var _this = _super.call(this, priority) || this;
  100564. _this.priority = priority;
  100565. _this.maximumScale = maximumScale;
  100566. _this.step = step;
  100567. _this._currentScale = -1;
  100568. _this._directionOffset = 1;
  100569. return _this;
  100570. }
  100571. /**
  100572. * Gets a string describing the action executed by the current optimization
  100573. * @return description string
  100574. */
  100575. HardwareScalingOptimization.prototype.getDescription = function () {
  100576. return "Setting hardware scaling level to " + this._currentScale;
  100577. };
  100578. /**
  100579. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100580. * @param scene defines the current scene where to apply this optimization
  100581. * @param optimizer defines the current optimizer
  100582. * @returns true if everything that can be done was applied
  100583. */
  100584. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  100585. if (this._currentScale === -1) {
  100586. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  100587. if (this._currentScale > this.maximumScale) {
  100588. this._directionOffset = -1;
  100589. }
  100590. }
  100591. this._currentScale += this._directionOffset * this.step;
  100592. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  100593. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  100594. };
  100595. ;
  100596. return HardwareScalingOptimization;
  100597. }(SceneOptimization));
  100598. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  100599. /**
  100600. * Defines an optimization used to remove shadows
  100601. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100602. */
  100603. var ShadowsOptimization = /** @class */ (function (_super) {
  100604. __extends(ShadowsOptimization, _super);
  100605. function ShadowsOptimization() {
  100606. return _super !== null && _super.apply(this, arguments) || this;
  100607. }
  100608. /**
  100609. * Gets a string describing the action executed by the current optimization
  100610. * @return description string
  100611. */
  100612. ShadowsOptimization.prototype.getDescription = function () {
  100613. return "Turning shadows on/off";
  100614. };
  100615. /**
  100616. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100617. * @param scene defines the current scene where to apply this optimization
  100618. * @param optimizer defines the current optimizer
  100619. * @returns true if everything that can be done was applied
  100620. */
  100621. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  100622. scene.shadowsEnabled = optimizer.isInImprovementMode;
  100623. return true;
  100624. };
  100625. ;
  100626. return ShadowsOptimization;
  100627. }(SceneOptimization));
  100628. BABYLON.ShadowsOptimization = ShadowsOptimization;
  100629. /**
  100630. * Defines an optimization used to turn post-processes off
  100631. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100632. */
  100633. var PostProcessesOptimization = /** @class */ (function (_super) {
  100634. __extends(PostProcessesOptimization, _super);
  100635. function PostProcessesOptimization() {
  100636. return _super !== null && _super.apply(this, arguments) || this;
  100637. }
  100638. /**
  100639. * Gets a string describing the action executed by the current optimization
  100640. * @return description string
  100641. */
  100642. PostProcessesOptimization.prototype.getDescription = function () {
  100643. return "Turning post-processes on/off";
  100644. };
  100645. /**
  100646. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100647. * @param scene defines the current scene where to apply this optimization
  100648. * @param optimizer defines the current optimizer
  100649. * @returns true if everything that can be done was applied
  100650. */
  100651. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  100652. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  100653. return true;
  100654. };
  100655. ;
  100656. return PostProcessesOptimization;
  100657. }(SceneOptimization));
  100658. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  100659. /**
  100660. * Defines an optimization used to turn lens flares off
  100661. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100662. */
  100663. var LensFlaresOptimization = /** @class */ (function (_super) {
  100664. __extends(LensFlaresOptimization, _super);
  100665. function LensFlaresOptimization() {
  100666. return _super !== null && _super.apply(this, arguments) || this;
  100667. }
  100668. /**
  100669. * Gets a string describing the action executed by the current optimization
  100670. * @return description string
  100671. */
  100672. LensFlaresOptimization.prototype.getDescription = function () {
  100673. return "Turning lens flares on/off";
  100674. };
  100675. /**
  100676. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100677. * @param scene defines the current scene where to apply this optimization
  100678. * @param optimizer defines the current optimizer
  100679. * @returns true if everything that can be done was applied
  100680. */
  100681. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  100682. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  100683. return true;
  100684. };
  100685. ;
  100686. return LensFlaresOptimization;
  100687. }(SceneOptimization));
  100688. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  100689. /**
  100690. * Defines an optimization based on user defined callback.
  100691. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100692. */
  100693. var CustomOptimization = /** @class */ (function (_super) {
  100694. __extends(CustomOptimization, _super);
  100695. function CustomOptimization() {
  100696. return _super !== null && _super.apply(this, arguments) || this;
  100697. }
  100698. /**
  100699. * Gets a string describing the action executed by the current optimization
  100700. * @returns description string
  100701. */
  100702. CustomOptimization.prototype.getDescription = function () {
  100703. if (this.onGetDescription) {
  100704. return this.onGetDescription();
  100705. }
  100706. return "Running user defined callback";
  100707. };
  100708. /**
  100709. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100710. * @param scene defines the current scene where to apply this optimization
  100711. * @param optimizer defines the current optimizer
  100712. * @returns true if everything that can be done was applied
  100713. */
  100714. CustomOptimization.prototype.apply = function (scene, optimizer) {
  100715. if (this.onApply) {
  100716. return this.onApply(scene, optimizer);
  100717. }
  100718. return true;
  100719. };
  100720. ;
  100721. return CustomOptimization;
  100722. }(SceneOptimization));
  100723. BABYLON.CustomOptimization = CustomOptimization;
  100724. /**
  100725. * Defines an optimization used to turn particles off
  100726. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100727. */
  100728. var ParticlesOptimization = /** @class */ (function (_super) {
  100729. __extends(ParticlesOptimization, _super);
  100730. function ParticlesOptimization() {
  100731. return _super !== null && _super.apply(this, arguments) || this;
  100732. }
  100733. /**
  100734. * Gets a string describing the action executed by the current optimization
  100735. * @return description string
  100736. */
  100737. ParticlesOptimization.prototype.getDescription = function () {
  100738. return "Turning particles on/off";
  100739. };
  100740. /**
  100741. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100742. * @param scene defines the current scene where to apply this optimization
  100743. * @param optimizer defines the current optimizer
  100744. * @returns true if everything that can be done was applied
  100745. */
  100746. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  100747. scene.particlesEnabled = optimizer.isInImprovementMode;
  100748. return true;
  100749. };
  100750. ;
  100751. return ParticlesOptimization;
  100752. }(SceneOptimization));
  100753. BABYLON.ParticlesOptimization = ParticlesOptimization;
  100754. /**
  100755. * Defines an optimization used to turn render targets off
  100756. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100757. */
  100758. var RenderTargetsOptimization = /** @class */ (function (_super) {
  100759. __extends(RenderTargetsOptimization, _super);
  100760. function RenderTargetsOptimization() {
  100761. return _super !== null && _super.apply(this, arguments) || this;
  100762. }
  100763. /**
  100764. * Gets a string describing the action executed by the current optimization
  100765. * @return description string
  100766. */
  100767. RenderTargetsOptimization.prototype.getDescription = function () {
  100768. return "Turning render targets off";
  100769. };
  100770. /**
  100771. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100772. * @param scene defines the current scene where to apply this optimization
  100773. * @param optimizer defines the current optimizer
  100774. * @returns true if everything that can be done was applied
  100775. */
  100776. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  100777. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  100778. return true;
  100779. };
  100780. ;
  100781. return RenderTargetsOptimization;
  100782. }(SceneOptimization));
  100783. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  100784. /**
  100785. * Defines an optimization used to merge meshes with compatible materials
  100786. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100787. */
  100788. var MergeMeshesOptimization = /** @class */ (function (_super) {
  100789. __extends(MergeMeshesOptimization, _super);
  100790. function MergeMeshesOptimization() {
  100791. var _this = _super !== null && _super.apply(this, arguments) || this;
  100792. _this._canBeMerged = function (abstractMesh) {
  100793. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  100794. return false;
  100795. }
  100796. var mesh = abstractMesh;
  100797. if (mesh.isDisposed()) {
  100798. return false;
  100799. }
  100800. if (!mesh.isVisible || !mesh.isEnabled()) {
  100801. return false;
  100802. }
  100803. if (mesh.instances.length > 0) {
  100804. return false;
  100805. }
  100806. if (mesh.skeleton || mesh.hasLODLevels) {
  100807. return false;
  100808. }
  100809. return true;
  100810. };
  100811. return _this;
  100812. }
  100813. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  100814. /**
  100815. * Gets or sets a boolean which defines if optimization octree has to be updated
  100816. */
  100817. get: function () {
  100818. return MergeMeshesOptimization._UpdateSelectionTree;
  100819. },
  100820. /**
  100821. * Gets or sets a boolean which defines if optimization octree has to be updated
  100822. */
  100823. set: function (value) {
  100824. MergeMeshesOptimization._UpdateSelectionTree = value;
  100825. },
  100826. enumerable: true,
  100827. configurable: true
  100828. });
  100829. /**
  100830. * Gets a string describing the action executed by the current optimization
  100831. * @return description string
  100832. */
  100833. MergeMeshesOptimization.prototype.getDescription = function () {
  100834. return "Merging similar meshes together";
  100835. };
  100836. /**
  100837. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100838. * @param scene defines the current scene where to apply this optimization
  100839. * @param optimizer defines the current optimizer
  100840. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  100841. * @returns true if everything that can be done was applied
  100842. */
  100843. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  100844. var globalPool = scene.meshes.slice(0);
  100845. var globalLength = globalPool.length;
  100846. for (var index = 0; index < globalLength; index++) {
  100847. var currentPool = new Array();
  100848. var current = globalPool[index];
  100849. // Checks
  100850. if (!this._canBeMerged(current)) {
  100851. continue;
  100852. }
  100853. currentPool.push(current);
  100854. // Find compatible meshes
  100855. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  100856. var otherMesh = globalPool[subIndex];
  100857. if (!this._canBeMerged(otherMesh)) {
  100858. continue;
  100859. }
  100860. if (otherMesh.material !== current.material) {
  100861. continue;
  100862. }
  100863. if (otherMesh.checkCollisions !== current.checkCollisions) {
  100864. continue;
  100865. }
  100866. currentPool.push(otherMesh);
  100867. globalLength--;
  100868. globalPool.splice(subIndex, 1);
  100869. subIndex--;
  100870. }
  100871. if (currentPool.length < 2) {
  100872. continue;
  100873. }
  100874. // Merge meshes
  100875. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  100876. }
  100877. // Call the octree system optimization if it is defined.
  100878. var sceneAsAny = scene;
  100879. if (sceneAsAny.createOrUpdateSelectionOctree) {
  100880. if (updateSelectionTree != undefined) {
  100881. if (updateSelectionTree) {
  100882. sceneAsAny.createOrUpdateSelectionOctree();
  100883. }
  100884. }
  100885. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  100886. sceneAsAny.createOrUpdateSelectionOctree();
  100887. }
  100888. }
  100889. return true;
  100890. };
  100891. ;
  100892. MergeMeshesOptimization._UpdateSelectionTree = false;
  100893. return MergeMeshesOptimization;
  100894. }(SceneOptimization));
  100895. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  100896. /**
  100897. * Defines a list of options used by SceneOptimizer
  100898. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100899. */
  100900. var SceneOptimizerOptions = /** @class */ (function () {
  100901. /**
  100902. * Creates a new list of options used by SceneOptimizer
  100903. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  100904. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  100905. */
  100906. function SceneOptimizerOptions(
  100907. /**
  100908. * Defines the target frame rate to reach (60 by default)
  100909. */
  100910. targetFrameRate,
  100911. /**
  100912. * Defines the interval between two checkes (2000ms by default)
  100913. */
  100914. trackerDuration) {
  100915. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  100916. if (trackerDuration === void 0) { trackerDuration = 2000; }
  100917. this.targetFrameRate = targetFrameRate;
  100918. this.trackerDuration = trackerDuration;
  100919. /**
  100920. * Gets the list of optimizations to apply
  100921. */
  100922. this.optimizations = new Array();
  100923. }
  100924. /**
  100925. * Add a new optimization
  100926. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  100927. * @returns the current SceneOptimizerOptions
  100928. */
  100929. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  100930. this.optimizations.push(optimization);
  100931. return this;
  100932. };
  100933. /**
  100934. * Add a new custom optimization
  100935. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  100936. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  100937. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100938. * @returns the current SceneOptimizerOptions
  100939. */
  100940. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  100941. if (priority === void 0) { priority = 0; }
  100942. var optimization = new CustomOptimization(priority);
  100943. optimization.onApply = onApply;
  100944. optimization.onGetDescription = onGetDescription;
  100945. this.optimizations.push(optimization);
  100946. return this;
  100947. };
  100948. /**
  100949. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  100950. * @param targetFrameRate defines the target frame rate (60 by default)
  100951. * @returns a SceneOptimizerOptions object
  100952. */
  100953. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  100954. var result = new SceneOptimizerOptions(targetFrameRate);
  100955. var priority = 0;
  100956. result.addOptimization(new MergeMeshesOptimization(priority));
  100957. result.addOptimization(new ShadowsOptimization(priority));
  100958. result.addOptimization(new LensFlaresOptimization(priority));
  100959. // Next priority
  100960. priority++;
  100961. result.addOptimization(new PostProcessesOptimization(priority));
  100962. result.addOptimization(new ParticlesOptimization(priority));
  100963. // Next priority
  100964. priority++;
  100965. result.addOptimization(new TextureOptimization(priority, 1024));
  100966. return result;
  100967. };
  100968. /**
  100969. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  100970. * @param targetFrameRate defines the target frame rate (60 by default)
  100971. * @returns a SceneOptimizerOptions object
  100972. */
  100973. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  100974. var result = new SceneOptimizerOptions(targetFrameRate);
  100975. var priority = 0;
  100976. result.addOptimization(new MergeMeshesOptimization(priority));
  100977. result.addOptimization(new ShadowsOptimization(priority));
  100978. result.addOptimization(new LensFlaresOptimization(priority));
  100979. // Next priority
  100980. priority++;
  100981. result.addOptimization(new PostProcessesOptimization(priority));
  100982. result.addOptimization(new ParticlesOptimization(priority));
  100983. // Next priority
  100984. priority++;
  100985. result.addOptimization(new TextureOptimization(priority, 512));
  100986. // Next priority
  100987. priority++;
  100988. result.addOptimization(new RenderTargetsOptimization(priority));
  100989. // Next priority
  100990. priority++;
  100991. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  100992. return result;
  100993. };
  100994. /**
  100995. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  100996. * @param targetFrameRate defines the target frame rate (60 by default)
  100997. * @returns a SceneOptimizerOptions object
  100998. */
  100999. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  101000. var result = new SceneOptimizerOptions(targetFrameRate);
  101001. var priority = 0;
  101002. result.addOptimization(new MergeMeshesOptimization(priority));
  101003. result.addOptimization(new ShadowsOptimization(priority));
  101004. result.addOptimization(new LensFlaresOptimization(priority));
  101005. // Next priority
  101006. priority++;
  101007. result.addOptimization(new PostProcessesOptimization(priority));
  101008. result.addOptimization(new ParticlesOptimization(priority));
  101009. // Next priority
  101010. priority++;
  101011. result.addOptimization(new TextureOptimization(priority, 256));
  101012. // Next priority
  101013. priority++;
  101014. result.addOptimization(new RenderTargetsOptimization(priority));
  101015. // Next priority
  101016. priority++;
  101017. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  101018. return result;
  101019. };
  101020. return SceneOptimizerOptions;
  101021. }());
  101022. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  101023. /**
  101024. * Class used to run optimizations in order to reach a target frame rate
  101025. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  101026. */
  101027. var SceneOptimizer = /** @class */ (function () {
  101028. /**
  101029. * Creates a new SceneOptimizer
  101030. * @param scene defines the scene to work on
  101031. * @param options defines the options to use with the SceneOptimizer
  101032. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  101033. * @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)
  101034. */
  101035. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  101036. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  101037. if (improvementMode === void 0) { improvementMode = false; }
  101038. var _this = this;
  101039. this._isRunning = false;
  101040. this._currentPriorityLevel = 0;
  101041. this._targetFrameRate = 60;
  101042. this._trackerDuration = 2000;
  101043. this._currentFrameRate = 0;
  101044. this._improvementMode = false;
  101045. /**
  101046. * Defines an observable called when the optimizer reaches the target frame rate
  101047. */
  101048. this.onSuccessObservable = new BABYLON.Observable();
  101049. /**
  101050. * Defines an observable called when the optimizer enables an optimization
  101051. */
  101052. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  101053. /**
  101054. * Defines an observable called when the optimizer is not able to reach the target frame rate
  101055. */
  101056. this.onFailureObservable = new BABYLON.Observable();
  101057. if (!options) {
  101058. this._options = new SceneOptimizerOptions();
  101059. }
  101060. else {
  101061. this._options = options;
  101062. }
  101063. if (this._options.targetFrameRate) {
  101064. this._targetFrameRate = this._options.targetFrameRate;
  101065. }
  101066. if (this._options.trackerDuration) {
  101067. this._trackerDuration = this._options.trackerDuration;
  101068. }
  101069. if (autoGeneratePriorities) {
  101070. var priority = 0;
  101071. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  101072. var optim = _a[_i];
  101073. optim.priority = priority++;
  101074. }
  101075. }
  101076. this._improvementMode = improvementMode;
  101077. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  101078. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  101079. _this._sceneDisposeObserver = null;
  101080. _this.dispose();
  101081. });
  101082. }
  101083. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  101084. /**
  101085. * Gets a boolean indicating if the optimizer is in improvement mode
  101086. */
  101087. get: function () {
  101088. return this._improvementMode;
  101089. },
  101090. enumerable: true,
  101091. configurable: true
  101092. });
  101093. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  101094. /**
  101095. * Gets the current priority level (0 at start)
  101096. */
  101097. get: function () {
  101098. return this._currentPriorityLevel;
  101099. },
  101100. enumerable: true,
  101101. configurable: true
  101102. });
  101103. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  101104. /**
  101105. * Gets the current frame rate checked by the SceneOptimizer
  101106. */
  101107. get: function () {
  101108. return this._currentFrameRate;
  101109. },
  101110. enumerable: true,
  101111. configurable: true
  101112. });
  101113. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  101114. /**
  101115. * Gets or sets the current target frame rate (60 by default)
  101116. */
  101117. get: function () {
  101118. return this._targetFrameRate;
  101119. },
  101120. /**
  101121. * Gets or sets the current target frame rate (60 by default)
  101122. */
  101123. set: function (value) {
  101124. this._targetFrameRate = value;
  101125. },
  101126. enumerable: true,
  101127. configurable: true
  101128. });
  101129. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  101130. /**
  101131. * Gets or sets the current interval between two checks (every 2000ms by default)
  101132. */
  101133. get: function () {
  101134. return this._trackerDuration;
  101135. },
  101136. /**
  101137. * Gets or sets the current interval between two checks (every 2000ms by default)
  101138. */
  101139. set: function (value) {
  101140. this._trackerDuration = value;
  101141. },
  101142. enumerable: true,
  101143. configurable: true
  101144. });
  101145. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  101146. /**
  101147. * Gets the list of active optimizations
  101148. */
  101149. get: function () {
  101150. return this._options.optimizations;
  101151. },
  101152. enumerable: true,
  101153. configurable: true
  101154. });
  101155. /**
  101156. * Stops the current optimizer
  101157. */
  101158. SceneOptimizer.prototype.stop = function () {
  101159. this._isRunning = false;
  101160. };
  101161. /**
  101162. * Reset the optimizer to initial step (current priority level = 0)
  101163. */
  101164. SceneOptimizer.prototype.reset = function () {
  101165. this._currentPriorityLevel = 0;
  101166. };
  101167. /**
  101168. * Start the optimizer. By default it will try to reach a specific framerate
  101169. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  101170. */
  101171. SceneOptimizer.prototype.start = function () {
  101172. var _this = this;
  101173. if (this._isRunning) {
  101174. return;
  101175. }
  101176. this._isRunning = true;
  101177. // Let's wait for the scene to be ready before running our check
  101178. this._scene.executeWhenReady(function () {
  101179. setTimeout(function () {
  101180. _this._checkCurrentState();
  101181. }, _this._trackerDuration);
  101182. });
  101183. };
  101184. SceneOptimizer.prototype._checkCurrentState = function () {
  101185. var _this = this;
  101186. if (!this._isRunning) {
  101187. return;
  101188. }
  101189. var scene = this._scene;
  101190. var options = this._options;
  101191. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  101192. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  101193. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  101194. this._isRunning = false;
  101195. this.onSuccessObservable.notifyObservers(this);
  101196. return;
  101197. }
  101198. // Apply current level of optimizations
  101199. var allDone = true;
  101200. var noOptimizationApplied = true;
  101201. for (var index = 0; index < options.optimizations.length; index++) {
  101202. var optimization = options.optimizations[index];
  101203. if (optimization.priority === this._currentPriorityLevel) {
  101204. noOptimizationApplied = false;
  101205. allDone = allDone && optimization.apply(scene, this);
  101206. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  101207. }
  101208. }
  101209. // If no optimization was applied, this is a failure :(
  101210. if (noOptimizationApplied) {
  101211. this._isRunning = false;
  101212. this.onFailureObservable.notifyObservers(this);
  101213. return;
  101214. }
  101215. // If all optimizations were done, move to next level
  101216. if (allDone) {
  101217. this._currentPriorityLevel++;
  101218. }
  101219. // Let's the system running for a specific amount of time before checking FPS
  101220. scene.executeWhenReady(function () {
  101221. setTimeout(function () {
  101222. _this._checkCurrentState();
  101223. }, _this._trackerDuration);
  101224. });
  101225. };
  101226. /**
  101227. * Release all resources
  101228. */
  101229. SceneOptimizer.prototype.dispose = function () {
  101230. this.stop();
  101231. this.onSuccessObservable.clear();
  101232. this.onFailureObservable.clear();
  101233. this.onNewOptimizationAppliedObservable.clear();
  101234. if (this._sceneDisposeObserver) {
  101235. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  101236. }
  101237. };
  101238. /**
  101239. * Helper function to create a SceneOptimizer with one single line of code
  101240. * @param scene defines the scene to work on
  101241. * @param options defines the options to use with the SceneOptimizer
  101242. * @param onSuccess defines a callback to call on success
  101243. * @param onFailure defines a callback to call on failure
  101244. * @returns the new SceneOptimizer object
  101245. */
  101246. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  101247. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  101248. if (onSuccess) {
  101249. optimizer.onSuccessObservable.add(function () {
  101250. onSuccess();
  101251. });
  101252. }
  101253. if (onFailure) {
  101254. optimizer.onFailureObservable.add(function () {
  101255. onFailure();
  101256. });
  101257. }
  101258. optimizer.start();
  101259. return optimizer;
  101260. };
  101261. return SceneOptimizer;
  101262. }());
  101263. BABYLON.SceneOptimizer = SceneOptimizer;
  101264. })(BABYLON || (BABYLON = {}));
  101265. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  101266. var BABYLON;
  101267. (function (BABYLON) {
  101268. /**
  101269. * Gets the outline renderer associated with the scene
  101270. * @returns a OutlineRenderer
  101271. */
  101272. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  101273. if (!this._outlineRenderer) {
  101274. this._outlineRenderer = new OutlineRenderer(this);
  101275. }
  101276. return this._outlineRenderer;
  101277. };
  101278. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  101279. get: function () {
  101280. return this._renderOutline;
  101281. },
  101282. set: function (value) {
  101283. if (value) {
  101284. // Lazy Load the component.
  101285. this.getScene().getOutlineRenderer();
  101286. }
  101287. this._renderOutline = value;
  101288. },
  101289. enumerable: true,
  101290. configurable: true
  101291. });
  101292. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  101293. get: function () {
  101294. return this._renderOverlay;
  101295. },
  101296. set: function (value) {
  101297. if (value) {
  101298. // Lazy Load the component.
  101299. this.getScene().getOutlineRenderer();
  101300. }
  101301. this._renderOverlay = value;
  101302. },
  101303. enumerable: true,
  101304. configurable: true
  101305. });
  101306. /**
  101307. * This class is responsible to draw bothe outline/overlay of meshes.
  101308. * It should not be used directly but through the available method on mesh.
  101309. */
  101310. var OutlineRenderer = /** @class */ (function () {
  101311. /**
  101312. * Instantiates a new outline renderer. (There could be only one per scene).
  101313. * @param scene Defines the scene it belongs to
  101314. */
  101315. function OutlineRenderer(scene) {
  101316. /**
  101317. * The name of the component. Each component must have a unique name.
  101318. */
  101319. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  101320. /**
  101321. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  101322. */
  101323. this.zOffset = 1;
  101324. this.scene = scene;
  101325. this._engine = scene.getEngine();
  101326. this.scene._addComponent(this);
  101327. }
  101328. /**
  101329. * Register the component to one instance of a scene.
  101330. */
  101331. OutlineRenderer.prototype.register = function () {
  101332. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  101333. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  101334. };
  101335. /**
  101336. * Rebuilds the elements related to this component in case of
  101337. * context lost for instance.
  101338. */
  101339. OutlineRenderer.prototype.rebuild = function () {
  101340. // Nothing to do here.
  101341. };
  101342. /**
  101343. * Disposes the component and the associated ressources.
  101344. */
  101345. OutlineRenderer.prototype.dispose = function () {
  101346. // Nothing to do here.
  101347. };
  101348. /**
  101349. * Renders the outline in the canvas.
  101350. * @param subMesh Defines the sumesh to render
  101351. * @param batch Defines the batch of meshes in case of instances
  101352. * @param useOverlay Defines if the rendering is for the overlay or the outline
  101353. */
  101354. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  101355. var _this = this;
  101356. if (useOverlay === void 0) { useOverlay = false; }
  101357. var scene = this.scene;
  101358. var engine = scene.getEngine();
  101359. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  101360. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  101361. return;
  101362. }
  101363. var mesh = subMesh.getRenderingMesh();
  101364. var material = subMesh.getMaterial();
  101365. if (!material || !scene.activeCamera) {
  101366. return;
  101367. }
  101368. engine.enableEffect(this._effect);
  101369. // Logarithmic depth
  101370. if (material.useLogarithmicDepth) {
  101371. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  101372. }
  101373. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  101374. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  101375. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  101376. // Bones
  101377. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  101378. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  101379. }
  101380. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  101381. // Alpha test
  101382. if (material && material.needAlphaTesting()) {
  101383. var alphaTexture = material.getAlphaTestTexture();
  101384. if (alphaTexture) {
  101385. this._effect.setTexture("diffuseSampler", alphaTexture);
  101386. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  101387. }
  101388. }
  101389. engine.setZOffset(-this.zOffset);
  101390. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  101391. engine.setZOffset(0);
  101392. };
  101393. /**
  101394. * Returns whether or not the outline renderer is ready for a given submesh.
  101395. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  101396. * @param subMesh Defines the submesh to check readyness for
  101397. * @param useInstances Defines wheter wee are trying to render instances or not
  101398. * @returns true if ready otherwise false
  101399. */
  101400. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  101401. var defines = [];
  101402. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  101403. var mesh = subMesh.getMesh();
  101404. var material = subMesh.getMaterial();
  101405. if (material) {
  101406. // Alpha test
  101407. if (material.needAlphaTesting()) {
  101408. defines.push("#define ALPHATEST");
  101409. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  101410. attribs.push(BABYLON.VertexBuffer.UVKind);
  101411. defines.push("#define UV1");
  101412. }
  101413. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  101414. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  101415. defines.push("#define UV2");
  101416. }
  101417. }
  101418. //Logarithmic depth
  101419. if (material.useLogarithmicDepth) {
  101420. defines.push("#define LOGARITHMICDEPTH");
  101421. }
  101422. }
  101423. // Bones
  101424. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  101425. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  101426. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  101427. if (mesh.numBoneInfluencers > 4) {
  101428. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  101429. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  101430. }
  101431. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  101432. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  101433. }
  101434. else {
  101435. defines.push("#define NUM_BONE_INFLUENCERS 0");
  101436. }
  101437. // Instances
  101438. if (useInstances) {
  101439. defines.push("#define INSTANCES");
  101440. attribs.push("world0");
  101441. attribs.push("world1");
  101442. attribs.push("world2");
  101443. attribs.push("world3");
  101444. }
  101445. // Get correct effect
  101446. var join = defines.join("\n");
  101447. if (this._cachedDefines !== join) {
  101448. this._cachedDefines = join;
  101449. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  101450. }
  101451. return this._effect.isReady();
  101452. };
  101453. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  101454. // Outline - step 1
  101455. this._savedDepthWrite = this._engine.getDepthWrite();
  101456. if (mesh.renderOutline) {
  101457. this._engine.setDepthWrite(false);
  101458. this.render(subMesh, batch);
  101459. this._engine.setDepthWrite(this._savedDepthWrite);
  101460. }
  101461. };
  101462. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  101463. // Outline - step 2
  101464. if (mesh.renderOutline && this._savedDepthWrite) {
  101465. this._engine.setDepthWrite(true);
  101466. this._engine.setColorWrite(false);
  101467. this.render(subMesh, batch);
  101468. this._engine.setColorWrite(true);
  101469. }
  101470. // Overlay
  101471. if (mesh.renderOverlay) {
  101472. var currentMode = this._engine.getAlphaMode();
  101473. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  101474. this.render(subMesh, batch, true);
  101475. this._engine.setAlphaMode(currentMode);
  101476. }
  101477. };
  101478. return OutlineRenderer;
  101479. }());
  101480. BABYLON.OutlineRenderer = OutlineRenderer;
  101481. })(BABYLON || (BABYLON = {}));
  101482. //# sourceMappingURL=babylon.outlineRenderer.js.map
  101483. var BABYLON;
  101484. (function (BABYLON) {
  101485. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  101486. if (this._edgesRenderer) {
  101487. this._edgesRenderer.dispose();
  101488. this._edgesRenderer = null;
  101489. }
  101490. return this;
  101491. };
  101492. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  101493. if (epsilon === void 0) { epsilon = 0.95; }
  101494. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101495. this.disableEdgesRendering();
  101496. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  101497. return this;
  101498. };
  101499. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  101500. get: function () {
  101501. return this._edgesRenderer;
  101502. },
  101503. enumerable: true,
  101504. configurable: true
  101505. });
  101506. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  101507. if (epsilon === void 0) { epsilon = 0.95; }
  101508. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101509. this.disableEdgesRendering();
  101510. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  101511. return this;
  101512. };
  101513. /**
  101514. * FaceAdjacencies Helper class to generate edges
  101515. */
  101516. var FaceAdjacencies = /** @class */ (function () {
  101517. function FaceAdjacencies() {
  101518. this.edges = new Array();
  101519. this.edgesConnectedCount = 0;
  101520. }
  101521. return FaceAdjacencies;
  101522. }());
  101523. /**
  101524. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  101525. */
  101526. var EdgesRenderer = /** @class */ (function () {
  101527. /**
  101528. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  101529. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  101530. * @param source Mesh used to create edges
  101531. * @param epsilon sum of angles in adjacency to check for edge
  101532. * @param checkVerticesInsteadOfIndices
  101533. * @param generateEdgesLines - should generate Lines or only prepare resources.
  101534. */
  101535. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  101536. if (epsilon === void 0) { epsilon = 0.95; }
  101537. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101538. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  101539. var _this = this;
  101540. this.edgesWidthScalerForOrthographic = 1000.0;
  101541. this.edgesWidthScalerForPerspective = 50.0;
  101542. this._linesPositions = new Array();
  101543. this._linesNormals = new Array();
  101544. this._linesIndices = new Array();
  101545. this._buffers = {};
  101546. this._checkVerticesInsteadOfIndices = false;
  101547. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  101548. this.isEnabled = true;
  101549. this._source = source;
  101550. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  101551. this._epsilon = epsilon;
  101552. this._prepareRessources();
  101553. if (generateEdgesLines) {
  101554. this._generateEdgesLines();
  101555. }
  101556. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  101557. _this._rebuild();
  101558. });
  101559. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  101560. _this.dispose();
  101561. });
  101562. }
  101563. EdgesRenderer.prototype._prepareRessources = function () {
  101564. if (this._lineShader) {
  101565. return;
  101566. }
  101567. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  101568. attributes: ["position", "normal"],
  101569. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  101570. });
  101571. this._lineShader.disableDepthWrite = true;
  101572. this._lineShader.backFaceCulling = false;
  101573. };
  101574. /** @hidden */
  101575. EdgesRenderer.prototype._rebuild = function () {
  101576. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  101577. if (buffer) {
  101578. buffer._rebuild();
  101579. }
  101580. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  101581. if (buffer) {
  101582. buffer._rebuild();
  101583. }
  101584. var scene = this._source.getScene();
  101585. var engine = scene.getEngine();
  101586. this._ib = engine.createIndexBuffer(this._linesIndices);
  101587. };
  101588. /**
  101589. * Releases the required resources for the edges renderer
  101590. */
  101591. EdgesRenderer.prototype.dispose = function () {
  101592. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  101593. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  101594. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  101595. if (buffer) {
  101596. buffer.dispose();
  101597. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  101598. }
  101599. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  101600. if (buffer) {
  101601. buffer.dispose();
  101602. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  101603. }
  101604. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  101605. this._lineShader.dispose();
  101606. };
  101607. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  101608. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  101609. return 0;
  101610. }
  101611. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  101612. return 1;
  101613. }
  101614. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  101615. return 2;
  101616. }
  101617. return -1;
  101618. };
  101619. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  101620. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  101621. return 0;
  101622. }
  101623. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  101624. return 1;
  101625. }
  101626. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  101627. return 2;
  101628. }
  101629. return -1;
  101630. };
  101631. /**
  101632. * Checks if the pair of p0 and p1 is en edge
  101633. * @param faceIndex
  101634. * @param edge
  101635. * @param faceNormals
  101636. * @param p0
  101637. * @param p1
  101638. * @private
  101639. */
  101640. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  101641. var needToCreateLine;
  101642. if (edge === undefined) {
  101643. needToCreateLine = true;
  101644. }
  101645. else {
  101646. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  101647. needToCreateLine = dotProduct < this._epsilon;
  101648. }
  101649. if (needToCreateLine) {
  101650. var offset = this._linesPositions.length / 3;
  101651. var normal = p0.subtract(p1);
  101652. normal.normalize();
  101653. // Positions
  101654. this._linesPositions.push(p0.x);
  101655. this._linesPositions.push(p0.y);
  101656. this._linesPositions.push(p0.z);
  101657. this._linesPositions.push(p0.x);
  101658. this._linesPositions.push(p0.y);
  101659. this._linesPositions.push(p0.z);
  101660. this._linesPositions.push(p1.x);
  101661. this._linesPositions.push(p1.y);
  101662. this._linesPositions.push(p1.z);
  101663. this._linesPositions.push(p1.x);
  101664. this._linesPositions.push(p1.y);
  101665. this._linesPositions.push(p1.z);
  101666. // Normals
  101667. this._linesNormals.push(p1.x);
  101668. this._linesNormals.push(p1.y);
  101669. this._linesNormals.push(p1.z);
  101670. this._linesNormals.push(-1);
  101671. this._linesNormals.push(p1.x);
  101672. this._linesNormals.push(p1.y);
  101673. this._linesNormals.push(p1.z);
  101674. this._linesNormals.push(1);
  101675. this._linesNormals.push(p0.x);
  101676. this._linesNormals.push(p0.y);
  101677. this._linesNormals.push(p0.z);
  101678. this._linesNormals.push(-1);
  101679. this._linesNormals.push(p0.x);
  101680. this._linesNormals.push(p0.y);
  101681. this._linesNormals.push(p0.z);
  101682. this._linesNormals.push(1);
  101683. // Indices
  101684. this._linesIndices.push(offset);
  101685. this._linesIndices.push(offset + 1);
  101686. this._linesIndices.push(offset + 2);
  101687. this._linesIndices.push(offset);
  101688. this._linesIndices.push(offset + 2);
  101689. this._linesIndices.push(offset + 3);
  101690. }
  101691. };
  101692. /**
  101693. * Generates lines edges from adjacencjes
  101694. * @private
  101695. */
  101696. EdgesRenderer.prototype._generateEdgesLines = function () {
  101697. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  101698. var indices = this._source.getIndices();
  101699. if (!indices || !positions) {
  101700. return;
  101701. }
  101702. // First let's find adjacencies
  101703. var adjacencies = new Array();
  101704. var faceNormals = new Array();
  101705. var index;
  101706. var faceAdjacencies;
  101707. // Prepare faces
  101708. for (index = 0; index < indices.length; index += 3) {
  101709. faceAdjacencies = new FaceAdjacencies();
  101710. var p0Index = indices[index];
  101711. var p1Index = indices[index + 1];
  101712. var p2Index = indices[index + 2];
  101713. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  101714. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  101715. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  101716. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  101717. faceNormal.normalize();
  101718. faceNormals.push(faceNormal);
  101719. adjacencies.push(faceAdjacencies);
  101720. }
  101721. // Scan
  101722. for (index = 0; index < adjacencies.length; index++) {
  101723. faceAdjacencies = adjacencies[index];
  101724. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  101725. var otherFaceAdjacencies = adjacencies[otherIndex];
  101726. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  101727. break;
  101728. }
  101729. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  101730. continue;
  101731. }
  101732. var otherP0 = indices[otherIndex * 3];
  101733. var otherP1 = indices[otherIndex * 3 + 1];
  101734. var otherP2 = indices[otherIndex * 3 + 2];
  101735. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  101736. var otherEdgeIndex = 0;
  101737. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  101738. continue;
  101739. }
  101740. switch (edgeIndex) {
  101741. case 0:
  101742. if (this._checkVerticesInsteadOfIndices) {
  101743. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101744. }
  101745. else {
  101746. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  101747. }
  101748. break;
  101749. case 1:
  101750. if (this._checkVerticesInsteadOfIndices) {
  101751. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101752. }
  101753. else {
  101754. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  101755. }
  101756. break;
  101757. case 2:
  101758. if (this._checkVerticesInsteadOfIndices) {
  101759. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101760. }
  101761. else {
  101762. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  101763. }
  101764. break;
  101765. }
  101766. if (otherEdgeIndex === -1) {
  101767. continue;
  101768. }
  101769. faceAdjacencies.edges[edgeIndex] = otherIndex;
  101770. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  101771. faceAdjacencies.edgesConnectedCount++;
  101772. otherFaceAdjacencies.edgesConnectedCount++;
  101773. if (faceAdjacencies.edgesConnectedCount === 3) {
  101774. break;
  101775. }
  101776. }
  101777. }
  101778. }
  101779. // Create lines
  101780. for (index = 0; index < adjacencies.length; index++) {
  101781. // 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
  101782. var current = adjacencies[index];
  101783. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  101784. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  101785. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  101786. }
  101787. // Merge into a single mesh
  101788. var engine = this._source.getScene().getEngine();
  101789. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  101790. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  101791. this._ib = engine.createIndexBuffer(this._linesIndices);
  101792. this._indicesCount = this._linesIndices.length;
  101793. };
  101794. /**
  101795. * Checks wether or not the edges renderer is ready to render.
  101796. * @return true if ready, otherwise false.
  101797. */
  101798. EdgesRenderer.prototype.isReady = function () {
  101799. return this._lineShader.isReady();
  101800. };
  101801. /**
  101802. * Renders the edges of the attached mesh,
  101803. */
  101804. EdgesRenderer.prototype.render = function () {
  101805. var scene = this._source.getScene();
  101806. if (!this.isReady() || !scene.activeCamera) {
  101807. return;
  101808. }
  101809. var engine = scene.getEngine();
  101810. this._lineShader._preBind();
  101811. if (this._source.edgesColor.a !== 1) {
  101812. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  101813. }
  101814. else {
  101815. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  101816. }
  101817. // VBOs
  101818. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  101819. scene.resetCachedMaterial();
  101820. this._lineShader.setColor4("color", this._source.edgesColor);
  101821. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  101822. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  101823. }
  101824. else {
  101825. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  101826. }
  101827. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  101828. this._lineShader.bind(this._source.getWorldMatrix());
  101829. // Draw order
  101830. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  101831. this._lineShader.unbind();
  101832. };
  101833. return EdgesRenderer;
  101834. }());
  101835. BABYLON.EdgesRenderer = EdgesRenderer;
  101836. })(BABYLON || (BABYLON = {}));
  101837. //# sourceMappingURL=babylon.edgesRenderer.js.map
  101838. var BABYLON;
  101839. (function (BABYLON) {
  101840. /**
  101841. * FaceAdjacencies Helper class to generate edges
  101842. */
  101843. var FaceAdjacencies = /** @class */ (function () {
  101844. function FaceAdjacencies() {
  101845. this.edges = new Array();
  101846. this.edgesConnectedCount = 0;
  101847. }
  101848. return FaceAdjacencies;
  101849. }());
  101850. /**
  101851. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  101852. */
  101853. var LineEdgesRenderer = /** @class */ (function (_super) {
  101854. __extends(LineEdgesRenderer, _super);
  101855. /**
  101856. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  101857. * @param source LineMesh used to generate edges
  101858. * @param epsilon not important (specified angle for edge detection)
  101859. * @param checkVerticesInsteadOfIndices not important for LineMesh
  101860. */
  101861. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  101862. if (epsilon === void 0) { epsilon = 0.95; }
  101863. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101864. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  101865. _this._generateEdgesLines();
  101866. return _this;
  101867. }
  101868. /**
  101869. * Always create the edge since its a line so only important things are p0 and p1
  101870. * @param faceIndex not important for LineMesh
  101871. * @param edge not important for LineMesh
  101872. * @param faceNormals not important for LineMesh
  101873. * @param p0 beginnig of line
  101874. * @param p1 end of line
  101875. */
  101876. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  101877. var offset = this._linesPositions.length / 3;
  101878. var normal = p0.subtract(p1);
  101879. normal.normalize();
  101880. // Positions
  101881. this._linesPositions.push(p0.x);
  101882. this._linesPositions.push(p0.y);
  101883. this._linesPositions.push(p0.z);
  101884. this._linesPositions.push(p0.x);
  101885. this._linesPositions.push(p0.y);
  101886. this._linesPositions.push(p0.z);
  101887. this._linesPositions.push(p1.x);
  101888. this._linesPositions.push(p1.y);
  101889. this._linesPositions.push(p1.z);
  101890. this._linesPositions.push(p1.x);
  101891. this._linesPositions.push(p1.y);
  101892. this._linesPositions.push(p1.z);
  101893. // Normals
  101894. this._linesNormals.push(p1.x);
  101895. this._linesNormals.push(p1.y);
  101896. this._linesNormals.push(p1.z);
  101897. this._linesNormals.push(-1);
  101898. this._linesNormals.push(p1.x);
  101899. this._linesNormals.push(p1.y);
  101900. this._linesNormals.push(p1.z);
  101901. this._linesNormals.push(1);
  101902. this._linesNormals.push(p0.x);
  101903. this._linesNormals.push(p0.y);
  101904. this._linesNormals.push(p0.z);
  101905. this._linesNormals.push(-1);
  101906. this._linesNormals.push(p0.x);
  101907. this._linesNormals.push(p0.y);
  101908. this._linesNormals.push(p0.z);
  101909. this._linesNormals.push(1);
  101910. // Indices
  101911. this._linesIndices.push(offset);
  101912. this._linesIndices.push(offset + 1);
  101913. this._linesIndices.push(offset + 2);
  101914. this._linesIndices.push(offset);
  101915. this._linesIndices.push(offset + 2);
  101916. this._linesIndices.push(offset + 3);
  101917. };
  101918. /**
  101919. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  101920. */
  101921. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  101922. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  101923. var indices = this._source.getIndices();
  101924. if (!indices || !positions) {
  101925. return;
  101926. }
  101927. // First let's find adjacencies
  101928. var adjacencies = new Array();
  101929. var faceNormals = new Array();
  101930. var index;
  101931. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  101932. var currentAdjecancy = new FaceAdjacencies();
  101933. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  101934. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  101935. adjacencies.push(currentAdjecancy);
  101936. }
  101937. // Create lines
  101938. for (index = 0; index < adjacencies.length; index++) {
  101939. // 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
  101940. var current = adjacencies[index];
  101941. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  101942. }
  101943. // Merge into a single mesh
  101944. var engine = this._source.getScene().getEngine();
  101945. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  101946. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  101947. this._ib = engine.createIndexBuffer(this._linesIndices);
  101948. this._indicesCount = this._linesIndices.length;
  101949. };
  101950. return LineEdgesRenderer;
  101951. }(BABYLON.EdgesRenderer));
  101952. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  101953. })(BABYLON || (BABYLON = {}));
  101954. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  101955. var BABYLON;
  101956. (function (BABYLON) {
  101957. // Adds the parser to the scene parsers.
  101958. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  101959. if (parsedData.effectLayers) {
  101960. if (!container.effectLayers) {
  101961. container.effectLayers = new Array();
  101962. }
  101963. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  101964. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  101965. container.effectLayers.push(effectLayer);
  101966. }
  101967. }
  101968. });
  101969. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  101970. var index = this.effectLayers.indexOf(toRemove);
  101971. if (index !== -1) {
  101972. this.effectLayers.splice(index, 1);
  101973. }
  101974. return index;
  101975. };
  101976. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  101977. this.effectLayers.push(newEffectLayer);
  101978. };
  101979. /**
  101980. * Defines the layer scene component responsible to manage any effect layers
  101981. * in a given scene.
  101982. */
  101983. var EffectLayerSceneComponent = /** @class */ (function () {
  101984. /**
  101985. * Creates a new instance of the component for the given scene
  101986. * @param scene Defines the scene to register the component in
  101987. */
  101988. function EffectLayerSceneComponent(scene) {
  101989. /**
  101990. * The component name helpfull to identify the component in the list of scene components.
  101991. */
  101992. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  101993. this._renderEffects = false;
  101994. this._needStencil = false;
  101995. this._previousStencilState = false;
  101996. this.scene = scene;
  101997. this._engine = scene.getEngine();
  101998. scene.effectLayers = new Array();
  101999. }
  102000. /**
  102001. * Registers the component in a given scene
  102002. */
  102003. EffectLayerSceneComponent.prototype.register = function () {
  102004. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  102005. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  102006. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  102007. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  102008. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  102009. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  102010. };
  102011. /**
  102012. * Rebuilds the elements related to this component in case of
  102013. * context lost for instance.
  102014. */
  102015. EffectLayerSceneComponent.prototype.rebuild = function () {
  102016. var layers = this.scene.effectLayers;
  102017. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  102018. var effectLayer = layers_1[_i];
  102019. effectLayer._rebuild();
  102020. }
  102021. };
  102022. /**
  102023. * Serializes the component data to the specified json object
  102024. * @param serializationObject The object to serialize to
  102025. */
  102026. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  102027. // Effect layers
  102028. serializationObject.effectLayers = [];
  102029. var layers = this.scene.effectLayers;
  102030. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  102031. var effectLayer = layers_2[_i];
  102032. if (effectLayer.serialize) {
  102033. serializationObject.effectLayers.push(effectLayer.serialize());
  102034. }
  102035. }
  102036. };
  102037. /**
  102038. * Adds all the element from the container to the scene
  102039. * @param container the container holding the elements
  102040. */
  102041. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  102042. var _this = this;
  102043. if (!container.effectLayers) {
  102044. return;
  102045. }
  102046. container.effectLayers.forEach(function (o) {
  102047. _this.scene.addEffectLayer(o);
  102048. });
  102049. };
  102050. /**
  102051. * Removes all the elements in the container from the scene
  102052. * @param container contains the elements to remove
  102053. */
  102054. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  102055. var _this = this;
  102056. if (!container.effectLayers) {
  102057. return;
  102058. }
  102059. container.effectLayers.forEach(function (o) {
  102060. _this.scene.removeEffectLayer(o);
  102061. });
  102062. };
  102063. /**
  102064. * Disposes the component and the associated ressources.
  102065. */
  102066. EffectLayerSceneComponent.prototype.dispose = function () {
  102067. var layers = this.scene.effectLayers;
  102068. while (layers.length) {
  102069. layers[0].dispose();
  102070. }
  102071. };
  102072. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  102073. var layers = this.scene.effectLayers;
  102074. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  102075. var layer = layers_3[_i];
  102076. if (!layer.hasMesh(mesh)) {
  102077. continue;
  102078. }
  102079. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  102080. var subMesh = _b[_a];
  102081. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  102082. return false;
  102083. }
  102084. }
  102085. }
  102086. return true;
  102087. };
  102088. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  102089. this._renderEffects = false;
  102090. this._needStencil = false;
  102091. var layers = this.scene.effectLayers;
  102092. if (layers && layers.length > 0) {
  102093. this._previousStencilState = this._engine.getStencilBuffer();
  102094. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  102095. var effectLayer = layers_4[_i];
  102096. if (effectLayer.shouldRender() &&
  102097. (!effectLayer.camera ||
  102098. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  102099. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  102100. this._renderEffects = true;
  102101. this._needStencil = this._needStencil || effectLayer.needStencil();
  102102. var renderTarget = effectLayer._mainTexture;
  102103. if (renderTarget._shouldRender()) {
  102104. this.scene.incrementRenderId();
  102105. renderTarget.render(false, false);
  102106. }
  102107. }
  102108. }
  102109. this.scene.incrementRenderId();
  102110. }
  102111. };
  102112. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  102113. // Activate effect Layer stencil
  102114. if (this._needStencil) {
  102115. this._engine.setStencilBuffer(true);
  102116. }
  102117. };
  102118. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  102119. // Restore effect Layer stencil
  102120. if (this._needStencil) {
  102121. this._engine.setStencilBuffer(this._previousStencilState);
  102122. }
  102123. };
  102124. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  102125. if (this._renderEffects) {
  102126. this._engine.setDepthBuffer(false);
  102127. var layers = this.scene.effectLayers;
  102128. for (var i = 0; i < layers.length; i++) {
  102129. var effectLayer = layers[i];
  102130. if (effectLayer.renderingGroupId === renderingGroupId) {
  102131. if (effectLayer.shouldRender()) {
  102132. effectLayer.render();
  102133. }
  102134. }
  102135. }
  102136. this._engine.setDepthBuffer(true);
  102137. }
  102138. };
  102139. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  102140. if (this._renderEffects) {
  102141. this._draw(-1);
  102142. }
  102143. };
  102144. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  102145. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  102146. this._draw(index);
  102147. }
  102148. };
  102149. return EffectLayerSceneComponent;
  102150. }());
  102151. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  102152. })(BABYLON || (BABYLON = {}));
  102153. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  102154. var __assign = (this && this.__assign) || function () {
  102155. __assign = Object.assign || function(t) {
  102156. for (var s, i = 1, n = arguments.length; i < n; i++) {
  102157. s = arguments[i];
  102158. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  102159. t[p] = s[p];
  102160. }
  102161. return t;
  102162. };
  102163. return __assign.apply(this, arguments);
  102164. };
  102165. var BABYLON;
  102166. (function (BABYLON) {
  102167. /**
  102168. * The effect layer Helps adding post process effect blended with the main pass.
  102169. *
  102170. * This can be for instance use to generate glow or higlight effects on the scene.
  102171. *
  102172. * The effect layer class can not be used directly and is intented to inherited from to be
  102173. * customized per effects.
  102174. */
  102175. var EffectLayer = /** @class */ (function () {
  102176. /**
  102177. * Instantiates a new effect Layer and references it in the scene.
  102178. * @param name The name of the layer
  102179. * @param scene The scene to use the layer in
  102180. */
  102181. function EffectLayer(
  102182. /** The Friendly of the effect in the scene */
  102183. name, scene) {
  102184. this._vertexBuffers = {};
  102185. this._maxSize = 0;
  102186. this._mainTextureDesiredSize = { width: 0, height: 0 };
  102187. this._shouldRender = true;
  102188. this._postProcesses = [];
  102189. this._textures = [];
  102190. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  102191. /**
  102192. * The clear color of the texture used to generate the glow map.
  102193. */
  102194. this.neutralColor = new BABYLON.Color4();
  102195. /**
  102196. * Specifies wether the highlight layer is enabled or not.
  102197. */
  102198. this.isEnabled = true;
  102199. /**
  102200. * An event triggered when the effect layer has been disposed.
  102201. */
  102202. this.onDisposeObservable = new BABYLON.Observable();
  102203. /**
  102204. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  102205. */
  102206. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  102207. /**
  102208. * An event triggered when the generated texture is being merged in the scene.
  102209. */
  102210. this.onBeforeComposeObservable = new BABYLON.Observable();
  102211. /**
  102212. * An event triggered when the generated texture has been merged in the scene.
  102213. */
  102214. this.onAfterComposeObservable = new BABYLON.Observable();
  102215. /**
  102216. * An event triggered when the efffect layer changes its size.
  102217. */
  102218. this.onSizeChangedObservable = new BABYLON.Observable();
  102219. this.name = name;
  102220. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  102221. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  102222. if (!component) {
  102223. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  102224. this._scene._addComponent(component);
  102225. }
  102226. this._engine = this._scene.getEngine();
  102227. this._maxSize = this._engine.getCaps().maxTextureSize;
  102228. this._scene.effectLayers.push(this);
  102229. // Generate Buffers
  102230. this._generateIndexBuffer();
  102231. this._genrateVertexBuffer();
  102232. }
  102233. Object.defineProperty(EffectLayer.prototype, "camera", {
  102234. /**
  102235. * Gets the camera attached to the layer.
  102236. */
  102237. get: function () {
  102238. return this._effectLayerOptions.camera;
  102239. },
  102240. enumerable: true,
  102241. configurable: true
  102242. });
  102243. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  102244. /**
  102245. * Gets the rendering group id the layer should render in.
  102246. */
  102247. get: function () {
  102248. return this._effectLayerOptions.renderingGroupId;
  102249. },
  102250. enumerable: true,
  102251. configurable: true
  102252. });
  102253. /**
  102254. * Initializes the effect layer with the required options.
  102255. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  102256. */
  102257. EffectLayer.prototype._init = function (options) {
  102258. // Adapt options
  102259. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  102260. this._setMainTextureSize();
  102261. this._createMainTexture();
  102262. this._createTextureAndPostProcesses();
  102263. this._mergeEffect = this._createMergeEffect();
  102264. };
  102265. /**
  102266. * Generates the index buffer of the full screen quad blending to the main canvas.
  102267. */
  102268. EffectLayer.prototype._generateIndexBuffer = function () {
  102269. // Indices
  102270. var indices = [];
  102271. indices.push(0);
  102272. indices.push(1);
  102273. indices.push(2);
  102274. indices.push(0);
  102275. indices.push(2);
  102276. indices.push(3);
  102277. this._indexBuffer = this._engine.createIndexBuffer(indices);
  102278. };
  102279. /**
  102280. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  102281. */
  102282. EffectLayer.prototype._genrateVertexBuffer = function () {
  102283. // VBO
  102284. var vertices = [];
  102285. vertices.push(1, 1);
  102286. vertices.push(-1, 1);
  102287. vertices.push(-1, -1);
  102288. vertices.push(1, -1);
  102289. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  102290. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  102291. };
  102292. /**
  102293. * Sets the main texture desired size which is the closest power of two
  102294. * of the engine canvas size.
  102295. */
  102296. EffectLayer.prototype._setMainTextureSize = function () {
  102297. if (this._effectLayerOptions.mainTextureFixedSize) {
  102298. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  102299. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  102300. }
  102301. else {
  102302. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  102303. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  102304. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  102305. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  102306. }
  102307. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  102308. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  102309. };
  102310. /**
  102311. * Creates the main texture for the effect layer.
  102312. */
  102313. EffectLayer.prototype._createMainTexture = function () {
  102314. var _this = this;
  102315. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  102316. width: this._mainTextureDesiredSize.width,
  102317. height: this._mainTextureDesiredSize.height
  102318. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  102319. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  102320. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102321. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102322. this._mainTexture.anisotropicFilteringLevel = 1;
  102323. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102324. this._mainTexture.renderParticles = false;
  102325. this._mainTexture.renderList = null;
  102326. this._mainTexture.ignoreCameraViewport = true;
  102327. // Custom render function
  102328. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  102329. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  102330. var index;
  102331. var engine = _this._scene.getEngine();
  102332. if (depthOnlySubMeshes.length) {
  102333. engine.setColorWrite(false);
  102334. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  102335. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  102336. }
  102337. engine.setColorWrite(true);
  102338. }
  102339. for (index = 0; index < opaqueSubMeshes.length; index++) {
  102340. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  102341. }
  102342. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  102343. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  102344. }
  102345. for (index = 0; index < transparentSubMeshes.length; index++) {
  102346. _this._renderSubMesh(transparentSubMeshes.data[index]);
  102347. }
  102348. };
  102349. this._mainTexture.onClearObservable.add(function (engine) {
  102350. engine.clear(_this.neutralColor, true, true, true);
  102351. });
  102352. };
  102353. /**
  102354. * Checks for the readiness of the element composing the layer.
  102355. * @param subMesh the mesh to check for
  102356. * @param useInstances specify wether or not to use instances to render the mesh
  102357. * @param emissiveTexture the associated emissive texture used to generate the glow
  102358. * @return true if ready otherwise, false
  102359. */
  102360. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  102361. var material = subMesh.getMaterial();
  102362. if (!material) {
  102363. return false;
  102364. }
  102365. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  102366. return false;
  102367. }
  102368. var defines = [];
  102369. var attribs = [BABYLON.VertexBuffer.PositionKind];
  102370. var mesh = subMesh.getMesh();
  102371. var uv1 = false;
  102372. var uv2 = false;
  102373. // Alpha test
  102374. if (material && material.needAlphaTesting()) {
  102375. var alphaTexture = material.getAlphaTestTexture();
  102376. if (alphaTexture) {
  102377. defines.push("#define ALPHATEST");
  102378. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  102379. alphaTexture.coordinatesIndex === 1) {
  102380. defines.push("#define DIFFUSEUV2");
  102381. uv2 = true;
  102382. }
  102383. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  102384. defines.push("#define DIFFUSEUV1");
  102385. uv1 = true;
  102386. }
  102387. }
  102388. }
  102389. // Emissive
  102390. if (emissiveTexture) {
  102391. defines.push("#define EMISSIVE");
  102392. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  102393. emissiveTexture.coordinatesIndex === 1) {
  102394. defines.push("#define EMISSIVEUV2");
  102395. uv2 = true;
  102396. }
  102397. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  102398. defines.push("#define EMISSIVEUV1");
  102399. uv1 = true;
  102400. }
  102401. }
  102402. if (uv1) {
  102403. attribs.push(BABYLON.VertexBuffer.UVKind);
  102404. defines.push("#define UV1");
  102405. }
  102406. if (uv2) {
  102407. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  102408. defines.push("#define UV2");
  102409. }
  102410. // Bones
  102411. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  102412. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  102413. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  102414. if (mesh.numBoneInfluencers > 4) {
  102415. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  102416. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  102417. }
  102418. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  102419. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  102420. }
  102421. else {
  102422. defines.push("#define NUM_BONE_INFLUENCERS 0");
  102423. }
  102424. // Morph targets
  102425. var manager = mesh.morphTargetManager;
  102426. var morphInfluencers = 0;
  102427. if (manager) {
  102428. if (manager.numInfluencers > 0) {
  102429. defines.push("#define MORPHTARGETS");
  102430. morphInfluencers = manager.numInfluencers;
  102431. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  102432. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  102433. }
  102434. }
  102435. // Instances
  102436. if (useInstances) {
  102437. defines.push("#define INSTANCES");
  102438. attribs.push("world0");
  102439. attribs.push("world1");
  102440. attribs.push("world2");
  102441. attribs.push("world3");
  102442. }
  102443. // Get correct effect
  102444. var join = defines.join("\n");
  102445. if (this._cachedDefines !== join) {
  102446. this._cachedDefines = join;
  102447. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  102448. }
  102449. return this._effectLayerMapGenerationEffect.isReady();
  102450. };
  102451. /**
  102452. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  102453. */
  102454. EffectLayer.prototype.render = function () {
  102455. var currentEffect = this._mergeEffect;
  102456. // Check
  102457. if (!currentEffect.isReady())
  102458. return;
  102459. for (var i = 0; i < this._postProcesses.length; i++) {
  102460. if (!this._postProcesses[i].isReady()) {
  102461. return;
  102462. }
  102463. }
  102464. var engine = this._scene.getEngine();
  102465. this.onBeforeComposeObservable.notifyObservers(this);
  102466. // Render
  102467. engine.enableEffect(currentEffect);
  102468. engine.setState(false);
  102469. // VBOs
  102470. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  102471. // Cache
  102472. var previousAlphaMode = engine.getAlphaMode();
  102473. // Go Blend.
  102474. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  102475. // Blends the map on the main canvas.
  102476. this._internalRender(currentEffect);
  102477. // Restore Alpha
  102478. engine.setAlphaMode(previousAlphaMode);
  102479. this.onAfterComposeObservable.notifyObservers(this);
  102480. // Handle size changes.
  102481. var size = this._mainTexture.getSize();
  102482. this._setMainTextureSize();
  102483. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  102484. // Recreate RTT and post processes on size change.
  102485. this.onSizeChangedObservable.notifyObservers(this);
  102486. this._disposeTextureAndPostProcesses();
  102487. this._createMainTexture();
  102488. this._createTextureAndPostProcesses();
  102489. }
  102490. };
  102491. /**
  102492. * Determine if a given mesh will be used in the current effect.
  102493. * @param mesh mesh to test
  102494. * @returns true if the mesh will be used
  102495. */
  102496. EffectLayer.prototype.hasMesh = function (mesh) {
  102497. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  102498. return true;
  102499. }
  102500. return false;
  102501. };
  102502. /**
  102503. * Returns true if the layer contains information to display, otherwise false.
  102504. * @returns true if the glow layer should be rendered
  102505. */
  102506. EffectLayer.prototype.shouldRender = function () {
  102507. return this.isEnabled && this._shouldRender;
  102508. };
  102509. /**
  102510. * Returns true if the mesh should render, otherwise false.
  102511. * @param mesh The mesh to render
  102512. * @returns true if it should render otherwise false
  102513. */
  102514. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  102515. return true;
  102516. };
  102517. /**
  102518. * Returns true if the mesh should render, otherwise false.
  102519. * @param mesh The mesh to render
  102520. * @returns true if it should render otherwise false
  102521. */
  102522. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  102523. return true;
  102524. };
  102525. /**
  102526. * Renders the submesh passed in parameter to the generation map.
  102527. */
  102528. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  102529. var _this = this;
  102530. if (!this.shouldRender()) {
  102531. return;
  102532. }
  102533. var material = subMesh.getMaterial();
  102534. var mesh = subMesh.getRenderingMesh();
  102535. var scene = this._scene;
  102536. var engine = scene.getEngine();
  102537. if (!material) {
  102538. return;
  102539. }
  102540. // Do not block in blend mode.
  102541. if (material.needAlphaBlendingForMesh(mesh)) {
  102542. return;
  102543. }
  102544. // Culling
  102545. engine.setState(material.backFaceCulling);
  102546. // Managing instances
  102547. var batch = mesh._getInstancesRenderList(subMesh._id);
  102548. if (batch.mustReturn) {
  102549. return;
  102550. }
  102551. // Early Exit per mesh
  102552. if (!this._shouldRenderMesh(mesh)) {
  102553. return;
  102554. }
  102555. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  102556. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  102557. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  102558. engine.enableEffect(this._effectLayerMapGenerationEffect);
  102559. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  102560. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  102561. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  102562. // Alpha test
  102563. if (material && material.needAlphaTesting()) {
  102564. var alphaTexture = material.getAlphaTestTexture();
  102565. if (alphaTexture) {
  102566. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  102567. var textureMatrix = alphaTexture.getTextureMatrix();
  102568. if (textureMatrix) {
  102569. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  102570. }
  102571. }
  102572. }
  102573. // Glow emissive only
  102574. if (this._emissiveTextureAndColor.texture) {
  102575. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  102576. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  102577. }
  102578. // Bones
  102579. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  102580. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  102581. }
  102582. // Morph targets
  102583. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  102584. // Draw
  102585. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  102586. }
  102587. else {
  102588. // Need to reset refresh rate of the main map
  102589. this._mainTexture.resetRefreshCounter();
  102590. }
  102591. };
  102592. /**
  102593. * Rebuild the required buffers.
  102594. * @hidden Internal use only.
  102595. */
  102596. EffectLayer.prototype._rebuild = function () {
  102597. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102598. if (vb) {
  102599. vb._rebuild();
  102600. }
  102601. this._generateIndexBuffer();
  102602. };
  102603. /**
  102604. * Dispose only the render target textures and post process.
  102605. */
  102606. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  102607. this._mainTexture.dispose();
  102608. for (var i = 0; i < this._postProcesses.length; i++) {
  102609. if (this._postProcesses[i]) {
  102610. this._postProcesses[i].dispose();
  102611. }
  102612. }
  102613. this._postProcesses = [];
  102614. for (var i = 0; i < this._textures.length; i++) {
  102615. if (this._textures[i]) {
  102616. this._textures[i].dispose();
  102617. }
  102618. }
  102619. this._textures = [];
  102620. };
  102621. /**
  102622. * Dispose the highlight layer and free resources.
  102623. */
  102624. EffectLayer.prototype.dispose = function () {
  102625. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102626. if (vertexBuffer) {
  102627. vertexBuffer.dispose();
  102628. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  102629. }
  102630. if (this._indexBuffer) {
  102631. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  102632. this._indexBuffer = null;
  102633. }
  102634. // Clean textures and post processes
  102635. this._disposeTextureAndPostProcesses();
  102636. // Remove from scene
  102637. var index = this._scene.effectLayers.indexOf(this, 0);
  102638. if (index > -1) {
  102639. this._scene.effectLayers.splice(index, 1);
  102640. }
  102641. // Callback
  102642. this.onDisposeObservable.notifyObservers(this);
  102643. this.onDisposeObservable.clear();
  102644. this.onBeforeRenderMainTextureObservable.clear();
  102645. this.onBeforeComposeObservable.clear();
  102646. this.onAfterComposeObservable.clear();
  102647. this.onSizeChangedObservable.clear();
  102648. };
  102649. /**
  102650. * Gets the class name of the effect layer
  102651. * @returns the string with the class name of the effect layer
  102652. */
  102653. EffectLayer.prototype.getClassName = function () {
  102654. return "EffectLayer";
  102655. };
  102656. /**
  102657. * Creates an effect layer from parsed effect layer data
  102658. * @param parsedEffectLayer defines effect layer data
  102659. * @param scene defines the current scene
  102660. * @param rootUrl defines the root URL containing the effect layer information
  102661. * @returns a parsed effect Layer
  102662. */
  102663. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  102664. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  102665. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  102666. };
  102667. __decorate([
  102668. BABYLON.serialize()
  102669. ], EffectLayer.prototype, "name", void 0);
  102670. __decorate([
  102671. BABYLON.serializeAsColor4()
  102672. ], EffectLayer.prototype, "neutralColor", void 0);
  102673. __decorate([
  102674. BABYLON.serialize()
  102675. ], EffectLayer.prototype, "isEnabled", void 0);
  102676. __decorate([
  102677. BABYLON.serializeAsCameraReference()
  102678. ], EffectLayer.prototype, "camera", null);
  102679. __decorate([
  102680. BABYLON.serialize()
  102681. ], EffectLayer.prototype, "renderingGroupId", null);
  102682. return EffectLayer;
  102683. }());
  102684. BABYLON.EffectLayer = EffectLayer;
  102685. })(BABYLON || (BABYLON = {}));
  102686. //# sourceMappingURL=babylon.effectLayer.js.map
  102687. var BABYLON;
  102688. (function (BABYLON) {
  102689. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  102690. for (var index = 0; index < this.effectLayers.length; index++) {
  102691. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  102692. return this.effectLayers[index];
  102693. }
  102694. }
  102695. return null;
  102696. };
  102697. /**
  102698. * Special Glow Blur post process only blurring the alpha channel
  102699. * It enforces keeping the most luminous color in the color channel.
  102700. */
  102701. var GlowBlurPostProcess = /** @class */ (function (_super) {
  102702. __extends(GlowBlurPostProcess, _super);
  102703. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  102704. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  102705. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  102706. _this.direction = direction;
  102707. _this.kernel = kernel;
  102708. _this.onApplyObservable.add(function (effect) {
  102709. effect.setFloat2("screenSize", _this.width, _this.height);
  102710. effect.setVector2("direction", _this.direction);
  102711. effect.setFloat("blurWidth", _this.kernel);
  102712. });
  102713. return _this;
  102714. }
  102715. return GlowBlurPostProcess;
  102716. }(BABYLON.PostProcess));
  102717. /**
  102718. * The highlight layer Helps adding a glow effect around a mesh.
  102719. *
  102720. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  102721. * glowy meshes to your scene.
  102722. *
  102723. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  102724. */
  102725. var HighlightLayer = /** @class */ (function (_super) {
  102726. __extends(HighlightLayer, _super);
  102727. /**
  102728. * Instantiates a new highlight Layer and references it to the scene..
  102729. * @param name The name of the layer
  102730. * @param scene The scene to use the layer in
  102731. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  102732. */
  102733. function HighlightLayer(name, scene, options) {
  102734. var _this = _super.call(this, name, scene) || this;
  102735. _this.name = name;
  102736. /**
  102737. * Specifies whether or not the inner glow is ACTIVE in the layer.
  102738. */
  102739. _this.innerGlow = true;
  102740. /**
  102741. * Specifies whether or not the outer glow is ACTIVE in the layer.
  102742. */
  102743. _this.outerGlow = true;
  102744. /**
  102745. * An event triggered when the highlight layer is being blurred.
  102746. */
  102747. _this.onBeforeBlurObservable = new BABYLON.Observable();
  102748. /**
  102749. * An event triggered when the highlight layer has been blurred.
  102750. */
  102751. _this.onAfterBlurObservable = new BABYLON.Observable();
  102752. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  102753. _this._meshes = {};
  102754. _this._excludedMeshes = {};
  102755. _this.neutralColor = HighlightLayer.NeutralColor;
  102756. // Warn on stencil
  102757. if (!_this._engine.isStencilEnable) {
  102758. 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 }");
  102759. }
  102760. // Adapt options
  102761. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  102762. // Initialize the layer
  102763. _this._init({
  102764. alphaBlendingMode: _this._options.alphaBlendingMode,
  102765. camera: _this._options.camera,
  102766. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  102767. mainTextureRatio: _this._options.mainTextureRatio,
  102768. renderingGroupId: _this._options.renderingGroupId
  102769. });
  102770. // Do not render as long as no meshes have been added
  102771. _this._shouldRender = false;
  102772. return _this;
  102773. }
  102774. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  102775. /**
  102776. * Gets the horizontal size of the blur.
  102777. */
  102778. get: function () {
  102779. return this._horizontalBlurPostprocess.kernel;
  102780. },
  102781. /**
  102782. * Specifies the horizontal size of the blur.
  102783. */
  102784. set: function (value) {
  102785. this._horizontalBlurPostprocess.kernel = value;
  102786. },
  102787. enumerable: true,
  102788. configurable: true
  102789. });
  102790. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  102791. /**
  102792. * Gets the vertical size of the blur.
  102793. */
  102794. get: function () {
  102795. return this._verticalBlurPostprocess.kernel;
  102796. },
  102797. /**
  102798. * Specifies the vertical size of the blur.
  102799. */
  102800. set: function (value) {
  102801. this._verticalBlurPostprocess.kernel = value;
  102802. },
  102803. enumerable: true,
  102804. configurable: true
  102805. });
  102806. /**
  102807. * Get the effect name of the layer.
  102808. * @return The effect name
  102809. */
  102810. HighlightLayer.prototype.getEffectName = function () {
  102811. return HighlightLayer.EffectName;
  102812. };
  102813. /**
  102814. * Create the merge effect. This is the shader use to blit the information back
  102815. * to the main canvas at the end of the scene rendering.
  102816. */
  102817. HighlightLayer.prototype._createMergeEffect = function () {
  102818. // Effect
  102819. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  102820. };
  102821. /**
  102822. * Creates the render target textures and post processes used in the highlight layer.
  102823. */
  102824. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  102825. var _this = this;
  102826. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  102827. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  102828. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  102829. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  102830. var textureType = 0;
  102831. if (this._engine.getCaps().textureHalfFloatRender) {
  102832. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  102833. }
  102834. else {
  102835. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  102836. }
  102837. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  102838. width: blurTextureWidth,
  102839. height: blurTextureHeight
  102840. }, this._scene, false, true, textureType);
  102841. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102842. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102843. this._blurTexture.anisotropicFilteringLevel = 16;
  102844. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  102845. this._blurTexture.renderParticles = false;
  102846. this._blurTexture.ignoreCameraViewport = true;
  102847. this._textures = [this._blurTexture];
  102848. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  102849. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102850. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  102851. effect.setTexture("textureSampler", _this._mainTexture);
  102852. });
  102853. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102854. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  102855. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  102856. });
  102857. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102858. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  102859. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  102860. });
  102861. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  102862. }
  102863. else {
  102864. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  102865. width: blurTextureWidth,
  102866. height: blurTextureHeight
  102867. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102868. this._horizontalBlurPostprocess.width = blurTextureWidth;
  102869. this._horizontalBlurPostprocess.height = blurTextureHeight;
  102870. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  102871. effect.setTexture("textureSampler", _this._mainTexture);
  102872. });
  102873. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  102874. width: blurTextureWidth,
  102875. height: blurTextureHeight
  102876. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102877. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  102878. }
  102879. this._mainTexture.onAfterUnbindObservable.add(function () {
  102880. _this.onBeforeBlurObservable.notifyObservers(_this);
  102881. var internalTexture = _this._blurTexture.getInternalTexture();
  102882. if (internalTexture) {
  102883. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  102884. }
  102885. _this.onAfterBlurObservable.notifyObservers(_this);
  102886. });
  102887. // Prevent autoClear.
  102888. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  102889. };
  102890. /**
  102891. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  102892. */
  102893. HighlightLayer.prototype.needStencil = function () {
  102894. return true;
  102895. };
  102896. /**
  102897. * Checks for the readiness of the element composing the layer.
  102898. * @param subMesh the mesh to check for
  102899. * @param useInstances specify wether or not to use instances to render the mesh
  102900. * @param emissiveTexture the associated emissive texture used to generate the glow
  102901. * @return true if ready otherwise, false
  102902. */
  102903. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  102904. var material = subMesh.getMaterial();
  102905. var mesh = subMesh.getRenderingMesh();
  102906. if (!material || !mesh || !this._meshes) {
  102907. return false;
  102908. }
  102909. var emissiveTexture = null;
  102910. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  102911. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  102912. emissiveTexture = material.emissiveTexture;
  102913. }
  102914. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  102915. };
  102916. /**
  102917. * Implementation specific of rendering the generating effect on the main canvas.
  102918. * @param effect The effect used to render through
  102919. */
  102920. HighlightLayer.prototype._internalRender = function (effect) {
  102921. // Texture
  102922. effect.setTexture("textureSampler", this._blurTexture);
  102923. // Cache
  102924. var engine = this._engine;
  102925. var previousStencilBuffer = engine.getStencilBuffer();
  102926. var previousStencilFunction = engine.getStencilFunction();
  102927. var previousStencilMask = engine.getStencilMask();
  102928. var previousStencilOperationPass = engine.getStencilOperationPass();
  102929. var previousStencilOperationFail = engine.getStencilOperationFail();
  102930. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  102931. var previousStencilReference = engine.getStencilFunctionReference();
  102932. // Stencil operations
  102933. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  102934. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  102935. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  102936. // Draw order
  102937. engine.setStencilMask(0x00);
  102938. engine.setStencilBuffer(true);
  102939. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  102940. // 2 passes inner outer
  102941. if (this.outerGlow) {
  102942. effect.setFloat("offset", 0);
  102943. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  102944. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102945. }
  102946. if (this.innerGlow) {
  102947. effect.setFloat("offset", 1);
  102948. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  102949. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102950. }
  102951. // Restore Cache
  102952. engine.setStencilFunction(previousStencilFunction);
  102953. engine.setStencilMask(previousStencilMask);
  102954. engine.setStencilBuffer(previousStencilBuffer);
  102955. engine.setStencilOperationPass(previousStencilOperationPass);
  102956. engine.setStencilOperationFail(previousStencilOperationFail);
  102957. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  102958. engine.setStencilFunctionReference(previousStencilReference);
  102959. };
  102960. /**
  102961. * Returns true if the layer contains information to display, otherwise false.
  102962. */
  102963. HighlightLayer.prototype.shouldRender = function () {
  102964. if (_super.prototype.shouldRender.call(this)) {
  102965. return this._meshes ? true : false;
  102966. }
  102967. return false;
  102968. };
  102969. /**
  102970. * Returns true if the mesh should render, otherwise false.
  102971. * @param mesh The mesh to render
  102972. * @returns true if it should render otherwise false
  102973. */
  102974. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  102975. // Excluded Mesh
  102976. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  102977. return false;
  102978. }
  102979. ;
  102980. if (!_super.prototype.hasMesh.call(this, mesh)) {
  102981. return false;
  102982. }
  102983. return true;
  102984. };
  102985. /**
  102986. * Sets the required values for both the emissive texture and and the main color.
  102987. */
  102988. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  102989. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  102990. if (highlightLayerMesh) {
  102991. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  102992. }
  102993. else {
  102994. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  102995. }
  102996. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  102997. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  102998. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  102999. }
  103000. else {
  103001. this._emissiveTextureAndColor.texture = null;
  103002. }
  103003. };
  103004. /**
  103005. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  103006. * @param mesh The mesh to exclude from the highlight layer
  103007. */
  103008. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  103009. if (!this._excludedMeshes) {
  103010. return;
  103011. }
  103012. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  103013. if (!meshExcluded) {
  103014. this._excludedMeshes[mesh.uniqueId] = {
  103015. mesh: mesh,
  103016. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  103017. mesh.getEngine().setStencilBuffer(false);
  103018. }),
  103019. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  103020. mesh.getEngine().setStencilBuffer(true);
  103021. }),
  103022. };
  103023. }
  103024. };
  103025. /**
  103026. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  103027. * @param mesh The mesh to highlight
  103028. */
  103029. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  103030. if (!this._excludedMeshes) {
  103031. return;
  103032. }
  103033. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  103034. if (meshExcluded) {
  103035. if (meshExcluded.beforeRender) {
  103036. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  103037. }
  103038. if (meshExcluded.afterRender) {
  103039. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  103040. }
  103041. }
  103042. this._excludedMeshes[mesh.uniqueId] = null;
  103043. };
  103044. /**
  103045. * Determine if a given mesh will be highlighted by the current HighlightLayer
  103046. * @param mesh mesh to test
  103047. * @returns true if the mesh will be highlighted by the current HighlightLayer
  103048. */
  103049. HighlightLayer.prototype.hasMesh = function (mesh) {
  103050. if (!this._meshes) {
  103051. return false;
  103052. }
  103053. if (!_super.prototype.hasMesh.call(this, mesh)) {
  103054. return false;
  103055. }
  103056. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  103057. };
  103058. /**
  103059. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  103060. * @param mesh The mesh to highlight
  103061. * @param color The color of the highlight
  103062. * @param glowEmissiveOnly Extract the glow from the emissive texture
  103063. */
  103064. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  103065. var _this = this;
  103066. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  103067. if (!this._meshes) {
  103068. return;
  103069. }
  103070. var meshHighlight = this._meshes[mesh.uniqueId];
  103071. if (meshHighlight) {
  103072. meshHighlight.color = color;
  103073. }
  103074. else {
  103075. this._meshes[mesh.uniqueId] = {
  103076. mesh: mesh,
  103077. color: color,
  103078. // Lambda required for capture due to Observable this context
  103079. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  103080. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  103081. _this._defaultStencilReference(mesh);
  103082. }
  103083. else {
  103084. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  103085. }
  103086. }),
  103087. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  103088. glowEmissiveOnly: glowEmissiveOnly
  103089. };
  103090. mesh.onDisposeObservable.add(function () {
  103091. _this._disposeMesh(mesh);
  103092. });
  103093. }
  103094. this._shouldRender = true;
  103095. };
  103096. /**
  103097. * Remove a mesh from the highlight layer in order to make it stop glowing.
  103098. * @param mesh The mesh to highlight
  103099. */
  103100. HighlightLayer.prototype.removeMesh = function (mesh) {
  103101. if (!this._meshes) {
  103102. return;
  103103. }
  103104. var meshHighlight = this._meshes[mesh.uniqueId];
  103105. if (meshHighlight) {
  103106. if (meshHighlight.observerHighlight) {
  103107. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  103108. }
  103109. if (meshHighlight.observerDefault) {
  103110. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  103111. }
  103112. delete this._meshes[mesh.uniqueId];
  103113. }
  103114. this._shouldRender = false;
  103115. for (var meshHighlightToCheck in this._meshes) {
  103116. if (this._meshes[meshHighlightToCheck]) {
  103117. this._shouldRender = true;
  103118. break;
  103119. }
  103120. }
  103121. };
  103122. /**
  103123. * Force the stencil to the normal expected value for none glowing parts
  103124. */
  103125. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  103126. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  103127. };
  103128. /**
  103129. * Free any resources and references associated to a mesh.
  103130. * Internal use
  103131. * @param mesh The mesh to free.
  103132. * @hidden
  103133. */
  103134. HighlightLayer.prototype._disposeMesh = function (mesh) {
  103135. this.removeMesh(mesh);
  103136. this.removeExcludedMesh(mesh);
  103137. };
  103138. /**
  103139. * Dispose the highlight layer and free resources.
  103140. */
  103141. HighlightLayer.prototype.dispose = function () {
  103142. if (this._meshes) {
  103143. // Clean mesh references
  103144. for (var id in this._meshes) {
  103145. var meshHighlight = this._meshes[id];
  103146. if (meshHighlight && meshHighlight.mesh) {
  103147. if (meshHighlight.observerHighlight) {
  103148. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  103149. }
  103150. if (meshHighlight.observerDefault) {
  103151. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  103152. }
  103153. }
  103154. }
  103155. this._meshes = null;
  103156. }
  103157. if (this._excludedMeshes) {
  103158. for (var id in this._excludedMeshes) {
  103159. var meshHighlight = this._excludedMeshes[id];
  103160. if (meshHighlight) {
  103161. if (meshHighlight.beforeRender) {
  103162. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  103163. }
  103164. if (meshHighlight.afterRender) {
  103165. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  103166. }
  103167. }
  103168. }
  103169. this._excludedMeshes = null;
  103170. }
  103171. _super.prototype.dispose.call(this);
  103172. };
  103173. /**
  103174. * Gets the class name of the effect layer
  103175. * @returns the string with the class name of the effect layer
  103176. */
  103177. HighlightLayer.prototype.getClassName = function () {
  103178. return "HighlightLayer";
  103179. };
  103180. /**
  103181. * Serializes this Highlight layer
  103182. * @returns a serialized Highlight layer object
  103183. */
  103184. HighlightLayer.prototype.serialize = function () {
  103185. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103186. serializationObject.customType = "BABYLON.HighlightLayer";
  103187. // Highlighted meshes
  103188. serializationObject.meshes = [];
  103189. if (this._meshes) {
  103190. for (var m in this._meshes) {
  103191. var mesh = this._meshes[m];
  103192. if (mesh) {
  103193. serializationObject.meshes.push({
  103194. glowEmissiveOnly: mesh.glowEmissiveOnly,
  103195. color: mesh.color.asArray(),
  103196. meshId: mesh.mesh.id
  103197. });
  103198. }
  103199. }
  103200. }
  103201. // Excluded meshes
  103202. serializationObject.excludedMeshes = [];
  103203. if (this._excludedMeshes) {
  103204. for (var e in this._excludedMeshes) {
  103205. var excludedMesh = this._excludedMeshes[e];
  103206. if (excludedMesh) {
  103207. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  103208. }
  103209. }
  103210. }
  103211. return serializationObject;
  103212. };
  103213. /**
  103214. * Creates a Highlight layer from parsed Highlight layer data
  103215. * @param parsedHightlightLayer defines the Highlight layer data
  103216. * @param scene defines the current scene
  103217. * @param rootUrl defines the root URL containing the Highlight layer information
  103218. * @returns a parsed Highlight layer
  103219. */
  103220. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  103221. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  103222. var index;
  103223. // Excluded meshes
  103224. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  103225. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  103226. if (mesh) {
  103227. hl.addExcludedMesh(mesh);
  103228. }
  103229. }
  103230. // Included meshes
  103231. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  103232. var highlightedMesh = parsedHightlightLayer.meshes[index];
  103233. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  103234. if (mesh) {
  103235. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  103236. }
  103237. }
  103238. return hl;
  103239. };
  103240. /**
  103241. * Effect Name of the highlight layer.
  103242. */
  103243. HighlightLayer.EffectName = "HighlightLayer";
  103244. /**
  103245. * The neutral color used during the preparation of the glow effect.
  103246. * This is black by default as the blend operation is a blend operation.
  103247. */
  103248. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  103249. /**
  103250. * Stencil value used for glowing meshes.
  103251. */
  103252. HighlightLayer.GlowingMeshStencilReference = 0x02;
  103253. /**
  103254. * Stencil value used for the other meshes in the scene.
  103255. */
  103256. HighlightLayer.NormalMeshStencilReference = 0x01;
  103257. __decorate([
  103258. BABYLON.serialize()
  103259. ], HighlightLayer.prototype, "innerGlow", void 0);
  103260. __decorate([
  103261. BABYLON.serialize()
  103262. ], HighlightLayer.prototype, "outerGlow", void 0);
  103263. __decorate([
  103264. BABYLON.serialize()
  103265. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  103266. __decorate([
  103267. BABYLON.serialize()
  103268. ], HighlightLayer.prototype, "blurVerticalSize", null);
  103269. __decorate([
  103270. BABYLON.serialize("options")
  103271. ], HighlightLayer.prototype, "_options", void 0);
  103272. return HighlightLayer;
  103273. }(BABYLON.EffectLayer));
  103274. BABYLON.HighlightLayer = HighlightLayer;
  103275. })(BABYLON || (BABYLON = {}));
  103276. //# sourceMappingURL=babylon.highlightLayer.js.map
  103277. var BABYLON;
  103278. (function (BABYLON) {
  103279. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  103280. for (var index = 0; index < this.effectLayers.length; index++) {
  103281. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  103282. return this.effectLayers[index];
  103283. }
  103284. }
  103285. return null;
  103286. };
  103287. /**
  103288. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  103289. *
  103290. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  103291. * glowy meshes to your scene.
  103292. *
  103293. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  103294. */
  103295. var GlowLayer = /** @class */ (function (_super) {
  103296. __extends(GlowLayer, _super);
  103297. /**
  103298. * Instantiates a new glow Layer and references it to the scene.
  103299. * @param name The name of the layer
  103300. * @param scene The scene to use the layer in
  103301. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  103302. */
  103303. function GlowLayer(name, scene, options) {
  103304. var _this = _super.call(this, name, scene) || this;
  103305. _this._intensity = 1.0;
  103306. _this._includedOnlyMeshes = [];
  103307. _this._excludedMeshes = [];
  103308. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  103309. // Adapt options
  103310. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  103311. // Initialize the layer
  103312. _this._init({
  103313. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  103314. camera: _this._options.camera,
  103315. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  103316. mainTextureRatio: _this._options.mainTextureRatio,
  103317. renderingGroupId: _this._options.renderingGroupId
  103318. });
  103319. return _this;
  103320. }
  103321. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  103322. /**
  103323. * Gets the kernel size of the blur.
  103324. */
  103325. get: function () {
  103326. return this._horizontalBlurPostprocess1.kernel;
  103327. },
  103328. /**
  103329. * Sets the kernel size of the blur.
  103330. */
  103331. set: function (value) {
  103332. this._horizontalBlurPostprocess1.kernel = value;
  103333. this._verticalBlurPostprocess1.kernel = value;
  103334. this._horizontalBlurPostprocess2.kernel = value;
  103335. this._verticalBlurPostprocess2.kernel = value;
  103336. },
  103337. enumerable: true,
  103338. configurable: true
  103339. });
  103340. Object.defineProperty(GlowLayer.prototype, "intensity", {
  103341. /**
  103342. * Gets the glow intensity.
  103343. */
  103344. get: function () {
  103345. return this._intensity;
  103346. },
  103347. /**
  103348. * Sets the glow intensity.
  103349. */
  103350. set: function (value) {
  103351. this._intensity = value;
  103352. },
  103353. enumerable: true,
  103354. configurable: true
  103355. });
  103356. /**
  103357. * Get the effect name of the layer.
  103358. * @return The effect name
  103359. */
  103360. GlowLayer.prototype.getEffectName = function () {
  103361. return GlowLayer.EffectName;
  103362. };
  103363. /**
  103364. * Create the merge effect. This is the shader use to blit the information back
  103365. * to the main canvas at the end of the scene rendering.
  103366. */
  103367. GlowLayer.prototype._createMergeEffect = function () {
  103368. // Effect
  103369. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  103370. };
  103371. /**
  103372. * Creates the render target textures and post processes used in the glow layer.
  103373. */
  103374. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  103375. var _this = this;
  103376. var blurTextureWidth = this._mainTextureDesiredSize.width;
  103377. var blurTextureHeight = this._mainTextureDesiredSize.height;
  103378. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  103379. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  103380. var textureType = 0;
  103381. if (this._engine.getCaps().textureHalfFloatRender) {
  103382. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  103383. }
  103384. else {
  103385. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  103386. }
  103387. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  103388. width: blurTextureWidth,
  103389. height: blurTextureHeight
  103390. }, this._scene, false, true, textureType);
  103391. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103392. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103393. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  103394. this._blurTexture1.renderParticles = false;
  103395. this._blurTexture1.ignoreCameraViewport = true;
  103396. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  103397. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  103398. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  103399. width: blurTextureWidth2,
  103400. height: blurTextureHeight2
  103401. }, this._scene, false, true, textureType);
  103402. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103403. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103404. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  103405. this._blurTexture2.renderParticles = false;
  103406. this._blurTexture2.ignoreCameraViewport = true;
  103407. this._textures = [this._blurTexture1, this._blurTexture2];
  103408. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  103409. width: blurTextureWidth,
  103410. height: blurTextureHeight
  103411. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103412. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  103413. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  103414. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  103415. effect.setTexture("textureSampler", _this._mainTexture);
  103416. });
  103417. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  103418. width: blurTextureWidth,
  103419. height: blurTextureHeight
  103420. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103421. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  103422. width: blurTextureWidth2,
  103423. height: blurTextureHeight2
  103424. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103425. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  103426. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  103427. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  103428. effect.setTexture("textureSampler", _this._blurTexture1);
  103429. });
  103430. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  103431. width: blurTextureWidth2,
  103432. height: blurTextureHeight2
  103433. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103434. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  103435. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  103436. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  103437. this._mainTexture.samples = this._options.mainTextureSamples;
  103438. this._mainTexture.onAfterUnbindObservable.add(function () {
  103439. var internalTexture = _this._blurTexture1.getInternalTexture();
  103440. if (internalTexture) {
  103441. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  103442. internalTexture = _this._blurTexture2.getInternalTexture();
  103443. if (internalTexture) {
  103444. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  103445. }
  103446. }
  103447. });
  103448. // Prevent autoClear.
  103449. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  103450. };
  103451. /**
  103452. * Checks for the readiness of the element composing the layer.
  103453. * @param subMesh the mesh to check for
  103454. * @param useInstances specify wether or not to use instances to render the mesh
  103455. * @param emissiveTexture the associated emissive texture used to generate the glow
  103456. * @return true if ready otherwise, false
  103457. */
  103458. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  103459. var material = subMesh.getMaterial();
  103460. var mesh = subMesh.getRenderingMesh();
  103461. if (!material || !mesh) {
  103462. return false;
  103463. }
  103464. var emissiveTexture = material.emissiveTexture;
  103465. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  103466. };
  103467. /**
  103468. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  103469. */
  103470. GlowLayer.prototype.needStencil = function () {
  103471. return false;
  103472. };
  103473. /**
  103474. * Implementation specific of rendering the generating effect on the main canvas.
  103475. * @param effect The effect used to render through
  103476. */
  103477. GlowLayer.prototype._internalRender = function (effect) {
  103478. // Texture
  103479. effect.setTexture("textureSampler", this._blurTexture1);
  103480. effect.setTexture("textureSampler2", this._blurTexture2);
  103481. effect.setFloat("offset", this._intensity);
  103482. // Cache
  103483. var engine = this._engine;
  103484. var previousStencilBuffer = engine.getStencilBuffer();
  103485. // Draw order
  103486. engine.setStencilBuffer(false);
  103487. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  103488. // Draw order
  103489. engine.setStencilBuffer(previousStencilBuffer);
  103490. };
  103491. /**
  103492. * Sets the required values for both the emissive texture and and the main color.
  103493. */
  103494. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  103495. var textureLevel = 1.0;
  103496. if (this.customEmissiveTextureSelector) {
  103497. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  103498. }
  103499. else {
  103500. if (material) {
  103501. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  103502. if (this._emissiveTextureAndColor.texture) {
  103503. textureLevel = this._emissiveTextureAndColor.texture.level;
  103504. }
  103505. }
  103506. else {
  103507. this._emissiveTextureAndColor.texture = null;
  103508. }
  103509. }
  103510. if (this.customEmissiveColorSelector) {
  103511. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  103512. }
  103513. else {
  103514. if (material.emissiveColor) {
  103515. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  103516. }
  103517. else {
  103518. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  103519. }
  103520. }
  103521. };
  103522. /**
  103523. * Returns true if the mesh should render, otherwise false.
  103524. * @param mesh The mesh to render
  103525. * @returns true if it should render otherwise false
  103526. */
  103527. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  103528. return this.hasMesh(mesh);
  103529. };
  103530. /**
  103531. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  103532. * @param mesh The mesh to exclude from the glow layer
  103533. */
  103534. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  103535. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  103536. this._excludedMeshes.push(mesh.uniqueId);
  103537. }
  103538. };
  103539. /**
  103540. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  103541. * @param mesh The mesh to remove
  103542. */
  103543. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  103544. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  103545. if (index !== -1) {
  103546. this._excludedMeshes.splice(index, 1);
  103547. }
  103548. };
  103549. /**
  103550. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  103551. * @param mesh The mesh to include in the glow layer
  103552. */
  103553. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  103554. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  103555. this._includedOnlyMeshes.push(mesh.uniqueId);
  103556. }
  103557. };
  103558. /**
  103559. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  103560. * @param mesh The mesh to remove
  103561. */
  103562. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  103563. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  103564. if (index !== -1) {
  103565. this._includedOnlyMeshes.splice(index, 1);
  103566. }
  103567. };
  103568. /**
  103569. * Determine if a given mesh will be used in the glow layer
  103570. * @param mesh The mesh to test
  103571. * @returns true if the mesh will be highlighted by the current glow layer
  103572. */
  103573. GlowLayer.prototype.hasMesh = function (mesh) {
  103574. if (!_super.prototype.hasMesh.call(this, mesh)) {
  103575. return false;
  103576. }
  103577. // Included Mesh
  103578. if (this._includedOnlyMeshes.length) {
  103579. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  103580. }
  103581. ;
  103582. // Excluded Mesh
  103583. if (this._excludedMeshes.length) {
  103584. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  103585. }
  103586. ;
  103587. return true;
  103588. };
  103589. /**
  103590. * Free any resources and references associated to a mesh.
  103591. * Internal use
  103592. * @param mesh The mesh to free.
  103593. * @hidden
  103594. */
  103595. GlowLayer.prototype._disposeMesh = function (mesh) {
  103596. this.removeIncludedOnlyMesh(mesh);
  103597. this.removeExcludedMesh(mesh);
  103598. };
  103599. /**
  103600. * Gets the class name of the effect layer
  103601. * @returns the string with the class name of the effect layer
  103602. */
  103603. GlowLayer.prototype.getClassName = function () {
  103604. return "GlowLayer";
  103605. };
  103606. /**
  103607. * Serializes this glow layer
  103608. * @returns a serialized glow layer object
  103609. */
  103610. GlowLayer.prototype.serialize = function () {
  103611. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103612. serializationObject.customType = "BABYLON.GlowLayer";
  103613. var index;
  103614. // Included meshes
  103615. serializationObject.includedMeshes = [];
  103616. if (this._includedOnlyMeshes.length) {
  103617. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  103618. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  103619. if (mesh) {
  103620. serializationObject.includedMeshes.push(mesh.id);
  103621. }
  103622. }
  103623. }
  103624. // Excluded meshes
  103625. serializationObject.excludedMeshes = [];
  103626. if (this._excludedMeshes.length) {
  103627. for (index = 0; index < this._excludedMeshes.length; index++) {
  103628. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  103629. if (mesh) {
  103630. serializationObject.excludedMeshes.push(mesh.id);
  103631. }
  103632. }
  103633. }
  103634. return serializationObject;
  103635. };
  103636. /**
  103637. * Creates a Glow Layer from parsed glow layer data
  103638. * @param parsedGlowLayer defines glow layer data
  103639. * @param scene defines the current scene
  103640. * @param rootUrl defines the root URL containing the glow layer information
  103641. * @returns a parsed Glow Layer
  103642. */
  103643. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  103644. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  103645. var index;
  103646. // Excluded meshes
  103647. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  103648. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  103649. if (mesh) {
  103650. gl.addExcludedMesh(mesh);
  103651. }
  103652. }
  103653. // Included meshes
  103654. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  103655. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  103656. if (mesh) {
  103657. gl.addIncludedOnlyMesh(mesh);
  103658. }
  103659. }
  103660. return gl;
  103661. };
  103662. /**
  103663. * Effect Name of the layer.
  103664. */
  103665. GlowLayer.EffectName = "GlowLayer";
  103666. /**
  103667. * The default blur kernel size used for the glow.
  103668. */
  103669. GlowLayer.DefaultBlurKernelSize = 32;
  103670. /**
  103671. * The default texture size ratio used for the glow.
  103672. */
  103673. GlowLayer.DefaultTextureRatio = 0.5;
  103674. __decorate([
  103675. BABYLON.serialize()
  103676. ], GlowLayer.prototype, "blurKernelSize", null);
  103677. __decorate([
  103678. BABYLON.serialize()
  103679. ], GlowLayer.prototype, "intensity", null);
  103680. __decorate([
  103681. BABYLON.serialize("options")
  103682. ], GlowLayer.prototype, "_options", void 0);
  103683. return GlowLayer;
  103684. }(BABYLON.EffectLayer));
  103685. BABYLON.GlowLayer = GlowLayer;
  103686. })(BABYLON || (BABYLON = {}));
  103687. //# sourceMappingURL=babylon.glowLayer.js.map
  103688. var BABYLON;
  103689. (function (BABYLON) {
  103690. /**
  103691. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  103692. */
  103693. var AssetTaskState;
  103694. (function (AssetTaskState) {
  103695. /**
  103696. * Initialization
  103697. */
  103698. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  103699. /**
  103700. * Running
  103701. */
  103702. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  103703. /**
  103704. * Done
  103705. */
  103706. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  103707. /**
  103708. * Error
  103709. */
  103710. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  103711. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  103712. /**
  103713. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  103714. */
  103715. var AbstractAssetTask = /** @class */ (function () {
  103716. /**
  103717. * Creates a new {BABYLON.AssetsManager}
  103718. * @param name defines the name of the task
  103719. */
  103720. function AbstractAssetTask(
  103721. /**
  103722. * Task name
  103723. */ name) {
  103724. this.name = name;
  103725. this._isCompleted = false;
  103726. this._taskState = AssetTaskState.INIT;
  103727. }
  103728. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  103729. /**
  103730. * Get if the task is completed
  103731. */
  103732. get: function () {
  103733. return this._isCompleted;
  103734. },
  103735. enumerable: true,
  103736. configurable: true
  103737. });
  103738. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  103739. /**
  103740. * Gets the current state of the task
  103741. */
  103742. get: function () {
  103743. return this._taskState;
  103744. },
  103745. enumerable: true,
  103746. configurable: true
  103747. });
  103748. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  103749. /**
  103750. * Gets the current error object (if task is in error)
  103751. */
  103752. get: function () {
  103753. return this._errorObject;
  103754. },
  103755. enumerable: true,
  103756. configurable: true
  103757. });
  103758. /**
  103759. * Internal only
  103760. * @hidden
  103761. */
  103762. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  103763. if (this._errorObject) {
  103764. return;
  103765. }
  103766. this._errorObject = {
  103767. message: message,
  103768. exception: exception
  103769. };
  103770. };
  103771. /**
  103772. * Execute the current task
  103773. * @param scene defines the scene where you want your assets to be loaded
  103774. * @param onSuccess is a callback called when the task is successfully executed
  103775. * @param onError is a callback called if an error occurs
  103776. */
  103777. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  103778. var _this = this;
  103779. this._taskState = AssetTaskState.RUNNING;
  103780. this.runTask(scene, function () {
  103781. _this.onDoneCallback(onSuccess, onError);
  103782. }, function (msg, exception) {
  103783. _this.onErrorCallback(onError, msg, exception);
  103784. });
  103785. };
  103786. /**
  103787. * Execute the current task
  103788. * @param scene defines the scene where you want your assets to be loaded
  103789. * @param onSuccess is a callback called when the task is successfully executed
  103790. * @param onError is a callback called if an error occurs
  103791. */
  103792. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103793. throw new Error("runTask is not implemented");
  103794. };
  103795. /**
  103796. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  103797. * This can be used with failed tasks that have the reason for failure fixed.
  103798. */
  103799. AbstractAssetTask.prototype.reset = function () {
  103800. this._taskState = AssetTaskState.INIT;
  103801. };
  103802. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  103803. this._taskState = AssetTaskState.ERROR;
  103804. this._errorObject = {
  103805. message: message,
  103806. exception: exception
  103807. };
  103808. if (this.onError) {
  103809. this.onError(this, message, exception);
  103810. }
  103811. onError();
  103812. };
  103813. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  103814. try {
  103815. this._taskState = AssetTaskState.DONE;
  103816. this._isCompleted = true;
  103817. if (this.onSuccess) {
  103818. this.onSuccess(this);
  103819. }
  103820. onSuccess();
  103821. }
  103822. catch (e) {
  103823. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  103824. }
  103825. };
  103826. return AbstractAssetTask;
  103827. }());
  103828. BABYLON.AbstractAssetTask = AbstractAssetTask;
  103829. /**
  103830. * Class used to share progress information about assets loading
  103831. */
  103832. var AssetsProgressEvent = /** @class */ (function () {
  103833. /**
  103834. * Creates a {BABYLON.AssetsProgressEvent}
  103835. * @param remainingCount defines the number of remaining tasks to process
  103836. * @param totalCount defines the total number of tasks
  103837. * @param task defines the task that was just processed
  103838. */
  103839. function AssetsProgressEvent(remainingCount, totalCount, task) {
  103840. this.remainingCount = remainingCount;
  103841. this.totalCount = totalCount;
  103842. this.task = task;
  103843. }
  103844. return AssetsProgressEvent;
  103845. }());
  103846. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  103847. /**
  103848. * Define a task used by {BABYLON.AssetsManager} to load meshes
  103849. */
  103850. var MeshAssetTask = /** @class */ (function (_super) {
  103851. __extends(MeshAssetTask, _super);
  103852. /**
  103853. * Creates a new {BABYLON.MeshAssetTask}
  103854. * @param name defines the name of the task
  103855. * @param meshesNames defines the list of mesh's names you want to load
  103856. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  103857. * @param sceneFilename defines the filename of the scene to load from
  103858. */
  103859. function MeshAssetTask(
  103860. /**
  103861. * Defines the name of the task
  103862. */
  103863. name,
  103864. /**
  103865. * Defines the list of mesh's names you want to load
  103866. */
  103867. meshesNames,
  103868. /**
  103869. * Defines the root url to use as a base to load your meshes and associated resources
  103870. */
  103871. rootUrl,
  103872. /**
  103873. * Defines the filename of the scene to load from
  103874. */
  103875. sceneFilename) {
  103876. var _this = _super.call(this, name) || this;
  103877. _this.name = name;
  103878. _this.meshesNames = meshesNames;
  103879. _this.rootUrl = rootUrl;
  103880. _this.sceneFilename = sceneFilename;
  103881. return _this;
  103882. }
  103883. /**
  103884. * Execute the current task
  103885. * @param scene defines the scene where you want your assets to be loaded
  103886. * @param onSuccess is a callback called when the task is successfully executed
  103887. * @param onError is a callback called if an error occurs
  103888. */
  103889. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103890. var _this = this;
  103891. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  103892. _this.loadedMeshes = meshes;
  103893. _this.loadedParticleSystems = particleSystems;
  103894. _this.loadedSkeletons = skeletons;
  103895. onSuccess();
  103896. }, null, function (scene, message, exception) {
  103897. onError(message, exception);
  103898. });
  103899. };
  103900. return MeshAssetTask;
  103901. }(AbstractAssetTask));
  103902. BABYLON.MeshAssetTask = MeshAssetTask;
  103903. /**
  103904. * Define a task used by {BABYLON.AssetsManager} to load text content
  103905. */
  103906. var TextFileAssetTask = /** @class */ (function (_super) {
  103907. __extends(TextFileAssetTask, _super);
  103908. /**
  103909. * Creates a new TextFileAssetTask object
  103910. * @param name defines the name of the task
  103911. * @param url defines the location of the file to load
  103912. */
  103913. function TextFileAssetTask(
  103914. /**
  103915. * Defines the name of the task
  103916. */
  103917. name,
  103918. /**
  103919. * Defines the location of the file to load
  103920. */
  103921. url) {
  103922. var _this = _super.call(this, name) || this;
  103923. _this.name = name;
  103924. _this.url = url;
  103925. return _this;
  103926. }
  103927. /**
  103928. * Execute the current task
  103929. * @param scene defines the scene where you want your assets to be loaded
  103930. * @param onSuccess is a callback called when the task is successfully executed
  103931. * @param onError is a callback called if an error occurs
  103932. */
  103933. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103934. var _this = this;
  103935. scene._loadFile(this.url, function (data) {
  103936. _this.text = data;
  103937. onSuccess();
  103938. }, undefined, false, false, function (request, exception) {
  103939. if (request) {
  103940. onError(request.status + " " + request.statusText, exception);
  103941. }
  103942. });
  103943. };
  103944. return TextFileAssetTask;
  103945. }(AbstractAssetTask));
  103946. BABYLON.TextFileAssetTask = TextFileAssetTask;
  103947. /**
  103948. * Define a task used by {BABYLON.AssetsManager} to load binary data
  103949. */
  103950. var BinaryFileAssetTask = /** @class */ (function (_super) {
  103951. __extends(BinaryFileAssetTask, _super);
  103952. /**
  103953. * Creates a new BinaryFileAssetTask object
  103954. * @param name defines the name of the new task
  103955. * @param url defines the location of the file to load
  103956. */
  103957. function BinaryFileAssetTask(
  103958. /**
  103959. * Defines the name of the task
  103960. */
  103961. name,
  103962. /**
  103963. * Defines the location of the file to load
  103964. */
  103965. url) {
  103966. var _this = _super.call(this, name) || this;
  103967. _this.name = name;
  103968. _this.url = url;
  103969. return _this;
  103970. }
  103971. /**
  103972. * Execute the current task
  103973. * @param scene defines the scene where you want your assets to be loaded
  103974. * @param onSuccess is a callback called when the task is successfully executed
  103975. * @param onError is a callback called if an error occurs
  103976. */
  103977. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103978. var _this = this;
  103979. scene._loadFile(this.url, function (data) {
  103980. _this.data = data;
  103981. onSuccess();
  103982. }, undefined, true, true, function (request, exception) {
  103983. if (request) {
  103984. onError(request.status + " " + request.statusText, exception);
  103985. }
  103986. });
  103987. };
  103988. return BinaryFileAssetTask;
  103989. }(AbstractAssetTask));
  103990. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  103991. /**
  103992. * Define a task used by {BABYLON.AssetsManager} to load images
  103993. */
  103994. var ImageAssetTask = /** @class */ (function (_super) {
  103995. __extends(ImageAssetTask, _super);
  103996. /**
  103997. * Creates a new ImageAssetTask
  103998. * @param name defines the name of the task
  103999. * @param url defines the location of the image to load
  104000. */
  104001. function ImageAssetTask(
  104002. /**
  104003. * Defines the name of the task
  104004. */
  104005. name,
  104006. /**
  104007. * Defines the location of the image to load
  104008. */
  104009. url) {
  104010. var _this = _super.call(this, name) || this;
  104011. _this.name = name;
  104012. _this.url = url;
  104013. return _this;
  104014. }
  104015. /**
  104016. * Execute the current task
  104017. * @param scene defines the scene where you want your assets to be loaded
  104018. * @param onSuccess is a callback called when the task is successfully executed
  104019. * @param onError is a callback called if an error occurs
  104020. */
  104021. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104022. var _this = this;
  104023. var img = new Image();
  104024. BABYLON.Tools.SetCorsBehavior(this.url, img);
  104025. img.onload = function () {
  104026. _this.image = img;
  104027. onSuccess();
  104028. };
  104029. img.onerror = function (err) {
  104030. onError("Error loading image", err);
  104031. };
  104032. img.src = this.url;
  104033. };
  104034. return ImageAssetTask;
  104035. }(AbstractAssetTask));
  104036. BABYLON.ImageAssetTask = ImageAssetTask;
  104037. /**
  104038. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  104039. */
  104040. var TextureAssetTask = /** @class */ (function (_super) {
  104041. __extends(TextureAssetTask, _super);
  104042. /**
  104043. * Creates a new TextureAssetTask object
  104044. * @param name defines the name of the task
  104045. * @param url defines the location of the file to load
  104046. * @param noMipmap defines if mipmap should not be generated (default is false)
  104047. * @param invertY defines if texture must be inverted on Y axis (default is false)
  104048. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  104049. */
  104050. function TextureAssetTask(
  104051. /**
  104052. * Defines the name of the task
  104053. */
  104054. name,
  104055. /**
  104056. * Defines the location of the file to load
  104057. */
  104058. url,
  104059. /**
  104060. * Defines if mipmap should not be generated (default is false)
  104061. */
  104062. noMipmap,
  104063. /**
  104064. * Defines if texture must be inverted on Y axis (default is false)
  104065. */
  104066. invertY,
  104067. /**
  104068. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  104069. */
  104070. samplingMode) {
  104071. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  104072. var _this = _super.call(this, name) || this;
  104073. _this.name = name;
  104074. _this.url = url;
  104075. _this.noMipmap = noMipmap;
  104076. _this.invertY = invertY;
  104077. _this.samplingMode = samplingMode;
  104078. return _this;
  104079. }
  104080. /**
  104081. * Execute the current task
  104082. * @param scene defines the scene where you want your assets to be loaded
  104083. * @param onSuccess is a callback called when the task is successfully executed
  104084. * @param onError is a callback called if an error occurs
  104085. */
  104086. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104087. var onload = function () {
  104088. onSuccess();
  104089. };
  104090. var onerror = function (message, exception) {
  104091. onError(message, exception);
  104092. };
  104093. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  104094. };
  104095. return TextureAssetTask;
  104096. }(AbstractAssetTask));
  104097. BABYLON.TextureAssetTask = TextureAssetTask;
  104098. /**
  104099. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  104100. */
  104101. var CubeTextureAssetTask = /** @class */ (function (_super) {
  104102. __extends(CubeTextureAssetTask, _super);
  104103. /**
  104104. * Creates a new CubeTextureAssetTask
  104105. * @param name defines the name of the task
  104106. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  104107. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  104108. * @param noMipmap defines if mipmaps should not be generated (default is false)
  104109. * @param files defines the explicit list of files (undefined by default)
  104110. */
  104111. function CubeTextureAssetTask(
  104112. /**
  104113. * Defines the name of the task
  104114. */
  104115. name,
  104116. /**
  104117. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  104118. */
  104119. url,
  104120. /**
  104121. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  104122. */
  104123. extensions,
  104124. /**
  104125. * Defines if mipmaps should not be generated (default is false)
  104126. */
  104127. noMipmap,
  104128. /**
  104129. * Defines the explicit list of files (undefined by default)
  104130. */
  104131. files) {
  104132. var _this = _super.call(this, name) || this;
  104133. _this.name = name;
  104134. _this.url = url;
  104135. _this.extensions = extensions;
  104136. _this.noMipmap = noMipmap;
  104137. _this.files = files;
  104138. return _this;
  104139. }
  104140. /**
  104141. * Execute the current task
  104142. * @param scene defines the scene where you want your assets to be loaded
  104143. * @param onSuccess is a callback called when the task is successfully executed
  104144. * @param onError is a callback called if an error occurs
  104145. */
  104146. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104147. var onload = function () {
  104148. onSuccess();
  104149. };
  104150. var onerror = function (message, exception) {
  104151. onError(message, exception);
  104152. };
  104153. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  104154. };
  104155. return CubeTextureAssetTask;
  104156. }(AbstractAssetTask));
  104157. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  104158. /**
  104159. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  104160. */
  104161. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  104162. __extends(HDRCubeTextureAssetTask, _super);
  104163. /**
  104164. * Creates a new HDRCubeTextureAssetTask object
  104165. * @param name defines the name of the task
  104166. * @param url defines the location of the file to load
  104167. * @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.
  104168. * @param noMipmap defines if mipmaps should not be generated (default is false)
  104169. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  104170. * @param gammaSpace 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)
  104171. * @param reserved Internal use only
  104172. */
  104173. function HDRCubeTextureAssetTask(
  104174. /**
  104175. * Defines the name of the task
  104176. */
  104177. name,
  104178. /**
  104179. * Defines the location of the file to load
  104180. */
  104181. url,
  104182. /**
  104183. * Defines the desired size (the more it increases the longer the generation will be)
  104184. */
  104185. size,
  104186. /**
  104187. * Defines if mipmaps should not be generated (default is false)
  104188. */
  104189. noMipmap,
  104190. /**
  104191. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  104192. */
  104193. generateHarmonics,
  104194. /**
  104195. * 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)
  104196. */
  104197. gammaSpace,
  104198. /**
  104199. * Internal Use Only
  104200. */
  104201. reserved) {
  104202. if (noMipmap === void 0) { noMipmap = false; }
  104203. if (generateHarmonics === void 0) { generateHarmonics = true; }
  104204. if (gammaSpace === void 0) { gammaSpace = false; }
  104205. if (reserved === void 0) { reserved = false; }
  104206. var _this = _super.call(this, name) || this;
  104207. _this.name = name;
  104208. _this.url = url;
  104209. _this.size = size;
  104210. _this.noMipmap = noMipmap;
  104211. _this.generateHarmonics = generateHarmonics;
  104212. _this.gammaSpace = gammaSpace;
  104213. _this.reserved = reserved;
  104214. return _this;
  104215. }
  104216. /**
  104217. * Execute the current task
  104218. * @param scene defines the scene where you want your assets to be loaded
  104219. * @param onSuccess is a callback called when the task is successfully executed
  104220. * @param onError is a callback called if an error occurs
  104221. */
  104222. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  104223. var onload = function () {
  104224. onSuccess();
  104225. };
  104226. var onerror = function (message, exception) {
  104227. onError(message, exception);
  104228. };
  104229. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  104230. };
  104231. return HDRCubeTextureAssetTask;
  104232. }(AbstractAssetTask));
  104233. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  104234. /**
  104235. * This class can be used to easily import assets into a scene
  104236. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  104237. */
  104238. var AssetsManager = /** @class */ (function () {
  104239. /**
  104240. * Creates a new AssetsManager
  104241. * @param scene defines the scene to work on
  104242. */
  104243. function AssetsManager(scene) {
  104244. this._isLoading = false;
  104245. this._tasks = new Array();
  104246. this._waitingTasksCount = 0;
  104247. this._totalTasksCount = 0;
  104248. /**
  104249. * Observable called when all tasks are processed
  104250. */
  104251. this.onTaskSuccessObservable = new BABYLON.Observable();
  104252. /**
  104253. * Observable called when a task had an error
  104254. */
  104255. this.onTaskErrorObservable = new BABYLON.Observable();
  104256. /**
  104257. * Observable called when a task is successful
  104258. */
  104259. this.onTasksDoneObservable = new BABYLON.Observable();
  104260. /**
  104261. * Observable called when a task is done (whatever the result is)
  104262. */
  104263. this.onProgressObservable = new BABYLON.Observable();
  104264. /**
  104265. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  104266. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  104267. */
  104268. this.useDefaultLoadingScreen = true;
  104269. this._scene = scene;
  104270. }
  104271. /**
  104272. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  104273. * @param taskName defines the name of the new task
  104274. * @param meshesNames defines the name of meshes to load
  104275. * @param rootUrl defines the root url to use to locate files
  104276. * @param sceneFilename defines the filename of the scene file
  104277. * @returns a new {BABYLON.MeshAssetTask} object
  104278. */
  104279. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  104280. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  104281. this._tasks.push(task);
  104282. return task;
  104283. };
  104284. /**
  104285. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  104286. * @param taskName defines the name of the new task
  104287. * @param url defines the url of the file to load
  104288. * @returns a new {BABYLON.TextFileAssetTask} object
  104289. */
  104290. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  104291. var task = new TextFileAssetTask(taskName, url);
  104292. this._tasks.push(task);
  104293. return task;
  104294. };
  104295. /**
  104296. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  104297. * @param taskName defines the name of the new task
  104298. * @param url defines the url of the file to load
  104299. * @returns a new {BABYLON.BinaryFileAssetTask} object
  104300. */
  104301. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  104302. var task = new BinaryFileAssetTask(taskName, url);
  104303. this._tasks.push(task);
  104304. return task;
  104305. };
  104306. /**
  104307. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  104308. * @param taskName defines the name of the new task
  104309. * @param url defines the url of the file to load
  104310. * @returns a new {BABYLON.ImageAssetTask} object
  104311. */
  104312. AssetsManager.prototype.addImageTask = function (taskName, url) {
  104313. var task = new ImageAssetTask(taskName, url);
  104314. this._tasks.push(task);
  104315. return task;
  104316. };
  104317. /**
  104318. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  104319. * @param taskName defines the name of the new task
  104320. * @param url defines the url of the file to load
  104321. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  104322. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  104323. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  104324. * @returns a new {BABYLON.TextureAssetTask} object
  104325. */
  104326. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  104327. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  104328. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  104329. this._tasks.push(task);
  104330. return task;
  104331. };
  104332. /**
  104333. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  104334. * @param taskName defines the name of the new task
  104335. * @param url defines the url of the file to load
  104336. * @param extensions defines the extension to use to load the cube map (can be null)
  104337. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  104338. * @param files defines the list of files to load (can be null)
  104339. * @returns a new {BABYLON.CubeTextureAssetTask} object
  104340. */
  104341. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  104342. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  104343. this._tasks.push(task);
  104344. return task;
  104345. };
  104346. /**
  104347. *
  104348. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  104349. * @param taskName defines the name of the new task
  104350. * @param url defines the url of the file to load
  104351. * @param size defines the size you want for the cubemap (can be null)
  104352. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  104353. * @param generateHarmonics defines if you want to automatically generate (true by default)
  104354. * @param gammaSpace 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)
  104355. * @param reserved Internal use only
  104356. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  104357. */
  104358. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  104359. if (noMipmap === void 0) { noMipmap = false; }
  104360. if (generateHarmonics === void 0) { generateHarmonics = true; }
  104361. if (gammaSpace === void 0) { gammaSpace = false; }
  104362. if (reserved === void 0) { reserved = false; }
  104363. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  104364. this._tasks.push(task);
  104365. return task;
  104366. };
  104367. /**
  104368. * Remove a task from the assets manager.
  104369. * @param task the task to remove
  104370. */
  104371. AssetsManager.prototype.removeTask = function (task) {
  104372. var index = this._tasks.indexOf(task);
  104373. if (index > -1) {
  104374. this._tasks.splice(index, 1);
  104375. }
  104376. };
  104377. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  104378. this._waitingTasksCount--;
  104379. try {
  104380. if (this.onProgress) {
  104381. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  104382. }
  104383. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  104384. }
  104385. catch (e) {
  104386. BABYLON.Tools.Error("Error running progress callbacks.");
  104387. console.log(e);
  104388. }
  104389. if (this._waitingTasksCount === 0) {
  104390. try {
  104391. if (this.onFinish) {
  104392. this.onFinish(this._tasks);
  104393. }
  104394. // Let's remove successfull tasks
  104395. var currentTasks = this._tasks.slice();
  104396. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  104397. var task = currentTasks_1[_i];
  104398. if (task.taskState === AssetTaskState.DONE) {
  104399. var index = this._tasks.indexOf(task);
  104400. if (index > -1) {
  104401. this._tasks.splice(index, 1);
  104402. }
  104403. }
  104404. }
  104405. this.onTasksDoneObservable.notifyObservers(this._tasks);
  104406. }
  104407. catch (e) {
  104408. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  104409. console.log(e);
  104410. }
  104411. this._isLoading = false;
  104412. this._scene.getEngine().hideLoadingUI();
  104413. }
  104414. };
  104415. AssetsManager.prototype._runTask = function (task) {
  104416. var _this = this;
  104417. var done = function () {
  104418. try {
  104419. if (_this.onTaskSuccess) {
  104420. _this.onTaskSuccess(task);
  104421. }
  104422. _this.onTaskSuccessObservable.notifyObservers(task);
  104423. _this._decreaseWaitingTasksCount(task);
  104424. }
  104425. catch (e) {
  104426. error("Error executing task success callbacks", e);
  104427. }
  104428. };
  104429. var error = function (message, exception) {
  104430. task._setErrorObject(message, exception);
  104431. if (_this.onTaskError) {
  104432. _this.onTaskError(task);
  104433. }
  104434. _this.onTaskErrorObservable.notifyObservers(task);
  104435. _this._decreaseWaitingTasksCount(task);
  104436. };
  104437. task.run(this._scene, done, error);
  104438. };
  104439. /**
  104440. * Reset the {BABYLON.AssetsManager} and remove all tasks
  104441. * @return the current instance of the {BABYLON.AssetsManager}
  104442. */
  104443. AssetsManager.prototype.reset = function () {
  104444. this._isLoading = false;
  104445. this._tasks = new Array();
  104446. return this;
  104447. };
  104448. /**
  104449. * Start the loading process
  104450. * @return the current instance of the {BABYLON.AssetsManager}
  104451. */
  104452. AssetsManager.prototype.load = function () {
  104453. if (this._isLoading) {
  104454. return this;
  104455. }
  104456. this._isLoading = true;
  104457. this._waitingTasksCount = this._tasks.length;
  104458. this._totalTasksCount = this._tasks.length;
  104459. if (this._waitingTasksCount === 0) {
  104460. this._isLoading = false;
  104461. if (this.onFinish) {
  104462. this.onFinish(this._tasks);
  104463. }
  104464. this.onTasksDoneObservable.notifyObservers(this._tasks);
  104465. return this;
  104466. }
  104467. if (this.useDefaultLoadingScreen) {
  104468. this._scene.getEngine().displayLoadingUI();
  104469. }
  104470. for (var index = 0; index < this._tasks.length; index++) {
  104471. var task = this._tasks[index];
  104472. if (task.taskState === AssetTaskState.INIT) {
  104473. this._runTask(task);
  104474. }
  104475. }
  104476. return this;
  104477. };
  104478. return AssetsManager;
  104479. }());
  104480. BABYLON.AssetsManager = AssetsManager;
  104481. })(BABYLON || (BABYLON = {}));
  104482. //# sourceMappingURL=babylon.assetsManager.js.map
  104483. var BABYLON;
  104484. (function (BABYLON) {
  104485. var serializedGeometries = [];
  104486. var serializeGeometry = function (geometry, serializationGeometries) {
  104487. if (serializedGeometries[geometry.id]) {
  104488. return;
  104489. }
  104490. if (geometry.doNotSerialize) {
  104491. return;
  104492. }
  104493. if (geometry instanceof BABYLON.BoxGeometry) {
  104494. serializationGeometries.boxes.push(geometry.serialize());
  104495. }
  104496. else if (geometry instanceof BABYLON.SphereGeometry) {
  104497. serializationGeometries.spheres.push(geometry.serialize());
  104498. }
  104499. else if (geometry instanceof BABYLON.CylinderGeometry) {
  104500. serializationGeometries.cylinders.push(geometry.serialize());
  104501. }
  104502. else if (geometry instanceof BABYLON.TorusGeometry) {
  104503. serializationGeometries.toruses.push(geometry.serialize());
  104504. }
  104505. else if (geometry instanceof BABYLON.GroundGeometry) {
  104506. serializationGeometries.grounds.push(geometry.serialize());
  104507. }
  104508. else if (geometry instanceof BABYLON.Plane) {
  104509. serializationGeometries.planes.push(geometry.serialize());
  104510. }
  104511. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  104512. serializationGeometries.torusKnots.push(geometry.serialize());
  104513. }
  104514. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  104515. throw new Error("Unknown primitive type");
  104516. }
  104517. else {
  104518. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  104519. }
  104520. serializedGeometries[geometry.id] = true;
  104521. };
  104522. var serializeMesh = function (mesh, serializationScene) {
  104523. var serializationObject = {};
  104524. // Geometry
  104525. var geometry = mesh._geometry;
  104526. if (geometry) {
  104527. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  104528. // 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
  104529. serializeGeometry(geometry, serializationScene.geometries);
  104530. }
  104531. }
  104532. // Custom
  104533. if (mesh.serialize) {
  104534. mesh.serialize(serializationObject);
  104535. }
  104536. return serializationObject;
  104537. };
  104538. var finalizeSingleMesh = function (mesh, serializationObject) {
  104539. //only works if the mesh is already loaded
  104540. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  104541. //serialize material
  104542. if (mesh.material) {
  104543. if (mesh.material instanceof BABYLON.MultiMaterial) {
  104544. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  104545. serializationObject.materials = serializationObject.materials || [];
  104546. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  104547. serializationObject.multiMaterials.push(mesh.material.serialize());
  104548. var _loop_1 = function (submaterial) {
  104549. if (submaterial) {
  104550. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  104551. serializationObject.materials.push(submaterial.serialize());
  104552. }
  104553. }
  104554. };
  104555. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  104556. var submaterial = _a[_i];
  104557. _loop_1(submaterial);
  104558. }
  104559. }
  104560. }
  104561. else {
  104562. serializationObject.materials = serializationObject.materials || [];
  104563. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  104564. serializationObject.materials.push(mesh.material.serialize());
  104565. }
  104566. }
  104567. }
  104568. //serialize geometry
  104569. var geometry = mesh._geometry;
  104570. if (geometry) {
  104571. if (!serializationObject.geometries) {
  104572. serializationObject.geometries = {};
  104573. serializationObject.geometries.boxes = [];
  104574. serializationObject.geometries.spheres = [];
  104575. serializationObject.geometries.cylinders = [];
  104576. serializationObject.geometries.toruses = [];
  104577. serializationObject.geometries.grounds = [];
  104578. serializationObject.geometries.planes = [];
  104579. serializationObject.geometries.torusKnots = [];
  104580. serializationObject.geometries.vertexData = [];
  104581. }
  104582. serializeGeometry(geometry, serializationObject.geometries);
  104583. }
  104584. // Skeletons
  104585. if (mesh.skeleton) {
  104586. serializationObject.skeletons = serializationObject.skeletons || [];
  104587. serializationObject.skeletons.push(mesh.skeleton.serialize());
  104588. }
  104589. //serialize the actual mesh
  104590. serializationObject.meshes = serializationObject.meshes || [];
  104591. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  104592. }
  104593. };
  104594. var SceneSerializer = /** @class */ (function () {
  104595. function SceneSerializer() {
  104596. }
  104597. SceneSerializer.ClearCache = function () {
  104598. serializedGeometries = [];
  104599. };
  104600. SceneSerializer.Serialize = function (scene) {
  104601. var serializationObject = {};
  104602. SceneSerializer.ClearCache();
  104603. // Scene
  104604. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  104605. serializationObject.autoClear = scene.autoClear;
  104606. serializationObject.clearColor = scene.clearColor.asArray();
  104607. serializationObject.ambientColor = scene.ambientColor.asArray();
  104608. serializationObject.gravity = scene.gravity.asArray();
  104609. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  104610. serializationObject.workerCollisions = scene.workerCollisions;
  104611. // Fog
  104612. if (scene.fogMode && scene.fogMode !== 0) {
  104613. serializationObject.fogMode = scene.fogMode;
  104614. serializationObject.fogColor = scene.fogColor.asArray();
  104615. serializationObject.fogStart = scene.fogStart;
  104616. serializationObject.fogEnd = scene.fogEnd;
  104617. serializationObject.fogDensity = scene.fogDensity;
  104618. }
  104619. //Physics
  104620. if (scene.isPhysicsEnabled()) {
  104621. var physicEngine = scene.getPhysicsEngine();
  104622. if (physicEngine) {
  104623. serializationObject.physicsEnabled = true;
  104624. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  104625. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  104626. }
  104627. }
  104628. // Metadata
  104629. if (scene.metadata) {
  104630. serializationObject.metadata = scene.metadata;
  104631. }
  104632. // Morph targets
  104633. serializationObject.morphTargetManagers = [];
  104634. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  104635. var abstractMesh = _a[_i];
  104636. var manager = abstractMesh.morphTargetManager;
  104637. if (manager) {
  104638. serializationObject.morphTargetManagers.push(manager.serialize());
  104639. }
  104640. }
  104641. // Lights
  104642. serializationObject.lights = [];
  104643. var index;
  104644. var light;
  104645. for (index = 0; index < scene.lights.length; index++) {
  104646. light = scene.lights[index];
  104647. if (!light.doNotSerialize) {
  104648. serializationObject.lights.push(light.serialize());
  104649. }
  104650. }
  104651. // Cameras
  104652. serializationObject.cameras = [];
  104653. for (index = 0; index < scene.cameras.length; index++) {
  104654. var camera = scene.cameras[index];
  104655. if (!camera.doNotSerialize) {
  104656. serializationObject.cameras.push(camera.serialize());
  104657. }
  104658. }
  104659. if (scene.activeCamera) {
  104660. serializationObject.activeCameraID = scene.activeCamera.id;
  104661. }
  104662. // Animations
  104663. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  104664. // Materials
  104665. serializationObject.materials = [];
  104666. serializationObject.multiMaterials = [];
  104667. var material;
  104668. for (index = 0; index < scene.materials.length; index++) {
  104669. material = scene.materials[index];
  104670. if (!material.doNotSerialize) {
  104671. serializationObject.materials.push(material.serialize());
  104672. }
  104673. }
  104674. // MultiMaterials
  104675. serializationObject.multiMaterials = [];
  104676. for (index = 0; index < scene.multiMaterials.length; index++) {
  104677. var multiMaterial = scene.multiMaterials[index];
  104678. serializationObject.multiMaterials.push(multiMaterial.serialize());
  104679. }
  104680. // Environment texture
  104681. if (scene.environmentTexture) {
  104682. serializationObject.environmentTexture = scene.environmentTexture.name;
  104683. }
  104684. // Skeletons
  104685. serializationObject.skeletons = [];
  104686. for (index = 0; index < scene.skeletons.length; index++) {
  104687. var skeleton = scene.skeletons[index];
  104688. if (!skeleton.doNotSerialize) {
  104689. serializationObject.skeletons.push(skeleton.serialize());
  104690. }
  104691. }
  104692. // Transform nodes
  104693. serializationObject.transformNodes = [];
  104694. for (index = 0; index < scene.transformNodes.length; index++) {
  104695. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  104696. }
  104697. // Geometries
  104698. serializationObject.geometries = {};
  104699. serializationObject.geometries.boxes = [];
  104700. serializationObject.geometries.spheres = [];
  104701. serializationObject.geometries.cylinders = [];
  104702. serializationObject.geometries.toruses = [];
  104703. serializationObject.geometries.grounds = [];
  104704. serializationObject.geometries.planes = [];
  104705. serializationObject.geometries.torusKnots = [];
  104706. serializationObject.geometries.vertexData = [];
  104707. serializedGeometries = [];
  104708. var geometries = scene.getGeometries();
  104709. for (index = 0; index < geometries.length; index++) {
  104710. var geometry = geometries[index];
  104711. if (geometry.isReady()) {
  104712. serializeGeometry(geometry, serializationObject.geometries);
  104713. }
  104714. }
  104715. // Meshes
  104716. serializationObject.meshes = [];
  104717. for (index = 0; index < scene.meshes.length; index++) {
  104718. var abstractMesh = scene.meshes[index];
  104719. if (abstractMesh instanceof BABYLON.Mesh) {
  104720. var mesh = abstractMesh;
  104721. if (!mesh.doNotSerialize) {
  104722. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  104723. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  104724. }
  104725. }
  104726. }
  104727. }
  104728. // Particles Systems
  104729. serializationObject.particleSystems = [];
  104730. for (index = 0; index < scene.particleSystems.length; index++) {
  104731. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  104732. }
  104733. // Action Manager
  104734. if (scene.actionManager) {
  104735. serializationObject.actions = scene.actionManager.serialize("scene");
  104736. }
  104737. // Components
  104738. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  104739. var component = _c[_b];
  104740. component.serialize(serializationObject);
  104741. }
  104742. return serializationObject;
  104743. };
  104744. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  104745. if (withParents === void 0) { withParents = false; }
  104746. if (withChildren === void 0) { withChildren = false; }
  104747. var serializationObject = {};
  104748. SceneSerializer.ClearCache();
  104749. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  104750. if (withParents || withChildren) {
  104751. //deliberate for loop! not for each, appended should be processed as well.
  104752. for (var i = 0; i < toSerialize.length; ++i) {
  104753. if (withChildren) {
  104754. toSerialize[i].getDescendants().forEach(function (node) {
  104755. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  104756. toSerialize.push(node);
  104757. }
  104758. });
  104759. }
  104760. //make sure the array doesn't contain the object already
  104761. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  104762. toSerialize.push(toSerialize[i].parent);
  104763. }
  104764. }
  104765. }
  104766. toSerialize.forEach(function (mesh) {
  104767. finalizeSingleMesh(mesh, serializationObject);
  104768. });
  104769. return serializationObject;
  104770. };
  104771. return SceneSerializer;
  104772. }());
  104773. BABYLON.SceneSerializer = SceneSerializer;
  104774. })(BABYLON || (BABYLON = {}));
  104775. //# sourceMappingURL=babylon.sceneSerializer.js.map
  104776. var BABYLON;
  104777. (function (BABYLON) {
  104778. /**
  104779. * Class used to generate realtime reflection / refraction cube textures
  104780. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  104781. */
  104782. var ReflectionProbe = /** @class */ (function () {
  104783. /**
  104784. * Creates a new reflection probe
  104785. * @param name defines the name of the probe
  104786. * @param size defines the texture resolution (for each face)
  104787. * @param scene defines the hosting scene
  104788. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  104789. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  104790. */
  104791. function ReflectionProbe(
  104792. /** defines the name of the probe */
  104793. name, size, scene, generateMipMaps, useFloat) {
  104794. if (generateMipMaps === void 0) { generateMipMaps = true; }
  104795. if (useFloat === void 0) { useFloat = false; }
  104796. var _this = this;
  104797. this.name = name;
  104798. this._viewMatrix = BABYLON.Matrix.Identity();
  104799. this._target = BABYLON.Vector3.Zero();
  104800. this._add = BABYLON.Vector3.Zero();
  104801. this._invertYAxis = false;
  104802. /** Gets or sets probe position (center of the cube map) */
  104803. this.position = BABYLON.Vector3.Zero();
  104804. this._scene = scene;
  104805. // Create the scene field if not exist.
  104806. if (!this._scene.reflectionProbes) {
  104807. this._scene.reflectionProbes = new Array();
  104808. }
  104809. this._scene.reflectionProbes.push(this);
  104810. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  104811. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  104812. switch (faceIndex) {
  104813. case 0:
  104814. _this._add.copyFromFloats(1, 0, 0);
  104815. break;
  104816. case 1:
  104817. _this._add.copyFromFloats(-1, 0, 0);
  104818. break;
  104819. case 2:
  104820. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  104821. break;
  104822. case 3:
  104823. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  104824. break;
  104825. case 4:
  104826. _this._add.copyFromFloats(0, 0, 1);
  104827. break;
  104828. case 5:
  104829. _this._add.copyFromFloats(0, 0, -1);
  104830. break;
  104831. }
  104832. if (_this._attachedMesh) {
  104833. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  104834. }
  104835. _this.position.addToRef(_this._add, _this._target);
  104836. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  104837. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  104838. scene._forcedViewPosition = _this.position;
  104839. });
  104840. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  104841. scene._forcedViewPosition = null;
  104842. scene.updateTransformMatrix(true);
  104843. });
  104844. if (scene.activeCamera) {
  104845. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  104846. }
  104847. }
  104848. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  104849. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  104850. get: function () {
  104851. return this._renderTargetTexture.samples;
  104852. },
  104853. set: function (value) {
  104854. this._renderTargetTexture.samples = value;
  104855. },
  104856. enumerable: true,
  104857. configurable: true
  104858. });
  104859. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  104860. /** Gets or sets the refresh rate to use (on every frame by default) */
  104861. get: function () {
  104862. return this._renderTargetTexture.refreshRate;
  104863. },
  104864. set: function (value) {
  104865. this._renderTargetTexture.refreshRate = value;
  104866. },
  104867. enumerable: true,
  104868. configurable: true
  104869. });
  104870. /**
  104871. * Gets the hosting scene
  104872. * @returns a Scene
  104873. */
  104874. ReflectionProbe.prototype.getScene = function () {
  104875. return this._scene;
  104876. };
  104877. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  104878. /** Gets the internal CubeTexture used to render to */
  104879. get: function () {
  104880. return this._renderTargetTexture;
  104881. },
  104882. enumerable: true,
  104883. configurable: true
  104884. });
  104885. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  104886. /** Gets the list of meshes to render */
  104887. get: function () {
  104888. return this._renderTargetTexture.renderList;
  104889. },
  104890. enumerable: true,
  104891. configurable: true
  104892. });
  104893. /**
  104894. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  104895. * @param mesh defines the mesh to attach to
  104896. */
  104897. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  104898. this._attachedMesh = mesh;
  104899. };
  104900. /**
  104901. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  104902. * @param renderingGroupId The rendering group id corresponding to its index
  104903. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  104904. */
  104905. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  104906. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  104907. };
  104908. /**
  104909. * Clean all associated resources
  104910. */
  104911. ReflectionProbe.prototype.dispose = function () {
  104912. var index = this._scene.reflectionProbes.indexOf(this);
  104913. if (index !== -1) {
  104914. // Remove from the scene if found
  104915. this._scene.reflectionProbes.splice(index, 1);
  104916. }
  104917. if (this._renderTargetTexture) {
  104918. this._renderTargetTexture.dispose();
  104919. this._renderTargetTexture = null;
  104920. }
  104921. };
  104922. return ReflectionProbe;
  104923. }());
  104924. BABYLON.ReflectionProbe = ReflectionProbe;
  104925. })(BABYLON || (BABYLON = {}));
  104926. //# sourceMappingURL=babylon.reflectionProbe.js.map
  104927. var BABYLON;
  104928. (function (BABYLON) {
  104929. /**
  104930. * Defines the layer scene component responsible to manage any layers
  104931. * in a given scene.
  104932. */
  104933. var LayerSceneComponent = /** @class */ (function () {
  104934. /**
  104935. * Creates a new instance of the component for the given scene
  104936. * @param scene Defines the scene to register the component in
  104937. */
  104938. function LayerSceneComponent(scene) {
  104939. /**
  104940. * The component name helpfull to identify the component in the list of scene components.
  104941. */
  104942. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  104943. this.scene = scene;
  104944. this._engine = scene.getEngine();
  104945. scene.layers = new Array();
  104946. }
  104947. /**
  104948. * Registers the component in a given scene
  104949. */
  104950. LayerSceneComponent.prototype.register = function () {
  104951. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  104952. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  104953. };
  104954. /**
  104955. * Rebuilds the elements related to this component in case of
  104956. * context lost for instance.
  104957. */
  104958. LayerSceneComponent.prototype.rebuild = function () {
  104959. var layers = this.scene.layers;
  104960. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  104961. var layer = layers_1[_i];
  104962. layer._rebuild();
  104963. }
  104964. };
  104965. /**
  104966. * Disposes the component and the associated ressources.
  104967. */
  104968. LayerSceneComponent.prototype.dispose = function () {
  104969. var layers = this.scene.layers;
  104970. while (layers.length) {
  104971. layers[0].dispose();
  104972. }
  104973. };
  104974. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  104975. var layers = this.scene.layers;
  104976. if (layers.length) {
  104977. this._engine.setDepthBuffer(false);
  104978. var cameraLayerMask = camera.layerMask;
  104979. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  104980. var layer = layers_2[_i];
  104981. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  104982. layer.render();
  104983. }
  104984. }
  104985. this._engine.setDepthBuffer(true);
  104986. }
  104987. };
  104988. LayerSceneComponent.prototype._drawBackground = function (camera) {
  104989. this._draw(camera, true);
  104990. };
  104991. LayerSceneComponent.prototype._drawForeground = function (camera) {
  104992. this._draw(camera, false);
  104993. };
  104994. return LayerSceneComponent;
  104995. }());
  104996. BABYLON.LayerSceneComponent = LayerSceneComponent;
  104997. })(BABYLON || (BABYLON = {}));
  104998. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  104999. var BABYLON;
  105000. (function (BABYLON) {
  105001. var Layer = /** @class */ (function () {
  105002. function Layer(name, imgUrl, scene, isBackground, color) {
  105003. this.name = name;
  105004. this.scale = new BABYLON.Vector2(1, 1);
  105005. this.offset = new BABYLON.Vector2(0, 0);
  105006. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  105007. this.layerMask = 0x0FFFFFFF;
  105008. this._vertexBuffers = {};
  105009. // Events
  105010. /**
  105011. * An event triggered when the layer is disposed.
  105012. */
  105013. this.onDisposeObservable = new BABYLON.Observable();
  105014. /**
  105015. * An event triggered before rendering the scene
  105016. */
  105017. this.onBeforeRenderObservable = new BABYLON.Observable();
  105018. /**
  105019. * An event triggered after rendering the scene
  105020. */
  105021. this.onAfterRenderObservable = new BABYLON.Observable();
  105022. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  105023. this.isBackground = isBackground === undefined ? true : isBackground;
  105024. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  105025. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  105026. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  105027. if (!layerComponent) {
  105028. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  105029. this._scene._addComponent(layerComponent);
  105030. }
  105031. this._scene.layers.push(this);
  105032. var engine = this._scene.getEngine();
  105033. // VBO
  105034. var vertices = [];
  105035. vertices.push(1, 1);
  105036. vertices.push(-1, 1);
  105037. vertices.push(-1, -1);
  105038. vertices.push(1, -1);
  105039. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  105040. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  105041. this._createIndexBuffer();
  105042. // Effects
  105043. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  105044. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  105045. }
  105046. Object.defineProperty(Layer.prototype, "onDispose", {
  105047. set: function (callback) {
  105048. if (this._onDisposeObserver) {
  105049. this.onDisposeObservable.remove(this._onDisposeObserver);
  105050. }
  105051. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  105052. },
  105053. enumerable: true,
  105054. configurable: true
  105055. });
  105056. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  105057. set: function (callback) {
  105058. if (this._onBeforeRenderObserver) {
  105059. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  105060. }
  105061. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  105062. },
  105063. enumerable: true,
  105064. configurable: true
  105065. });
  105066. Object.defineProperty(Layer.prototype, "onAfterRender", {
  105067. set: function (callback) {
  105068. if (this._onAfterRenderObserver) {
  105069. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  105070. }
  105071. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  105072. },
  105073. enumerable: true,
  105074. configurable: true
  105075. });
  105076. Layer.prototype._createIndexBuffer = function () {
  105077. var engine = this._scene.getEngine();
  105078. // Indices
  105079. var indices = [];
  105080. indices.push(0);
  105081. indices.push(1);
  105082. indices.push(2);
  105083. indices.push(0);
  105084. indices.push(2);
  105085. indices.push(3);
  105086. this._indexBuffer = engine.createIndexBuffer(indices);
  105087. };
  105088. /** @hidden */
  105089. Layer.prototype._rebuild = function () {
  105090. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  105091. if (vb) {
  105092. vb._rebuild();
  105093. }
  105094. this._createIndexBuffer();
  105095. };
  105096. Layer.prototype.render = function () {
  105097. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  105098. // Check
  105099. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  105100. return;
  105101. var engine = this._scene.getEngine();
  105102. this.onBeforeRenderObservable.notifyObservers(this);
  105103. // Render
  105104. engine.enableEffect(currentEffect);
  105105. engine.setState(false);
  105106. // Texture
  105107. currentEffect.setTexture("textureSampler", this.texture);
  105108. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  105109. // Color
  105110. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  105111. // Scale / offset
  105112. currentEffect.setVector2("offset", this.offset);
  105113. currentEffect.setVector2("scale", this.scale);
  105114. // VBOs
  105115. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  105116. // Draw order
  105117. if (!this.alphaTest) {
  105118. engine.setAlphaMode(this.alphaBlendingMode);
  105119. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105120. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  105121. }
  105122. else {
  105123. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105124. }
  105125. this.onAfterRenderObservable.notifyObservers(this);
  105126. };
  105127. Layer.prototype.dispose = function () {
  105128. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  105129. if (vertexBuffer) {
  105130. vertexBuffer.dispose();
  105131. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  105132. }
  105133. if (this._indexBuffer) {
  105134. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  105135. this._indexBuffer = null;
  105136. }
  105137. if (this.texture) {
  105138. this.texture.dispose();
  105139. this.texture = null;
  105140. }
  105141. // Remove from scene
  105142. var index = this._scene.layers.indexOf(this);
  105143. this._scene.layers.splice(index, 1);
  105144. // Callback
  105145. this.onDisposeObservable.notifyObservers(this);
  105146. this.onDisposeObservable.clear();
  105147. this.onAfterRenderObservable.clear();
  105148. this.onBeforeRenderObservable.clear();
  105149. };
  105150. return Layer;
  105151. }());
  105152. BABYLON.Layer = Layer;
  105153. })(BABYLON || (BABYLON = {}));
  105154. //# sourceMappingURL=babylon.layer.js.map
  105155. var BABYLON;
  105156. (function (BABYLON) {
  105157. var TextureTools = /** @class */ (function () {
  105158. function TextureTools() {
  105159. }
  105160. /**
  105161. * Uses the GPU to create a copy texture rescaled at a given size
  105162. * @param texture Texture to copy from
  105163. * @param width Desired width
  105164. * @param height Desired height
  105165. * @return Generated texture
  105166. */
  105167. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  105168. if (useBilinearMode === void 0) { useBilinearMode = true; }
  105169. var scene = texture.getScene();
  105170. var engine = scene.getEngine();
  105171. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  105172. rtt.wrapU = texture.wrapU;
  105173. rtt.wrapV = texture.wrapV;
  105174. rtt.uOffset = texture.uOffset;
  105175. rtt.vOffset = texture.vOffset;
  105176. rtt.uScale = texture.uScale;
  105177. rtt.vScale = texture.vScale;
  105178. rtt.uAng = texture.uAng;
  105179. rtt.vAng = texture.vAng;
  105180. rtt.wAng = texture.wAng;
  105181. rtt.coordinatesIndex = texture.coordinatesIndex;
  105182. rtt.level = texture.level;
  105183. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  105184. rtt._texture.isReady = false;
  105185. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105186. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105187. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  105188. passPostProcess.getEffect().executeWhenCompiled(function () {
  105189. passPostProcess.onApply = function (effect) {
  105190. effect.setTexture("textureSampler", texture);
  105191. };
  105192. var internalTexture = rtt.getInternalTexture();
  105193. if (internalTexture) {
  105194. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  105195. engine.unBindFramebuffer(internalTexture);
  105196. rtt.disposeFramebufferObjects();
  105197. passPostProcess.dispose();
  105198. internalTexture.isReady = true;
  105199. }
  105200. });
  105201. return rtt;
  105202. };
  105203. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  105204. if (!scene._environmentBRDFTexture) {
  105205. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105206. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105207. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105208. scene._environmentBRDFTexture = texture;
  105209. }
  105210. return scene._environmentBRDFTexture;
  105211. };
  105212. 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=";
  105213. return TextureTools;
  105214. }());
  105215. BABYLON.TextureTools = TextureTools;
  105216. })(BABYLON || (BABYLON = {}));
  105217. //# sourceMappingURL=babylon.textureTools.js.map
  105218. var BABYLON;
  105219. (function (BABYLON) {
  105220. var FramingBehavior = /** @class */ (function () {
  105221. function FramingBehavior() {
  105222. this._mode = FramingBehavior.FitFrustumSidesMode;
  105223. this._radiusScale = 1.0;
  105224. this._positionScale = 0.5;
  105225. this._defaultElevation = 0.3;
  105226. this._elevationReturnTime = 1500;
  105227. this._elevationReturnWaitTime = 1000;
  105228. this._zoomStopsAnimation = false;
  105229. this._framingTime = 1500;
  105230. this._isPointerDown = false;
  105231. this._lastInteractionTime = -Infinity;
  105232. // Framing control
  105233. this._animatables = new Array();
  105234. this._betaIsAnimating = false;
  105235. }
  105236. Object.defineProperty(FramingBehavior.prototype, "name", {
  105237. get: function () {
  105238. return "Framing";
  105239. },
  105240. enumerable: true,
  105241. configurable: true
  105242. });
  105243. Object.defineProperty(FramingBehavior.prototype, "mode", {
  105244. /**
  105245. * Gets current mode used by the behavior.
  105246. */
  105247. get: function () {
  105248. return this._mode;
  105249. },
  105250. /**
  105251. * Sets the current mode used by the behavior
  105252. */
  105253. set: function (mode) {
  105254. this._mode = mode;
  105255. },
  105256. enumerable: true,
  105257. configurable: true
  105258. });
  105259. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  105260. /**
  105261. * Gets the scale applied to the radius
  105262. */
  105263. get: function () {
  105264. return this._radiusScale;
  105265. },
  105266. /**
  105267. * Sets the scale applied to the radius (1 by default)
  105268. */
  105269. set: function (radius) {
  105270. this._radiusScale = radius;
  105271. },
  105272. enumerable: true,
  105273. configurable: true
  105274. });
  105275. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  105276. /**
  105277. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  105278. */
  105279. get: function () {
  105280. return this._positionScale;
  105281. },
  105282. /**
  105283. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  105284. */
  105285. set: function (scale) {
  105286. this._positionScale = scale;
  105287. },
  105288. enumerable: true,
  105289. configurable: true
  105290. });
  105291. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  105292. /**
  105293. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  105294. * behaviour is triggered, in radians.
  105295. */
  105296. get: function () {
  105297. return this._defaultElevation;
  105298. },
  105299. /**
  105300. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  105301. * behaviour is triggered, in radians.
  105302. */
  105303. set: function (elevation) {
  105304. this._defaultElevation = elevation;
  105305. },
  105306. enumerable: true,
  105307. configurable: true
  105308. });
  105309. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  105310. /**
  105311. * Gets the time (in milliseconds) taken to return to the default beta position.
  105312. * Negative value indicates camera should not return to default.
  105313. */
  105314. get: function () {
  105315. return this._elevationReturnTime;
  105316. },
  105317. /**
  105318. * Sets the time (in milliseconds) taken to return to the default beta position.
  105319. * Negative value indicates camera should not return to default.
  105320. */
  105321. set: function (speed) {
  105322. this._elevationReturnTime = speed;
  105323. },
  105324. enumerable: true,
  105325. configurable: true
  105326. });
  105327. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  105328. /**
  105329. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  105330. */
  105331. get: function () {
  105332. return this._elevationReturnWaitTime;
  105333. },
  105334. /**
  105335. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  105336. */
  105337. set: function (time) {
  105338. this._elevationReturnWaitTime = time;
  105339. },
  105340. enumerable: true,
  105341. configurable: true
  105342. });
  105343. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  105344. /**
  105345. * Gets the flag that indicates if user zooming should stop animation.
  105346. */
  105347. get: function () {
  105348. return this._zoomStopsAnimation;
  105349. },
  105350. /**
  105351. * Sets the flag that indicates if user zooming should stop animation.
  105352. */
  105353. set: function (flag) {
  105354. this._zoomStopsAnimation = flag;
  105355. },
  105356. enumerable: true,
  105357. configurable: true
  105358. });
  105359. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  105360. /**
  105361. * Gets the transition time when framing the mesh, in milliseconds
  105362. */
  105363. get: function () {
  105364. return this._framingTime;
  105365. },
  105366. /**
  105367. * Sets the transition time when framing the mesh, in milliseconds
  105368. */
  105369. set: function (time) {
  105370. this._framingTime = time;
  105371. },
  105372. enumerable: true,
  105373. configurable: true
  105374. });
  105375. FramingBehavior.prototype.init = function () {
  105376. // Do notihng
  105377. };
  105378. FramingBehavior.prototype.attach = function (camera) {
  105379. var _this = this;
  105380. this._attachedCamera = camera;
  105381. var scene = this._attachedCamera.getScene();
  105382. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  105383. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  105384. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  105385. _this._isPointerDown = true;
  105386. return;
  105387. }
  105388. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  105389. _this._isPointerDown = false;
  105390. }
  105391. });
  105392. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  105393. if (mesh) {
  105394. _this.zoomOnMesh(mesh);
  105395. }
  105396. });
  105397. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  105398. // Stop the animation if there is user interaction and the animation should stop for this interaction
  105399. _this._applyUserInteraction();
  105400. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  105401. // back to the default position after a given timeout
  105402. _this._maintainCameraAboveGround();
  105403. });
  105404. };
  105405. FramingBehavior.prototype.detach = function () {
  105406. if (!this._attachedCamera) {
  105407. return;
  105408. }
  105409. var scene = this._attachedCamera.getScene();
  105410. if (this._onPrePointerObservableObserver) {
  105411. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  105412. }
  105413. if (this._onAfterCheckInputsObserver) {
  105414. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  105415. }
  105416. if (this._onMeshTargetChangedObserver) {
  105417. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105418. }
  105419. this._attachedCamera = null;
  105420. };
  105421. /**
  105422. * Targets the given mesh and updates zoom level accordingly.
  105423. * @param mesh The mesh to target.
  105424. * @param radius Optional. If a cached radius position already exists, overrides default.
  105425. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105426. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105427. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105428. */
  105429. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  105430. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105431. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105432. mesh.computeWorldMatrix(true);
  105433. var boundingBox = mesh.getBoundingInfo().boundingBox;
  105434. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  105435. };
  105436. /**
  105437. * Targets the given mesh with its children and updates zoom level accordingly.
  105438. * @param mesh The mesh to target.
  105439. * @param radius Optional. If a cached radius position already exists, overrides default.
  105440. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105441. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105442. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105443. */
  105444. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  105445. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105446. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105447. mesh.computeWorldMatrix(true);
  105448. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  105449. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  105450. };
  105451. /**
  105452. * Targets the given meshes with their children and updates zoom level accordingly.
  105453. * @param meshes The mesh to target.
  105454. * @param radius Optional. If a cached radius position already exists, overrides default.
  105455. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105456. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105457. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105458. */
  105459. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  105460. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105461. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105462. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  105463. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  105464. for (var i = 0; i < meshes.length; i++) {
  105465. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  105466. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  105467. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  105468. }
  105469. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  105470. };
  105471. /**
  105472. * Targets the given mesh and updates zoom level accordingly.
  105473. * @param mesh The mesh to target.
  105474. * @param radius Optional. If a cached radius position already exists, overrides default.
  105475. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105476. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105477. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105478. */
  105479. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  105480. var _this = this;
  105481. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105482. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105483. var zoomTarget;
  105484. if (!this._attachedCamera) {
  105485. return;
  105486. }
  105487. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  105488. var bottom = minimumWorld.y;
  105489. var top = maximumWorld.y;
  105490. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  105491. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  105492. if (focusOnOriginXZ) {
  105493. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  105494. }
  105495. else {
  105496. var centerWorld = minimumWorld.add(radiusWorld);
  105497. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  105498. }
  105499. if (!this._vectorTransition) {
  105500. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  105501. }
  105502. this._betaIsAnimating = true;
  105503. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  105504. if (animatable) {
  105505. this._animatables.push(animatable);
  105506. }
  105507. // sets the radius and lower radius bounds
  105508. // Small delta ensures camera is not always at lower zoom limit.
  105509. var radius = 0;
  105510. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  105511. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  105512. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  105513. radius = position;
  105514. }
  105515. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  105516. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  105517. if (this._attachedCamera.lowerRadiusLimit === null) {
  105518. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  105519. }
  105520. }
  105521. // Set sensibilities
  105522. var extend = maximumWorld.subtract(minimumWorld).length();
  105523. this._attachedCamera.panningSensibility = 5000 / extend;
  105524. this._attachedCamera.wheelPrecision = 100 / radius;
  105525. // transition to new radius
  105526. if (!this._radiusTransition) {
  105527. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  105528. }
  105529. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  105530. _this.stopAllAnimations();
  105531. if (onAnimationEnd) {
  105532. onAnimationEnd();
  105533. }
  105534. if (_this._attachedCamera) {
  105535. _this._attachedCamera.storeState();
  105536. }
  105537. });
  105538. if (animatable) {
  105539. this._animatables.push(animatable);
  105540. }
  105541. };
  105542. /**
  105543. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  105544. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  105545. * frustum width.
  105546. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  105547. * to fully enclose the mesh in the viewing frustum.
  105548. */
  105549. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  105550. var size = maximumWorld.subtract(minimumWorld);
  105551. var boxVectorGlobalDiagonal = size.length();
  105552. var frustumSlope = this._getFrustumSlope();
  105553. // Formula for setting distance
  105554. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  105555. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  105556. // Horizon distance
  105557. var radius = radiusWithoutFraming * this._radiusScale;
  105558. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  105559. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  105560. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  105561. var camera = this._attachedCamera;
  105562. if (!camera) {
  105563. return 0;
  105564. }
  105565. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  105566. // Don't exceed the requested limit
  105567. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  105568. }
  105569. // Don't exceed the upper radius limit
  105570. if (camera.upperRadiusLimit) {
  105571. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  105572. }
  105573. return distance;
  105574. };
  105575. /**
  105576. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  105577. * is automatically returned to its default position (expected to be above ground plane).
  105578. */
  105579. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  105580. var _this = this;
  105581. if (this._elevationReturnTime < 0) {
  105582. return;
  105583. }
  105584. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  105585. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  105586. var limitBeta = Math.PI * 0.5;
  105587. // Bring the camera back up if below the ground plane
  105588. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  105589. this._betaIsAnimating = true;
  105590. //Transition to new position
  105591. this.stopAllAnimations();
  105592. if (!this._betaTransition) {
  105593. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  105594. }
  105595. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  105596. _this._clearAnimationLocks();
  105597. _this.stopAllAnimations();
  105598. });
  105599. if (animatabe) {
  105600. this._animatables.push(animatabe);
  105601. }
  105602. }
  105603. };
  105604. /**
  105605. * Returns the frustum slope based on the canvas ratio and camera FOV
  105606. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  105607. */
  105608. FramingBehavior.prototype._getFrustumSlope = function () {
  105609. // Calculate the viewport ratio
  105610. // Aspect Ratio is Height/Width.
  105611. var camera = this._attachedCamera;
  105612. if (!camera) {
  105613. return BABYLON.Vector2.Zero();
  105614. }
  105615. var engine = camera.getScene().getEngine();
  105616. var aspectRatio = engine.getAspectRatio(camera);
  105617. // Camera FOV is the vertical field of view (top-bottom) in radians.
  105618. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  105619. var frustumSlopeY = Math.tan(camera.fov / 2);
  105620. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  105621. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  105622. // along the forward vector.
  105623. var frustumSlopeX = frustumSlopeY * aspectRatio;
  105624. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  105625. };
  105626. /**
  105627. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  105628. */
  105629. FramingBehavior.prototype._clearAnimationLocks = function () {
  105630. this._betaIsAnimating = false;
  105631. };
  105632. /**
  105633. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  105634. */
  105635. FramingBehavior.prototype._applyUserInteraction = function () {
  105636. if (this.isUserIsMoving) {
  105637. this._lastInteractionTime = BABYLON.Tools.Now;
  105638. this.stopAllAnimations();
  105639. this._clearAnimationLocks();
  105640. }
  105641. };
  105642. /**
  105643. * Stops and removes all animations that have been applied to the camera
  105644. */
  105645. FramingBehavior.prototype.stopAllAnimations = function () {
  105646. if (this._attachedCamera) {
  105647. this._attachedCamera.animations = [];
  105648. }
  105649. while (this._animatables.length) {
  105650. if (this._animatables[0]) {
  105651. this._animatables[0].onAnimationEnd = null;
  105652. this._animatables[0].stop();
  105653. }
  105654. this._animatables.shift();
  105655. }
  105656. };
  105657. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  105658. /**
  105659. * Gets a value indicating if the user is moving the camera
  105660. */
  105661. get: function () {
  105662. if (!this._attachedCamera) {
  105663. return false;
  105664. }
  105665. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  105666. this._attachedCamera.inertialBetaOffset !== 0 ||
  105667. this._attachedCamera.inertialRadiusOffset !== 0 ||
  105668. this._attachedCamera.inertialPanningX !== 0 ||
  105669. this._attachedCamera.inertialPanningY !== 0 ||
  105670. this._isPointerDown;
  105671. },
  105672. enumerable: true,
  105673. configurable: true
  105674. });
  105675. /**
  105676. * The easing function used by animations
  105677. */
  105678. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  105679. /**
  105680. * The easing mode used by animations
  105681. */
  105682. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  105683. // Statics
  105684. /**
  105685. * The camera can move all the way towards the mesh.
  105686. */
  105687. FramingBehavior.IgnoreBoundsSizeMode = 0;
  105688. /**
  105689. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  105690. */
  105691. FramingBehavior.FitFrustumSidesMode = 1;
  105692. return FramingBehavior;
  105693. }());
  105694. BABYLON.FramingBehavior = FramingBehavior;
  105695. })(BABYLON || (BABYLON = {}));
  105696. //# sourceMappingURL=babylon.framingBehavior.js.map
  105697. var BABYLON;
  105698. (function (BABYLON) {
  105699. /**
  105700. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  105701. */
  105702. var BouncingBehavior = /** @class */ (function () {
  105703. function BouncingBehavior() {
  105704. /**
  105705. * The duration of the animation, in milliseconds
  105706. */
  105707. this.transitionDuration = 450;
  105708. /**
  105709. * Length of the distance animated by the transition when lower radius is reached
  105710. */
  105711. this.lowerRadiusTransitionRange = 2;
  105712. /**
  105713. * Length of the distance animated by the transition when upper radius is reached
  105714. */
  105715. this.upperRadiusTransitionRange = -2;
  105716. this._autoTransitionRange = false;
  105717. // Animations
  105718. this._radiusIsAnimating = false;
  105719. this._radiusBounceTransition = null;
  105720. this._animatables = new Array();
  105721. }
  105722. Object.defineProperty(BouncingBehavior.prototype, "name", {
  105723. get: function () {
  105724. return "Bouncing";
  105725. },
  105726. enumerable: true,
  105727. configurable: true
  105728. });
  105729. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  105730. /**
  105731. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  105732. */
  105733. get: function () {
  105734. return this._autoTransitionRange;
  105735. },
  105736. /**
  105737. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  105738. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  105739. */
  105740. set: function (value) {
  105741. var _this = this;
  105742. if (this._autoTransitionRange === value) {
  105743. return;
  105744. }
  105745. this._autoTransitionRange = value;
  105746. var camera = this._attachedCamera;
  105747. if (!camera) {
  105748. return;
  105749. }
  105750. if (value) {
  105751. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  105752. if (!mesh) {
  105753. return;
  105754. }
  105755. mesh.computeWorldMatrix(true);
  105756. var diagonal = mesh.getBoundingInfo().diagonalLength;
  105757. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  105758. _this.upperRadiusTransitionRange = diagonal * 0.05;
  105759. });
  105760. }
  105761. else if (this._onMeshTargetChangedObserver) {
  105762. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105763. }
  105764. },
  105765. enumerable: true,
  105766. configurable: true
  105767. });
  105768. BouncingBehavior.prototype.init = function () {
  105769. // Do notihng
  105770. };
  105771. BouncingBehavior.prototype.attach = function (camera) {
  105772. var _this = this;
  105773. this._attachedCamera = camera;
  105774. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  105775. if (!_this._attachedCamera) {
  105776. return;
  105777. }
  105778. // Add the bounce animation to the lower radius limit
  105779. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  105780. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  105781. }
  105782. // Add the bounce animation to the upper radius limit
  105783. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  105784. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  105785. }
  105786. });
  105787. };
  105788. BouncingBehavior.prototype.detach = function () {
  105789. if (!this._attachedCamera) {
  105790. return;
  105791. }
  105792. if (this._onAfterCheckInputsObserver) {
  105793. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  105794. }
  105795. if (this._onMeshTargetChangedObserver) {
  105796. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105797. }
  105798. this._attachedCamera = null;
  105799. };
  105800. /**
  105801. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  105802. * @param radiusLimit The limit to check against.
  105803. * @return Bool to indicate if at limit.
  105804. */
  105805. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  105806. if (!this._attachedCamera) {
  105807. return false;
  105808. }
  105809. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  105810. return true;
  105811. }
  105812. return false;
  105813. };
  105814. /**
  105815. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  105816. * @param radiusDelta The delta by which to animate to. Can be negative.
  105817. */
  105818. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  105819. var _this = this;
  105820. if (!this._attachedCamera) {
  105821. return;
  105822. }
  105823. if (!this._radiusBounceTransition) {
  105824. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  105825. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  105826. }
  105827. // Prevent zoom until bounce has completed
  105828. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  105829. this._attachedCamera.wheelPrecision = Infinity;
  105830. this._attachedCamera.inertialRadiusOffset = 0;
  105831. // Animate to the radius limit
  105832. this.stopAllAnimations();
  105833. this._radiusIsAnimating = true;
  105834. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  105835. if (animatable) {
  105836. this._animatables.push(animatable);
  105837. }
  105838. };
  105839. /**
  105840. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  105841. */
  105842. BouncingBehavior.prototype._clearAnimationLocks = function () {
  105843. this._radiusIsAnimating = false;
  105844. if (this._attachedCamera) {
  105845. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  105846. }
  105847. };
  105848. /**
  105849. * Stops and removes all animations that have been applied to the camera
  105850. */
  105851. BouncingBehavior.prototype.stopAllAnimations = function () {
  105852. if (this._attachedCamera) {
  105853. this._attachedCamera.animations = [];
  105854. }
  105855. while (this._animatables.length) {
  105856. this._animatables[0].onAnimationEnd = null;
  105857. this._animatables[0].stop();
  105858. this._animatables.shift();
  105859. }
  105860. };
  105861. /**
  105862. * The easing function used by animations
  105863. */
  105864. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  105865. /**
  105866. * The easing mode used by animations
  105867. */
  105868. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  105869. return BouncingBehavior;
  105870. }());
  105871. BABYLON.BouncingBehavior = BouncingBehavior;
  105872. })(BABYLON || (BABYLON = {}));
  105873. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  105874. var BABYLON;
  105875. (function (BABYLON) {
  105876. var AutoRotationBehavior = /** @class */ (function () {
  105877. function AutoRotationBehavior() {
  105878. this._zoomStopsAnimation = false;
  105879. this._idleRotationSpeed = 0.05;
  105880. this._idleRotationWaitTime = 2000;
  105881. this._idleRotationSpinupTime = 2000;
  105882. this._isPointerDown = false;
  105883. this._lastFrameTime = null;
  105884. this._lastInteractionTime = -Infinity;
  105885. this._cameraRotationSpeed = 0;
  105886. this._lastFrameRadius = 0;
  105887. }
  105888. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  105889. get: function () {
  105890. return "AutoRotation";
  105891. },
  105892. enumerable: true,
  105893. configurable: true
  105894. });
  105895. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  105896. /**
  105897. * Gets the flag that indicates if user zooming should stop animation.
  105898. */
  105899. get: function () {
  105900. return this._zoomStopsAnimation;
  105901. },
  105902. /**
  105903. * Sets the flag that indicates if user zooming should stop animation.
  105904. */
  105905. set: function (flag) {
  105906. this._zoomStopsAnimation = flag;
  105907. },
  105908. enumerable: true,
  105909. configurable: true
  105910. });
  105911. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  105912. /**
  105913. * Gets the default speed at which the camera rotates around the model.
  105914. */
  105915. get: function () {
  105916. return this._idleRotationSpeed;
  105917. },
  105918. /**
  105919. * Sets the default speed at which the camera rotates around the model.
  105920. */
  105921. set: function (speed) {
  105922. this._idleRotationSpeed = speed;
  105923. },
  105924. enumerable: true,
  105925. configurable: true
  105926. });
  105927. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  105928. /**
  105929. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  105930. */
  105931. get: function () {
  105932. return this._idleRotationWaitTime;
  105933. },
  105934. /**
  105935. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  105936. */
  105937. set: function (time) {
  105938. this._idleRotationWaitTime = time;
  105939. },
  105940. enumerable: true,
  105941. configurable: true
  105942. });
  105943. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  105944. /**
  105945. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  105946. */
  105947. get: function () {
  105948. return this._idleRotationSpinupTime;
  105949. },
  105950. /**
  105951. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  105952. */
  105953. set: function (time) {
  105954. this._idleRotationSpinupTime = time;
  105955. },
  105956. enumerable: true,
  105957. configurable: true
  105958. });
  105959. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  105960. /**
  105961. * Gets a value indicating if the camera is currently rotating because of this behavior
  105962. */
  105963. get: function () {
  105964. return Math.abs(this._cameraRotationSpeed) > 0;
  105965. },
  105966. enumerable: true,
  105967. configurable: true
  105968. });
  105969. AutoRotationBehavior.prototype.init = function () {
  105970. // Do notihng
  105971. };
  105972. AutoRotationBehavior.prototype.attach = function (camera) {
  105973. var _this = this;
  105974. this._attachedCamera = camera;
  105975. var scene = this._attachedCamera.getScene();
  105976. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  105977. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  105978. _this._isPointerDown = true;
  105979. return;
  105980. }
  105981. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  105982. _this._isPointerDown = false;
  105983. }
  105984. });
  105985. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  105986. var now = BABYLON.Tools.Now;
  105987. var dt = 0;
  105988. if (_this._lastFrameTime != null) {
  105989. dt = now - _this._lastFrameTime;
  105990. }
  105991. _this._lastFrameTime = now;
  105992. // Stop the animation if there is user interaction and the animation should stop for this interaction
  105993. _this._applyUserInteraction();
  105994. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  105995. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  105996. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  105997. // Step camera rotation by rotation speed
  105998. if (_this._attachedCamera) {
  105999. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  106000. }
  106001. });
  106002. };
  106003. AutoRotationBehavior.prototype.detach = function () {
  106004. if (!this._attachedCamera) {
  106005. return;
  106006. }
  106007. var scene = this._attachedCamera.getScene();
  106008. if (this._onPrePointerObservableObserver) {
  106009. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  106010. }
  106011. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  106012. this._attachedCamera = null;
  106013. };
  106014. /**
  106015. * Returns true if user is scrolling.
  106016. * @return true if user is scrolling.
  106017. */
  106018. AutoRotationBehavior.prototype._userIsZooming = function () {
  106019. if (!this._attachedCamera) {
  106020. return false;
  106021. }
  106022. return this._attachedCamera.inertialRadiusOffset !== 0;
  106023. };
  106024. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  106025. if (!this._attachedCamera) {
  106026. return false;
  106027. }
  106028. var zoomHasHitLimit = false;
  106029. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  106030. zoomHasHitLimit = true;
  106031. }
  106032. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  106033. this._lastFrameRadius = this._attachedCamera.radius;
  106034. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  106035. };
  106036. /**
  106037. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  106038. */
  106039. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  106040. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  106041. this._lastInteractionTime = BABYLON.Tools.Now;
  106042. }
  106043. };
  106044. // Tools
  106045. AutoRotationBehavior.prototype._userIsMoving = function () {
  106046. if (!this._attachedCamera) {
  106047. return false;
  106048. }
  106049. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  106050. this._attachedCamera.inertialBetaOffset !== 0 ||
  106051. this._attachedCamera.inertialRadiusOffset !== 0 ||
  106052. this._attachedCamera.inertialPanningX !== 0 ||
  106053. this._attachedCamera.inertialPanningY !== 0 ||
  106054. this._isPointerDown;
  106055. };
  106056. return AutoRotationBehavior;
  106057. }());
  106058. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  106059. })(BABYLON || (BABYLON = {}));
  106060. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  106061. var BABYLON;
  106062. (function (BABYLON) {
  106063. var NullEngineOptions = /** @class */ (function () {
  106064. function NullEngineOptions() {
  106065. this.renderWidth = 512;
  106066. this.renderHeight = 256;
  106067. this.textureSize = 512;
  106068. this.deterministicLockstep = false;
  106069. this.lockstepMaxSteps = 4;
  106070. }
  106071. return NullEngineOptions;
  106072. }());
  106073. BABYLON.NullEngineOptions = NullEngineOptions;
  106074. /**
  106075. * The null engine class provides support for headless version of babylon.js.
  106076. * This can be used in server side scenario or for testing purposes
  106077. */
  106078. var NullEngine = /** @class */ (function (_super) {
  106079. __extends(NullEngine, _super);
  106080. function NullEngine(options) {
  106081. if (options === void 0) { options = new NullEngineOptions(); }
  106082. var _this = _super.call(this, null) || this;
  106083. if (options.deterministicLockstep === undefined) {
  106084. options.deterministicLockstep = false;
  106085. }
  106086. if (options.lockstepMaxSteps === undefined) {
  106087. options.lockstepMaxSteps = 4;
  106088. }
  106089. _this._options = options;
  106090. // Init caps
  106091. // We consider we are on a webgl1 capable device
  106092. _this._caps = new BABYLON.EngineCapabilities();
  106093. _this._caps.maxTexturesImageUnits = 16;
  106094. _this._caps.maxVertexTextureImageUnits = 16;
  106095. _this._caps.maxTextureSize = 512;
  106096. _this._caps.maxCubemapTextureSize = 512;
  106097. _this._caps.maxRenderTextureSize = 512;
  106098. _this._caps.maxVertexAttribs = 16;
  106099. _this._caps.maxVaryingVectors = 16;
  106100. _this._caps.maxFragmentUniformVectors = 16;
  106101. _this._caps.maxVertexUniformVectors = 16;
  106102. // Extensions
  106103. _this._caps.standardDerivatives = false;
  106104. _this._caps.astc = null;
  106105. _this._caps.s3tc = null;
  106106. _this._caps.pvrtc = null;
  106107. _this._caps.etc1 = null;
  106108. _this._caps.etc2 = null;
  106109. _this._caps.textureAnisotropicFilterExtension = null;
  106110. _this._caps.maxAnisotropy = 0;
  106111. _this._caps.uintIndices = false;
  106112. _this._caps.fragmentDepthSupported = false;
  106113. _this._caps.highPrecisionShaderSupported = true;
  106114. _this._caps.colorBufferFloat = false;
  106115. _this._caps.textureFloat = false;
  106116. _this._caps.textureFloatLinearFiltering = false;
  106117. _this._caps.textureFloatRender = false;
  106118. _this._caps.textureHalfFloat = false;
  106119. _this._caps.textureHalfFloatLinearFiltering = false;
  106120. _this._caps.textureHalfFloatRender = false;
  106121. _this._caps.textureLOD = false;
  106122. _this._caps.drawBuffersExtension = false;
  106123. _this._caps.depthTextureExtension = false;
  106124. _this._caps.vertexArrayObject = false;
  106125. _this._caps.instancedArrays = false;
  106126. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  106127. // Wrappers
  106128. if (typeof URL === "undefined") {
  106129. URL = {
  106130. createObjectURL: function () { },
  106131. revokeObjectURL: function () { }
  106132. };
  106133. }
  106134. if (typeof Blob === "undefined") {
  106135. Blob = function () { };
  106136. }
  106137. return _this;
  106138. }
  106139. NullEngine.prototype.isDeterministicLockStep = function () {
  106140. return this._options.deterministicLockstep;
  106141. };
  106142. NullEngine.prototype.getLockstepMaxSteps = function () {
  106143. return this._options.lockstepMaxSteps;
  106144. };
  106145. NullEngine.prototype.getHardwareScalingLevel = function () {
  106146. return 1.0;
  106147. };
  106148. NullEngine.prototype.createVertexBuffer = function (vertices) {
  106149. return {
  106150. capacity: 0,
  106151. references: 1,
  106152. is32Bits: false
  106153. };
  106154. };
  106155. NullEngine.prototype.createIndexBuffer = function (indices) {
  106156. return {
  106157. capacity: 0,
  106158. references: 1,
  106159. is32Bits: false
  106160. };
  106161. };
  106162. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  106163. if (stencil === void 0) { stencil = false; }
  106164. };
  106165. NullEngine.prototype.getRenderWidth = function (useScreen) {
  106166. if (useScreen === void 0) { useScreen = false; }
  106167. if (!useScreen && this._currentRenderTarget) {
  106168. return this._currentRenderTarget.width;
  106169. }
  106170. return this._options.renderWidth;
  106171. };
  106172. NullEngine.prototype.getRenderHeight = function (useScreen) {
  106173. if (useScreen === void 0) { useScreen = false; }
  106174. if (!useScreen && this._currentRenderTarget) {
  106175. return this._currentRenderTarget.height;
  106176. }
  106177. return this._options.renderHeight;
  106178. };
  106179. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  106180. this._cachedViewport = viewport;
  106181. };
  106182. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  106183. return {
  106184. transformFeedback: null,
  106185. __SPECTOR_rebuildProgram: null
  106186. };
  106187. };
  106188. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  106189. return [];
  106190. };
  106191. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  106192. return [];
  106193. };
  106194. NullEngine.prototype.bindSamplers = function (effect) {
  106195. this._currentEffect = null;
  106196. };
  106197. NullEngine.prototype.enableEffect = function (effect) {
  106198. this._currentEffect = effect;
  106199. if (effect.onBind) {
  106200. effect.onBind(effect);
  106201. }
  106202. if (effect._onBindObservable) {
  106203. effect._onBindObservable.notifyObservers(effect);
  106204. }
  106205. };
  106206. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  106207. if (zOffset === void 0) { zOffset = 0; }
  106208. if (reverseSide === void 0) { reverseSide = false; }
  106209. };
  106210. NullEngine.prototype.setIntArray = function (uniform, array) {
  106211. };
  106212. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  106213. };
  106214. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  106215. };
  106216. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  106217. };
  106218. NullEngine.prototype.setFloatArray = function (uniform, array) {
  106219. };
  106220. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  106221. };
  106222. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  106223. };
  106224. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  106225. };
  106226. NullEngine.prototype.setArray = function (uniform, array) {
  106227. };
  106228. NullEngine.prototype.setArray2 = function (uniform, array) {
  106229. };
  106230. NullEngine.prototype.setArray3 = function (uniform, array) {
  106231. };
  106232. NullEngine.prototype.setArray4 = function (uniform, array) {
  106233. };
  106234. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  106235. };
  106236. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  106237. };
  106238. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  106239. };
  106240. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  106241. };
  106242. NullEngine.prototype.setFloat = function (uniform, value) {
  106243. };
  106244. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  106245. };
  106246. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  106247. };
  106248. NullEngine.prototype.setBool = function (uniform, bool) {
  106249. };
  106250. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  106251. };
  106252. NullEngine.prototype.setColor3 = function (uniform, color3) {
  106253. };
  106254. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  106255. };
  106256. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  106257. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  106258. if (this._alphaMode === mode) {
  106259. return;
  106260. }
  106261. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  106262. if (!noDepthWriteChange) {
  106263. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  106264. }
  106265. this._alphaMode = mode;
  106266. };
  106267. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  106268. };
  106269. NullEngine.prototype.wipeCaches = function (bruteForce) {
  106270. if (this.preventCacheWipeBetweenFrames) {
  106271. return;
  106272. }
  106273. this.resetTextureCache();
  106274. this._currentEffect = null;
  106275. if (bruteForce) {
  106276. this._currentProgram = null;
  106277. this._stencilState.reset();
  106278. this._depthCullingState.reset();
  106279. this._alphaState.reset();
  106280. }
  106281. this._cachedVertexBuffers = null;
  106282. this._cachedIndexBuffer = null;
  106283. this._cachedEffectForVertexBuffers = null;
  106284. };
  106285. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  106286. };
  106287. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  106288. };
  106289. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  106290. };
  106291. /** @hidden */
  106292. NullEngine.prototype._createTexture = function () {
  106293. return {};
  106294. };
  106295. /** @hidden */
  106296. NullEngine.prototype._releaseTexture = function (texture) {
  106297. };
  106298. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  106299. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  106300. if (onLoad === void 0) { onLoad = null; }
  106301. if (onError === void 0) { onError = null; }
  106302. if (buffer === void 0) { buffer = null; }
  106303. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  106304. var url = String(urlArg);
  106305. texture.url = url;
  106306. texture.generateMipMaps = !noMipmap;
  106307. texture.samplingMode = samplingMode;
  106308. texture.invertY = invertY;
  106309. texture.baseWidth = this._options.textureSize;
  106310. texture.baseHeight = this._options.textureSize;
  106311. texture.width = this._options.textureSize;
  106312. texture.height = this._options.textureSize;
  106313. if (format) {
  106314. texture.format = format;
  106315. }
  106316. texture.isReady = true;
  106317. if (onLoad) {
  106318. onLoad();
  106319. }
  106320. this._internalTexturesCache.push(texture);
  106321. return texture;
  106322. };
  106323. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  106324. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  106325. if (options !== undefined && typeof options === "object") {
  106326. fullOptions.generateMipMaps = options.generateMipMaps;
  106327. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  106328. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  106329. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  106330. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  106331. }
  106332. else {
  106333. fullOptions.generateMipMaps = options;
  106334. fullOptions.generateDepthBuffer = true;
  106335. fullOptions.generateStencilBuffer = false;
  106336. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  106337. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  106338. }
  106339. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  106340. var width = size.width || size;
  106341. var height = size.height || size;
  106342. texture._depthStencilBuffer = {};
  106343. texture._framebuffer = {};
  106344. texture.baseWidth = width;
  106345. texture.baseHeight = height;
  106346. texture.width = width;
  106347. texture.height = height;
  106348. texture.isReady = true;
  106349. texture.samples = 1;
  106350. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  106351. texture.samplingMode = fullOptions.samplingMode;
  106352. texture.type = fullOptions.type;
  106353. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  106354. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  106355. this._internalTexturesCache.push(texture);
  106356. return texture;
  106357. };
  106358. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  106359. texture.samplingMode = samplingMode;
  106360. };
  106361. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  106362. if (this._currentRenderTarget) {
  106363. this.unBindFramebuffer(this._currentRenderTarget);
  106364. }
  106365. this._currentRenderTarget = texture;
  106366. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  106367. if (this._cachedViewport && !forceFullscreenViewport) {
  106368. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  106369. }
  106370. };
  106371. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  106372. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  106373. this._currentRenderTarget = null;
  106374. if (onBeforeUnbind) {
  106375. if (texture._MSAAFramebuffer) {
  106376. this._currentFramebuffer = texture._framebuffer;
  106377. }
  106378. onBeforeUnbind();
  106379. }
  106380. this._currentFramebuffer = null;
  106381. };
  106382. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  106383. var vbo = {
  106384. capacity: 1,
  106385. references: 1,
  106386. is32Bits: false
  106387. };
  106388. return vbo;
  106389. };
  106390. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  106391. if (premulAlpha === void 0) { premulAlpha = false; }
  106392. };
  106393. /**
  106394. * @hidden
  106395. * Get the current error code of the webGL context
  106396. * @returns the error code
  106397. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  106398. */
  106399. NullEngine.prototype.getError = function () {
  106400. return 0;
  106401. };
  106402. /** @hidden */
  106403. NullEngine.prototype._getUnpackAlignement = function () {
  106404. return 1;
  106405. };
  106406. /** @hidden */
  106407. NullEngine.prototype._unpackFlipY = function (value) {
  106408. };
  106409. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  106410. if (offset === void 0) { offset = 0; }
  106411. };
  106412. /**
  106413. * Updates a dynamic vertex buffer.
  106414. * @param vertexBuffer the vertex buffer to update
  106415. * @param data the data used to update the vertex buffer
  106416. * @param byteOffset the byte offset of the data (optional)
  106417. * @param byteLength the byte length of the data (optional)
  106418. */
  106419. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  106420. };
  106421. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  106422. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  106423. this._boundTexturesCache[this._activeChannel] = texture;
  106424. return true;
  106425. }
  106426. return false;
  106427. };
  106428. /** @hidden */
  106429. NullEngine.prototype._bindTexture = function (channel, texture) {
  106430. if (channel < 0) {
  106431. return;
  106432. }
  106433. this._bindTextureDirectly(0, texture);
  106434. };
  106435. /** @hidden */
  106436. NullEngine.prototype._releaseBuffer = function (buffer) {
  106437. buffer.references--;
  106438. if (buffer.references === 0) {
  106439. return true;
  106440. }
  106441. return false;
  106442. };
  106443. NullEngine.prototype.releaseEffects = function () {
  106444. };
  106445. NullEngine.prototype.displayLoadingUI = function () {
  106446. };
  106447. NullEngine.prototype.hideLoadingUI = function () {
  106448. };
  106449. /** @hidden */
  106450. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  106451. if (faceIndex === void 0) { faceIndex = 0; }
  106452. if (lod === void 0) { lod = 0; }
  106453. };
  106454. /** @hidden */
  106455. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  106456. if (faceIndex === void 0) { faceIndex = 0; }
  106457. if (lod === void 0) { lod = 0; }
  106458. };
  106459. /** @hidden */
  106460. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  106461. if (faceIndex === void 0) { faceIndex = 0; }
  106462. if (lod === void 0) { lod = 0; }
  106463. };
  106464. /** @hidden */
  106465. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  106466. if (faceIndex === void 0) { faceIndex = 0; }
  106467. if (lod === void 0) { lod = 0; }
  106468. };
  106469. return NullEngine;
  106470. }(BABYLON.Engine));
  106471. BABYLON.NullEngine = NullEngine;
  106472. })(BABYLON || (BABYLON = {}));
  106473. //# sourceMappingURL=babylon.nullEngine.js.map
  106474. var BABYLON;
  106475. (function (BABYLON) {
  106476. /**
  106477. * This class can be used to get instrumentation data from a Babylon engine
  106478. */
  106479. var EngineInstrumentation = /** @class */ (function () {
  106480. function EngineInstrumentation(engine) {
  106481. this.engine = engine;
  106482. this._captureGPUFrameTime = false;
  106483. this._gpuFrameTime = new BABYLON.PerfCounter();
  106484. this._captureShaderCompilationTime = false;
  106485. this._shaderCompilationTime = new BABYLON.PerfCounter();
  106486. // Observers
  106487. this._onBeginFrameObserver = null;
  106488. this._onEndFrameObserver = null;
  106489. this._onBeforeShaderCompilationObserver = null;
  106490. this._onAfterShaderCompilationObserver = null;
  106491. }
  106492. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  106493. // Properties
  106494. /**
  106495. * Gets the perf counter used for GPU frame time
  106496. */
  106497. get: function () {
  106498. return this._gpuFrameTime;
  106499. },
  106500. enumerable: true,
  106501. configurable: true
  106502. });
  106503. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  106504. /**
  106505. * Gets the GPU frame time capture status
  106506. */
  106507. get: function () {
  106508. return this._captureGPUFrameTime;
  106509. },
  106510. /**
  106511. * Enable or disable the GPU frame time capture
  106512. */
  106513. set: function (value) {
  106514. var _this = this;
  106515. if (value === this._captureGPUFrameTime) {
  106516. return;
  106517. }
  106518. this._captureGPUFrameTime = value;
  106519. if (value) {
  106520. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  106521. if (!_this._gpuFrameTimeToken) {
  106522. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  106523. }
  106524. });
  106525. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  106526. if (!_this._gpuFrameTimeToken) {
  106527. return;
  106528. }
  106529. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  106530. if (time > -1) {
  106531. _this._gpuFrameTimeToken = null;
  106532. _this._gpuFrameTime.fetchNewFrame();
  106533. _this._gpuFrameTime.addCount(time, true);
  106534. }
  106535. });
  106536. }
  106537. else {
  106538. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  106539. this._onBeginFrameObserver = null;
  106540. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  106541. this._onEndFrameObserver = null;
  106542. }
  106543. },
  106544. enumerable: true,
  106545. configurable: true
  106546. });
  106547. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  106548. /**
  106549. * Gets the perf counter used for shader compilation time
  106550. */
  106551. get: function () {
  106552. return this._shaderCompilationTime;
  106553. },
  106554. enumerable: true,
  106555. configurable: true
  106556. });
  106557. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  106558. /**
  106559. * Gets the shader compilation time capture status
  106560. */
  106561. get: function () {
  106562. return this._captureShaderCompilationTime;
  106563. },
  106564. /**
  106565. * Enable or disable the shader compilation time capture
  106566. */
  106567. set: function (value) {
  106568. var _this = this;
  106569. if (value === this._captureShaderCompilationTime) {
  106570. return;
  106571. }
  106572. this._captureShaderCompilationTime = value;
  106573. if (value) {
  106574. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  106575. _this._shaderCompilationTime.fetchNewFrame();
  106576. _this._shaderCompilationTime.beginMonitoring();
  106577. });
  106578. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  106579. _this._shaderCompilationTime.endMonitoring();
  106580. });
  106581. }
  106582. else {
  106583. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  106584. this._onBeforeShaderCompilationObserver = null;
  106585. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  106586. this._onAfterShaderCompilationObserver = null;
  106587. }
  106588. },
  106589. enumerable: true,
  106590. configurable: true
  106591. });
  106592. EngineInstrumentation.prototype.dispose = function () {
  106593. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  106594. this._onBeginFrameObserver = null;
  106595. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  106596. this._onEndFrameObserver = null;
  106597. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  106598. this._onBeforeShaderCompilationObserver = null;
  106599. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  106600. this._onAfterShaderCompilationObserver = null;
  106601. this.engine = null;
  106602. };
  106603. return EngineInstrumentation;
  106604. }());
  106605. BABYLON.EngineInstrumentation = EngineInstrumentation;
  106606. })(BABYLON || (BABYLON = {}));
  106607. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  106608. var BABYLON;
  106609. (function (BABYLON) {
  106610. /**
  106611. * This class can be used to get instrumentation data from a Babylon engine
  106612. */
  106613. var SceneInstrumentation = /** @class */ (function () {
  106614. function SceneInstrumentation(scene) {
  106615. var _this = this;
  106616. this.scene = scene;
  106617. this._captureActiveMeshesEvaluationTime = false;
  106618. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  106619. this._captureRenderTargetsRenderTime = false;
  106620. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  106621. this._captureFrameTime = false;
  106622. this._frameTime = new BABYLON.PerfCounter();
  106623. this._captureRenderTime = false;
  106624. this._renderTime = new BABYLON.PerfCounter();
  106625. this._captureInterFrameTime = false;
  106626. this._interFrameTime = new BABYLON.PerfCounter();
  106627. this._captureParticlesRenderTime = false;
  106628. this._particlesRenderTime = new BABYLON.PerfCounter();
  106629. this._captureSpritesRenderTime = false;
  106630. this._spritesRenderTime = new BABYLON.PerfCounter();
  106631. this._capturePhysicsTime = false;
  106632. this._physicsTime = new BABYLON.PerfCounter();
  106633. this._captureAnimationsTime = false;
  106634. this._animationsTime = new BABYLON.PerfCounter();
  106635. this._captureCameraRenderTime = false;
  106636. this._cameraRenderTime = new BABYLON.PerfCounter();
  106637. // Observers
  106638. this._onBeforeActiveMeshesEvaluationObserver = null;
  106639. this._onAfterActiveMeshesEvaluationObserver = null;
  106640. this._onBeforeRenderTargetsRenderObserver = null;
  106641. this._onAfterRenderTargetsRenderObserver = null;
  106642. this._onAfterRenderObserver = null;
  106643. this._onBeforeDrawPhaseObserver = null;
  106644. this._onAfterDrawPhaseObserver = null;
  106645. this._onBeforeAnimationsObserver = null;
  106646. this._onBeforeParticlesRenderingObserver = null;
  106647. this._onAfterParticlesRenderingObserver = null;
  106648. this._onBeforeSpritesRenderingObserver = null;
  106649. this._onAfterSpritesRenderingObserver = null;
  106650. this._onBeforePhysicsObserver = null;
  106651. this._onAfterPhysicsObserver = null;
  106652. this._onAfterAnimationsObserver = null;
  106653. this._onBeforeCameraRenderObserver = null;
  106654. this._onAfterCameraRenderObserver = null;
  106655. // Before render
  106656. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  106657. if (_this._captureActiveMeshesEvaluationTime) {
  106658. _this._activeMeshesEvaluationTime.fetchNewFrame();
  106659. }
  106660. if (_this._captureRenderTargetsRenderTime) {
  106661. _this._renderTargetsRenderTime.fetchNewFrame();
  106662. }
  106663. if (_this._captureFrameTime) {
  106664. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  106665. _this._frameTime.beginMonitoring();
  106666. }
  106667. if (_this._captureInterFrameTime) {
  106668. _this._interFrameTime.endMonitoring();
  106669. }
  106670. if (_this._captureParticlesRenderTime) {
  106671. _this._particlesRenderTime.fetchNewFrame();
  106672. }
  106673. if (_this._captureSpritesRenderTime) {
  106674. _this._spritesRenderTime.fetchNewFrame();
  106675. }
  106676. if (_this._captureAnimationsTime) {
  106677. _this._animationsTime.beginMonitoring();
  106678. }
  106679. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  106680. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  106681. });
  106682. // After render
  106683. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  106684. if (_this._captureFrameTime) {
  106685. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  106686. _this._frameTime.endMonitoring();
  106687. }
  106688. if (_this._captureRenderTime) {
  106689. _this._renderTime.endMonitoring(false);
  106690. }
  106691. if (_this._captureInterFrameTime) {
  106692. _this._interFrameTime.beginMonitoring();
  106693. }
  106694. });
  106695. }
  106696. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  106697. // Properties
  106698. /**
  106699. * Gets the perf counter used for active meshes evaluation time
  106700. */
  106701. get: function () {
  106702. return this._activeMeshesEvaluationTime;
  106703. },
  106704. enumerable: true,
  106705. configurable: true
  106706. });
  106707. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  106708. /**
  106709. * Gets the active meshes evaluation time capture status
  106710. */
  106711. get: function () {
  106712. return this._captureActiveMeshesEvaluationTime;
  106713. },
  106714. /**
  106715. * Enable or disable the active meshes evaluation time capture
  106716. */
  106717. set: function (value) {
  106718. var _this = this;
  106719. if (value === this._captureActiveMeshesEvaluationTime) {
  106720. return;
  106721. }
  106722. this._captureActiveMeshesEvaluationTime = value;
  106723. if (value) {
  106724. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  106725. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  106726. _this._activeMeshesEvaluationTime.beginMonitoring();
  106727. });
  106728. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  106729. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  106730. _this._activeMeshesEvaluationTime.endMonitoring();
  106731. });
  106732. }
  106733. else {
  106734. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  106735. this._onBeforeActiveMeshesEvaluationObserver = null;
  106736. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  106737. this._onAfterActiveMeshesEvaluationObserver = null;
  106738. }
  106739. },
  106740. enumerable: true,
  106741. configurable: true
  106742. });
  106743. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  106744. /**
  106745. * Gets the perf counter used for render targets render time
  106746. */
  106747. get: function () {
  106748. return this._renderTargetsRenderTime;
  106749. },
  106750. enumerable: true,
  106751. configurable: true
  106752. });
  106753. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  106754. /**
  106755. * Gets the render targets render time capture status
  106756. */
  106757. get: function () {
  106758. return this._captureRenderTargetsRenderTime;
  106759. },
  106760. /**
  106761. * Enable or disable the render targets render time capture
  106762. */
  106763. set: function (value) {
  106764. var _this = this;
  106765. if (value === this._captureRenderTargetsRenderTime) {
  106766. return;
  106767. }
  106768. this._captureRenderTargetsRenderTime = value;
  106769. if (value) {
  106770. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  106771. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  106772. _this._renderTargetsRenderTime.beginMonitoring();
  106773. });
  106774. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  106775. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  106776. _this._renderTargetsRenderTime.endMonitoring(false);
  106777. });
  106778. }
  106779. else {
  106780. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  106781. this._onBeforeRenderTargetsRenderObserver = null;
  106782. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  106783. this._onAfterRenderTargetsRenderObserver = null;
  106784. }
  106785. },
  106786. enumerable: true,
  106787. configurable: true
  106788. });
  106789. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  106790. /**
  106791. * Gets the perf counter used for particles render time
  106792. */
  106793. get: function () {
  106794. return this._particlesRenderTime;
  106795. },
  106796. enumerable: true,
  106797. configurable: true
  106798. });
  106799. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  106800. /**
  106801. * Gets the particles render time capture status
  106802. */
  106803. get: function () {
  106804. return this._captureParticlesRenderTime;
  106805. },
  106806. /**
  106807. * Enable or disable the particles render time capture
  106808. */
  106809. set: function (value) {
  106810. var _this = this;
  106811. if (value === this._captureParticlesRenderTime) {
  106812. return;
  106813. }
  106814. this._captureParticlesRenderTime = value;
  106815. if (value) {
  106816. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  106817. BABYLON.Tools.StartPerformanceCounter("Particles");
  106818. _this._particlesRenderTime.beginMonitoring();
  106819. });
  106820. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  106821. BABYLON.Tools.EndPerformanceCounter("Particles");
  106822. _this._particlesRenderTime.endMonitoring(false);
  106823. });
  106824. }
  106825. else {
  106826. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  106827. this._onBeforeParticlesRenderingObserver = null;
  106828. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  106829. this._onAfterParticlesRenderingObserver = null;
  106830. }
  106831. },
  106832. enumerable: true,
  106833. configurable: true
  106834. });
  106835. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  106836. /**
  106837. * Gets the perf counter used for sprites render time
  106838. */
  106839. get: function () {
  106840. return this._spritesRenderTime;
  106841. },
  106842. enumerable: true,
  106843. configurable: true
  106844. });
  106845. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  106846. /**
  106847. * Gets the sprites render time capture status
  106848. */
  106849. get: function () {
  106850. return this._captureSpritesRenderTime;
  106851. },
  106852. /**
  106853. * Enable or disable the sprites render time capture
  106854. */
  106855. set: function (value) {
  106856. var _this = this;
  106857. if (value === this._captureSpritesRenderTime) {
  106858. return;
  106859. }
  106860. this._captureSpritesRenderTime = value;
  106861. if (!this.scene.spriteManagers) {
  106862. return;
  106863. }
  106864. if (value) {
  106865. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  106866. BABYLON.Tools.StartPerformanceCounter("Sprites");
  106867. _this._spritesRenderTime.beginMonitoring();
  106868. });
  106869. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  106870. BABYLON.Tools.EndPerformanceCounter("Sprites");
  106871. _this._spritesRenderTime.endMonitoring(false);
  106872. });
  106873. }
  106874. else {
  106875. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  106876. this._onBeforeSpritesRenderingObserver = null;
  106877. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  106878. this._onAfterSpritesRenderingObserver = null;
  106879. }
  106880. },
  106881. enumerable: true,
  106882. configurable: true
  106883. });
  106884. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  106885. /**
  106886. * Gets the perf counter used for physics time
  106887. */
  106888. get: function () {
  106889. return this._physicsTime;
  106890. },
  106891. enumerable: true,
  106892. configurable: true
  106893. });
  106894. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  106895. /**
  106896. * Gets the physics time capture status
  106897. */
  106898. get: function () {
  106899. return this._capturePhysicsTime;
  106900. },
  106901. /**
  106902. * Enable or disable the physics time capture
  106903. */
  106904. set: function (value) {
  106905. var _this = this;
  106906. if (value === this._capturePhysicsTime) {
  106907. return;
  106908. }
  106909. if (!this.scene.onBeforePhysicsObservable) {
  106910. return;
  106911. }
  106912. this._capturePhysicsTime = value;
  106913. if (value) {
  106914. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  106915. BABYLON.Tools.StartPerformanceCounter("Physics");
  106916. _this._physicsTime.beginMonitoring();
  106917. });
  106918. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  106919. BABYLON.Tools.EndPerformanceCounter("Physics");
  106920. _this._physicsTime.endMonitoring();
  106921. });
  106922. }
  106923. else {
  106924. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  106925. this._onBeforePhysicsObserver = null;
  106926. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  106927. this._onAfterPhysicsObserver = null;
  106928. }
  106929. },
  106930. enumerable: true,
  106931. configurable: true
  106932. });
  106933. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  106934. /**
  106935. * Gets the perf counter used for animations time
  106936. */
  106937. get: function () {
  106938. return this._animationsTime;
  106939. },
  106940. enumerable: true,
  106941. configurable: true
  106942. });
  106943. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  106944. /**
  106945. * Gets the animations time capture status
  106946. */
  106947. get: function () {
  106948. return this._captureAnimationsTime;
  106949. },
  106950. /**
  106951. * Enable or disable the animations time capture
  106952. */
  106953. set: function (value) {
  106954. var _this = this;
  106955. if (value === this._captureAnimationsTime) {
  106956. return;
  106957. }
  106958. this._captureAnimationsTime = value;
  106959. if (value) {
  106960. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  106961. _this._animationsTime.endMonitoring();
  106962. });
  106963. }
  106964. else {
  106965. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  106966. this._onAfterAnimationsObserver = null;
  106967. }
  106968. },
  106969. enumerable: true,
  106970. configurable: true
  106971. });
  106972. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  106973. /**
  106974. * Gets the perf counter used for frame time capture
  106975. */
  106976. get: function () {
  106977. return this._frameTime;
  106978. },
  106979. enumerable: true,
  106980. configurable: true
  106981. });
  106982. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  106983. /**
  106984. * Gets the frame time capture status
  106985. */
  106986. get: function () {
  106987. return this._captureFrameTime;
  106988. },
  106989. /**
  106990. * Enable or disable the frame time capture
  106991. */
  106992. set: function (value) {
  106993. this._captureFrameTime = value;
  106994. },
  106995. enumerable: true,
  106996. configurable: true
  106997. });
  106998. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  106999. /**
  107000. * Gets the perf counter used for inter-frames time capture
  107001. */
  107002. get: function () {
  107003. return this._interFrameTime;
  107004. },
  107005. enumerable: true,
  107006. configurable: true
  107007. });
  107008. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  107009. /**
  107010. * Gets the inter-frames time capture status
  107011. */
  107012. get: function () {
  107013. return this._captureInterFrameTime;
  107014. },
  107015. /**
  107016. * Enable or disable the inter-frames time capture
  107017. */
  107018. set: function (value) {
  107019. this._captureInterFrameTime = value;
  107020. },
  107021. enumerable: true,
  107022. configurable: true
  107023. });
  107024. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  107025. /**
  107026. * Gets the perf counter used for render time capture
  107027. */
  107028. get: function () {
  107029. return this._renderTime;
  107030. },
  107031. enumerable: true,
  107032. configurable: true
  107033. });
  107034. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  107035. /**
  107036. * Gets the render time capture status
  107037. */
  107038. get: function () {
  107039. return this._captureRenderTime;
  107040. },
  107041. /**
  107042. * Enable or disable the render time capture
  107043. */
  107044. set: function (value) {
  107045. var _this = this;
  107046. if (value === this._captureRenderTime) {
  107047. return;
  107048. }
  107049. this._captureRenderTime = value;
  107050. if (value) {
  107051. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  107052. _this._renderTime.beginMonitoring();
  107053. BABYLON.Tools.StartPerformanceCounter("Main render");
  107054. });
  107055. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  107056. _this._renderTime.endMonitoring(false);
  107057. BABYLON.Tools.EndPerformanceCounter("Main render");
  107058. });
  107059. }
  107060. else {
  107061. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  107062. this._onBeforeDrawPhaseObserver = null;
  107063. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  107064. this._onAfterDrawPhaseObserver = null;
  107065. }
  107066. },
  107067. enumerable: true,
  107068. configurable: true
  107069. });
  107070. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  107071. /**
  107072. * Gets the perf counter used for camera render time capture
  107073. */
  107074. get: function () {
  107075. return this._cameraRenderTime;
  107076. },
  107077. enumerable: true,
  107078. configurable: true
  107079. });
  107080. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  107081. /**
  107082. * Gets the camera render time capture status
  107083. */
  107084. get: function () {
  107085. return this._captureCameraRenderTime;
  107086. },
  107087. /**
  107088. * Enable or disable the camera render time capture
  107089. */
  107090. set: function (value) {
  107091. var _this = this;
  107092. if (value === this._captureCameraRenderTime) {
  107093. return;
  107094. }
  107095. this._captureCameraRenderTime = value;
  107096. if (value) {
  107097. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  107098. _this._cameraRenderTime.beginMonitoring();
  107099. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  107100. });
  107101. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  107102. _this._cameraRenderTime.endMonitoring(false);
  107103. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  107104. });
  107105. }
  107106. else {
  107107. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  107108. this._onBeforeCameraRenderObserver = null;
  107109. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  107110. this._onAfterCameraRenderObserver = null;
  107111. }
  107112. },
  107113. enumerable: true,
  107114. configurable: true
  107115. });
  107116. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  107117. /**
  107118. * Gets the perf counter used for draw calls
  107119. */
  107120. get: function () {
  107121. return this.scene.getEngine()._drawCalls;
  107122. },
  107123. enumerable: true,
  107124. configurable: true
  107125. });
  107126. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  107127. /**
  107128. * Gets the perf counter used for texture collisions
  107129. */
  107130. get: function () {
  107131. return this.scene.getEngine()._textureCollisions;
  107132. },
  107133. enumerable: true,
  107134. configurable: true
  107135. });
  107136. SceneInstrumentation.prototype.dispose = function () {
  107137. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  107138. this._onAfterRenderObserver = null;
  107139. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  107140. this._onBeforeActiveMeshesEvaluationObserver = null;
  107141. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  107142. this._onAfterActiveMeshesEvaluationObserver = null;
  107143. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  107144. this._onBeforeRenderTargetsRenderObserver = null;
  107145. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  107146. this._onAfterRenderTargetsRenderObserver = null;
  107147. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  107148. this._onBeforeAnimationsObserver = null;
  107149. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  107150. this._onBeforeParticlesRenderingObserver = null;
  107151. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  107152. this._onAfterParticlesRenderingObserver = null;
  107153. if (this._onBeforeSpritesRenderingObserver) {
  107154. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  107155. this._onBeforeSpritesRenderingObserver = null;
  107156. }
  107157. if (this._onAfterSpritesRenderingObserver) {
  107158. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  107159. this._onAfterSpritesRenderingObserver = null;
  107160. }
  107161. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  107162. this._onBeforeDrawPhaseObserver = null;
  107163. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  107164. this._onAfterDrawPhaseObserver = null;
  107165. if (this._onBeforePhysicsObserver) {
  107166. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  107167. this._onBeforePhysicsObserver = null;
  107168. }
  107169. if (this._onAfterPhysicsObserver) {
  107170. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  107171. this._onAfterPhysicsObserver = null;
  107172. }
  107173. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  107174. this._onAfterAnimationsObserver = null;
  107175. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  107176. this._onBeforeCameraRenderObserver = null;
  107177. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  107178. this._onAfterCameraRenderObserver = null;
  107179. this.scene = null;
  107180. };
  107181. return SceneInstrumentation;
  107182. }());
  107183. BABYLON.SceneInstrumentation = SceneInstrumentation;
  107184. })(BABYLON || (BABYLON = {}));
  107185. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  107186. var BABYLON;
  107187. (function (BABYLON) {
  107188. /**
  107189. * @hidden
  107190. **/
  107191. var _TimeToken = /** @class */ (function () {
  107192. function _TimeToken() {
  107193. this._timeElapsedQueryEnded = false;
  107194. }
  107195. return _TimeToken;
  107196. }());
  107197. BABYLON._TimeToken = _TimeToken;
  107198. })(BABYLON || (BABYLON = {}));
  107199. //# sourceMappingURL=babylon.timeToken.js.map
  107200. var BABYLON;
  107201. (function (BABYLON) {
  107202. /**
  107203. * Background material defines definition.
  107204. * @hidden Mainly internal Use
  107205. */
  107206. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  107207. __extends(BackgroundMaterialDefines, _super);
  107208. /**
  107209. * Constructor of the defines.
  107210. */
  107211. function BackgroundMaterialDefines() {
  107212. var _this = _super.call(this) || this;
  107213. /**
  107214. * True if the diffuse texture is in use.
  107215. */
  107216. _this.DIFFUSE = false;
  107217. /**
  107218. * The direct UV channel to use.
  107219. */
  107220. _this.DIFFUSEDIRECTUV = 0;
  107221. /**
  107222. * True if the diffuse texture is in gamma space.
  107223. */
  107224. _this.GAMMADIFFUSE = false;
  107225. /**
  107226. * True if the diffuse texture has opacity in the alpha channel.
  107227. */
  107228. _this.DIFFUSEHASALPHA = false;
  107229. /**
  107230. * True if you want the material to fade to transparent at grazing angle.
  107231. */
  107232. _this.OPACITYFRESNEL = false;
  107233. /**
  107234. * True if an extra blur needs to be added in the reflection.
  107235. */
  107236. _this.REFLECTIONBLUR = false;
  107237. /**
  107238. * True if you want the material to fade to reflection at grazing angle.
  107239. */
  107240. _this.REFLECTIONFRESNEL = false;
  107241. /**
  107242. * True if you want the material to falloff as far as you move away from the scene center.
  107243. */
  107244. _this.REFLECTIONFALLOFF = false;
  107245. /**
  107246. * False if the current Webgl implementation does not support the texture lod extension.
  107247. */
  107248. _this.TEXTURELODSUPPORT = false;
  107249. /**
  107250. * True to ensure the data are premultiplied.
  107251. */
  107252. _this.PREMULTIPLYALPHA = false;
  107253. /**
  107254. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  107255. */
  107256. _this.USERGBCOLOR = false;
  107257. /**
  107258. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  107259. * stays aligned with the desired configuration.
  107260. */
  107261. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  107262. /**
  107263. * True to add noise in order to reduce the banding effect.
  107264. */
  107265. _this.NOISE = false;
  107266. /**
  107267. * is the reflection texture in BGR color scheme?
  107268. * Mainly used to solve a bug in ios10 video tag
  107269. */
  107270. _this.REFLECTIONBGR = false;
  107271. _this.IMAGEPROCESSING = false;
  107272. _this.VIGNETTE = false;
  107273. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  107274. _this.VIGNETTEBLENDMODEOPAQUE = false;
  107275. _this.TONEMAPPING = false;
  107276. _this.TONEMAPPING_ACES = false;
  107277. _this.CONTRAST = false;
  107278. _this.COLORCURVES = false;
  107279. _this.COLORGRADING = false;
  107280. _this.COLORGRADING3D = false;
  107281. _this.SAMPLER3DGREENDEPTH = false;
  107282. _this.SAMPLER3DBGRMAP = false;
  107283. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  107284. _this.EXPOSURE = false;
  107285. // Reflection.
  107286. _this.REFLECTION = false;
  107287. _this.REFLECTIONMAP_3D = false;
  107288. _this.REFLECTIONMAP_SPHERICAL = false;
  107289. _this.REFLECTIONMAP_PLANAR = false;
  107290. _this.REFLECTIONMAP_CUBIC = false;
  107291. _this.REFLECTIONMAP_PROJECTION = false;
  107292. _this.REFLECTIONMAP_SKYBOX = false;
  107293. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  107294. _this.REFLECTIONMAP_EXPLICIT = false;
  107295. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  107296. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  107297. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  107298. _this.INVERTCUBICMAP = false;
  107299. _this.REFLECTIONMAP_OPPOSITEZ = false;
  107300. _this.LODINREFLECTIONALPHA = false;
  107301. _this.GAMMAREFLECTION = false;
  107302. _this.RGBDREFLECTION = false;
  107303. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  107304. // Default BJS.
  107305. _this.MAINUV1 = false;
  107306. _this.MAINUV2 = false;
  107307. _this.UV1 = false;
  107308. _this.UV2 = false;
  107309. _this.CLIPPLANE = false;
  107310. _this.CLIPPLANE2 = false;
  107311. _this.CLIPPLANE3 = false;
  107312. _this.CLIPPLANE4 = false;
  107313. _this.POINTSIZE = false;
  107314. _this.FOG = false;
  107315. _this.NORMAL = false;
  107316. _this.NUM_BONE_INFLUENCERS = 0;
  107317. _this.BonesPerMesh = 0;
  107318. _this.INSTANCES = false;
  107319. _this.SHADOWFLOAT = false;
  107320. _this.rebuild();
  107321. return _this;
  107322. }
  107323. return BackgroundMaterialDefines;
  107324. }(BABYLON.MaterialDefines));
  107325. /**
  107326. * Background material used to create an efficient environement around your scene.
  107327. */
  107328. var BackgroundMaterial = /** @class */ (function (_super) {
  107329. __extends(BackgroundMaterial, _super);
  107330. /**
  107331. * Instantiates a Background Material in the given scene
  107332. * @param name The friendly name of the material
  107333. * @param scene The scene to add the material to
  107334. */
  107335. function BackgroundMaterial(name, scene) {
  107336. var _this = _super.call(this, name, scene) || this;
  107337. /**
  107338. * Key light Color (multiply against the environement texture)
  107339. */
  107340. _this.primaryColor = BABYLON.Color3.White();
  107341. _this._primaryColorShadowLevel = 0;
  107342. _this._primaryColorHighlightLevel = 0;
  107343. /**
  107344. * Reflection Texture used in the material.
  107345. * Should be author in a specific way for the best result (refer to the documentation).
  107346. */
  107347. _this.reflectionTexture = null;
  107348. /**
  107349. * Reflection Texture level of blur.
  107350. *
  107351. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  107352. * texture twice.
  107353. */
  107354. _this.reflectionBlur = 0;
  107355. /**
  107356. * Diffuse Texture used in the material.
  107357. * Should be author in a specific way for the best result (refer to the documentation).
  107358. */
  107359. _this.diffuseTexture = null;
  107360. _this._shadowLights = null;
  107361. /**
  107362. * Specify the list of lights casting shadow on the material.
  107363. * All scene shadow lights will be included if null.
  107364. */
  107365. _this.shadowLights = null;
  107366. /**
  107367. * Helps adjusting the shadow to a softer level if required.
  107368. * 0 means black shadows and 1 means no shadows.
  107369. */
  107370. _this.shadowLevel = 0;
  107371. /**
  107372. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  107373. * It is usually zero but might be interesting to modify according to your setup.
  107374. */
  107375. _this.sceneCenter = BABYLON.Vector3.Zero();
  107376. /**
  107377. * This helps specifying that the material is falling off to the sky box at grazing angle.
  107378. * This helps ensuring a nice transition when the camera goes under the ground.
  107379. */
  107380. _this.opacityFresnel = true;
  107381. /**
  107382. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  107383. * This helps adding a mirror texture on the ground.
  107384. */
  107385. _this.reflectionFresnel = false;
  107386. /**
  107387. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  107388. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  107389. */
  107390. _this.reflectionFalloffDistance = 0.0;
  107391. /**
  107392. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  107393. */
  107394. _this.reflectionAmount = 1.0;
  107395. /**
  107396. * This specifies the weight of the reflection at grazing angle.
  107397. */
  107398. _this.reflectionReflectance0 = 0.05;
  107399. /**
  107400. * This specifies the weight of the reflection at a perpendicular point of view.
  107401. */
  107402. _this.reflectionReflectance90 = 0.5;
  107403. /**
  107404. * Helps to directly use the maps channels instead of their level.
  107405. */
  107406. _this.useRGBColor = true;
  107407. /**
  107408. * This helps reducing the banding effect that could occur on the background.
  107409. */
  107410. _this.enableNoise = false;
  107411. _this._fovMultiplier = 1.0;
  107412. /**
  107413. * Enable the FOV adjustment feature controlled by fovMultiplier.
  107414. */
  107415. _this.useEquirectangularFOV = false;
  107416. _this._maxSimultaneousLights = 4;
  107417. /**
  107418. * Number of Simultaneous lights allowed on the material.
  107419. */
  107420. _this.maxSimultaneousLights = 4;
  107421. /**
  107422. * Keep track of the image processing observer to allow dispose and replace.
  107423. */
  107424. _this._imageProcessingObserver = null;
  107425. /**
  107426. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  107427. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  107428. */
  107429. _this.switchToBGR = false;
  107430. // Temp values kept as cache in the material.
  107431. _this._renderTargets = new BABYLON.SmartArray(16);
  107432. _this._reflectionControls = BABYLON.Vector4.Zero();
  107433. _this._white = BABYLON.Color3.White();
  107434. _this._primaryShadowColor = BABYLON.Color3.Black();
  107435. _this._primaryHighlightColor = BABYLON.Color3.Black();
  107436. // Setup the default processing configuration to the scene.
  107437. _this._attachImageProcessingConfiguration(null);
  107438. _this.getRenderTargetTextures = function () {
  107439. _this._renderTargets.reset();
  107440. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  107441. _this._renderTargets.push(_this._diffuseTexture);
  107442. }
  107443. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  107444. _this._renderTargets.push(_this._reflectionTexture);
  107445. }
  107446. return _this._renderTargets;
  107447. };
  107448. return _this;
  107449. }
  107450. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  107451. /**
  107452. * Experimental Internal Use Only.
  107453. *
  107454. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  107455. * This acts as a helper to set the primary color to a more "human friendly" value.
  107456. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  107457. * output color as close as possible from the chosen value.
  107458. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  107459. * part of lighting setup.)
  107460. */
  107461. get: function () {
  107462. return this.__perceptualColor;
  107463. },
  107464. set: function (value) {
  107465. this.__perceptualColor = value;
  107466. this._computePrimaryColorFromPerceptualColor();
  107467. this._markAllSubMeshesAsLightsDirty();
  107468. },
  107469. enumerable: true,
  107470. configurable: true
  107471. });
  107472. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  107473. /**
  107474. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  107475. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  107476. */
  107477. get: function () {
  107478. return this._primaryColorShadowLevel;
  107479. },
  107480. set: function (value) {
  107481. this._primaryColorShadowLevel = value;
  107482. this._computePrimaryColors();
  107483. this._markAllSubMeshesAsLightsDirty();
  107484. },
  107485. enumerable: true,
  107486. configurable: true
  107487. });
  107488. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  107489. /**
  107490. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  107491. * The primary color is used at the level chosen to define what the white area would look.
  107492. */
  107493. get: function () {
  107494. return this._primaryColorHighlightLevel;
  107495. },
  107496. set: function (value) {
  107497. this._primaryColorHighlightLevel = value;
  107498. this._computePrimaryColors();
  107499. this._markAllSubMeshesAsLightsDirty();
  107500. },
  107501. enumerable: true,
  107502. configurable: true
  107503. });
  107504. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  107505. /**
  107506. * Sets the reflection reflectance fresnel values according to the default standard
  107507. * empirically know to work well :-)
  107508. */
  107509. set: function (value) {
  107510. var reflectionWeight = value;
  107511. if (reflectionWeight < 0.5) {
  107512. reflectionWeight = reflectionWeight * 2.0;
  107513. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  107514. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  107515. }
  107516. else {
  107517. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  107518. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  107519. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  107520. }
  107521. },
  107522. enumerable: true,
  107523. configurable: true
  107524. });
  107525. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  107526. /**
  107527. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  107528. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  107529. * Recommended to be keep at 1.0 except for special cases.
  107530. */
  107531. get: function () {
  107532. return this._fovMultiplier;
  107533. },
  107534. set: function (value) {
  107535. if (isNaN(value)) {
  107536. value = 1.0;
  107537. }
  107538. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  107539. },
  107540. enumerable: true,
  107541. configurable: true
  107542. });
  107543. /**
  107544. * Attaches a new image processing configuration to the PBR Material.
  107545. * @param configuration (if null the scene configuration will be use)
  107546. */
  107547. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  107548. var _this = this;
  107549. if (configuration === this._imageProcessingConfiguration) {
  107550. return;
  107551. }
  107552. // Detaches observer.
  107553. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  107554. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  107555. }
  107556. // Pick the scene configuration if needed.
  107557. if (!configuration) {
  107558. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  107559. }
  107560. else {
  107561. this._imageProcessingConfiguration = configuration;
  107562. }
  107563. // Attaches observer.
  107564. if (this._imageProcessingConfiguration) {
  107565. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  107566. _this._computePrimaryColorFromPerceptualColor();
  107567. _this._markAllSubMeshesAsImageProcessingDirty();
  107568. });
  107569. }
  107570. };
  107571. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  107572. /**
  107573. * Gets the image processing configuration used either in this material.
  107574. */
  107575. get: function () {
  107576. return this._imageProcessingConfiguration;
  107577. },
  107578. /**
  107579. * Sets the Default image processing configuration used either in the this material.
  107580. *
  107581. * If sets to null, the scene one is in use.
  107582. */
  107583. set: function (value) {
  107584. this._attachImageProcessingConfiguration(value);
  107585. // Ensure the effect will be rebuilt.
  107586. this._markAllSubMeshesAsTexturesDirty();
  107587. },
  107588. enumerable: true,
  107589. configurable: true
  107590. });
  107591. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  107592. /**
  107593. * Gets wether the color curves effect is enabled.
  107594. */
  107595. get: function () {
  107596. return this.imageProcessingConfiguration.colorCurvesEnabled;
  107597. },
  107598. /**
  107599. * Sets wether the color curves effect is enabled.
  107600. */
  107601. set: function (value) {
  107602. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  107603. },
  107604. enumerable: true,
  107605. configurable: true
  107606. });
  107607. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  107608. /**
  107609. * Gets wether the color grading effect is enabled.
  107610. */
  107611. get: function () {
  107612. return this.imageProcessingConfiguration.colorGradingEnabled;
  107613. },
  107614. /**
  107615. * Gets wether the color grading effect is enabled.
  107616. */
  107617. set: function (value) {
  107618. this.imageProcessingConfiguration.colorGradingEnabled = value;
  107619. },
  107620. enumerable: true,
  107621. configurable: true
  107622. });
  107623. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  107624. /**
  107625. * Gets wether tonemapping is enabled or not.
  107626. */
  107627. get: function () {
  107628. return this._imageProcessingConfiguration.toneMappingEnabled;
  107629. },
  107630. /**
  107631. * Sets wether tonemapping is enabled or not
  107632. */
  107633. set: function (value) {
  107634. this._imageProcessingConfiguration.toneMappingEnabled = value;
  107635. },
  107636. enumerable: true,
  107637. configurable: true
  107638. });
  107639. ;
  107640. ;
  107641. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  107642. /**
  107643. * The camera exposure used on this material.
  107644. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  107645. * This corresponds to a photographic exposure.
  107646. */
  107647. get: function () {
  107648. return this._imageProcessingConfiguration.exposure;
  107649. },
  107650. /**
  107651. * The camera exposure used on this material.
  107652. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  107653. * This corresponds to a photographic exposure.
  107654. */
  107655. set: function (value) {
  107656. this._imageProcessingConfiguration.exposure = value;
  107657. },
  107658. enumerable: true,
  107659. configurable: true
  107660. });
  107661. ;
  107662. ;
  107663. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  107664. /**
  107665. * Gets The camera contrast used on this material.
  107666. */
  107667. get: function () {
  107668. return this._imageProcessingConfiguration.contrast;
  107669. },
  107670. /**
  107671. * Sets The camera contrast used on this material.
  107672. */
  107673. set: function (value) {
  107674. this._imageProcessingConfiguration.contrast = value;
  107675. },
  107676. enumerable: true,
  107677. configurable: true
  107678. });
  107679. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  107680. /**
  107681. * Gets the Color Grading 2D Lookup Texture.
  107682. */
  107683. get: function () {
  107684. return this._imageProcessingConfiguration.colorGradingTexture;
  107685. },
  107686. /**
  107687. * Sets the Color Grading 2D Lookup Texture.
  107688. */
  107689. set: function (value) {
  107690. this.imageProcessingConfiguration.colorGradingTexture = value;
  107691. },
  107692. enumerable: true,
  107693. configurable: true
  107694. });
  107695. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  107696. /**
  107697. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  107698. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  107699. * 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;
  107700. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  107701. */
  107702. get: function () {
  107703. return this.imageProcessingConfiguration.colorCurves;
  107704. },
  107705. /**
  107706. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  107707. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  107708. * 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;
  107709. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  107710. */
  107711. set: function (value) {
  107712. this.imageProcessingConfiguration.colorCurves = value;
  107713. },
  107714. enumerable: true,
  107715. configurable: true
  107716. });
  107717. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  107718. /**
  107719. * Gets a boolean indicating that current material needs to register RTT
  107720. */
  107721. get: function () {
  107722. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  107723. return true;
  107724. }
  107725. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  107726. return true;
  107727. }
  107728. return false;
  107729. },
  107730. enumerable: true,
  107731. configurable: true
  107732. });
  107733. /**
  107734. * The entire material has been created in order to prevent overdraw.
  107735. * @returns false
  107736. */
  107737. BackgroundMaterial.prototype.needAlphaTesting = function () {
  107738. return true;
  107739. };
  107740. /**
  107741. * The entire material has been created in order to prevent overdraw.
  107742. * @returns true if blending is enable
  107743. */
  107744. BackgroundMaterial.prototype.needAlphaBlending = function () {
  107745. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  107746. };
  107747. /**
  107748. * Checks wether the material is ready to be rendered for a given mesh.
  107749. * @param mesh The mesh to render
  107750. * @param subMesh The submesh to check against
  107751. * @param useInstances Specify wether or not the material is used with instances
  107752. * @returns true if all the dependencies are ready (Textures, Effects...)
  107753. */
  107754. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  107755. var _this = this;
  107756. if (useInstances === void 0) { useInstances = false; }
  107757. if (subMesh.effect && this.isFrozen) {
  107758. if (this._wasPreviouslyReady) {
  107759. return true;
  107760. }
  107761. }
  107762. if (!subMesh._materialDefines) {
  107763. subMesh._materialDefines = new BackgroundMaterialDefines();
  107764. }
  107765. var scene = this.getScene();
  107766. var defines = subMesh._materialDefines;
  107767. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  107768. if (defines._renderId === scene.getRenderId()) {
  107769. return true;
  107770. }
  107771. }
  107772. var engine = scene.getEngine();
  107773. // Lights
  107774. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  107775. defines._needNormals = true;
  107776. // Textures
  107777. if (defines._areTexturesDirty) {
  107778. defines._needUVs = false;
  107779. if (scene.texturesEnabled) {
  107780. if (scene.getEngine().getCaps().textureLOD) {
  107781. defines.TEXTURELODSUPPORT = true;
  107782. }
  107783. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  107784. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  107785. return false;
  107786. }
  107787. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  107788. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  107789. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  107790. defines.OPACITYFRESNEL = this._opacityFresnel;
  107791. }
  107792. else {
  107793. defines.DIFFUSE = false;
  107794. defines.DIFFUSEHASALPHA = false;
  107795. defines.GAMMADIFFUSE = false;
  107796. defines.OPACITYFRESNEL = false;
  107797. }
  107798. var reflectionTexture = this._reflectionTexture;
  107799. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  107800. if (!reflectionTexture.isReadyOrNotBlocking()) {
  107801. return false;
  107802. }
  107803. defines.REFLECTION = true;
  107804. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  107805. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  107806. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  107807. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  107808. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  107809. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  107810. defines.REFLECTIONBGR = this.switchToBGR;
  107811. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  107812. defines.INVERTCUBICMAP = true;
  107813. }
  107814. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  107815. switch (reflectionTexture.coordinatesMode) {
  107816. case BABYLON.Texture.EXPLICIT_MODE:
  107817. defines.REFLECTIONMAP_EXPLICIT = true;
  107818. break;
  107819. case BABYLON.Texture.PLANAR_MODE:
  107820. defines.REFLECTIONMAP_PLANAR = true;
  107821. break;
  107822. case BABYLON.Texture.PROJECTION_MODE:
  107823. defines.REFLECTIONMAP_PROJECTION = true;
  107824. break;
  107825. case BABYLON.Texture.SKYBOX_MODE:
  107826. defines.REFLECTIONMAP_SKYBOX = true;
  107827. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  107828. break;
  107829. case BABYLON.Texture.SPHERICAL_MODE:
  107830. defines.REFLECTIONMAP_SPHERICAL = true;
  107831. break;
  107832. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  107833. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  107834. break;
  107835. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  107836. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  107837. break;
  107838. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  107839. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  107840. break;
  107841. case BABYLON.Texture.CUBIC_MODE:
  107842. case BABYLON.Texture.INVCUBIC_MODE:
  107843. default:
  107844. defines.REFLECTIONMAP_CUBIC = true;
  107845. break;
  107846. }
  107847. if (this.reflectionFresnel) {
  107848. defines.REFLECTIONFRESNEL = true;
  107849. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  107850. this._reflectionControls.x = this.reflectionAmount;
  107851. this._reflectionControls.y = this.reflectionReflectance0;
  107852. this._reflectionControls.z = this.reflectionReflectance90;
  107853. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  107854. }
  107855. else {
  107856. defines.REFLECTIONFRESNEL = false;
  107857. defines.REFLECTIONFALLOFF = false;
  107858. }
  107859. }
  107860. else {
  107861. defines.REFLECTION = false;
  107862. defines.REFLECTIONFRESNEL = false;
  107863. defines.REFLECTIONFALLOFF = false;
  107864. defines.REFLECTIONBLUR = false;
  107865. defines.REFLECTIONMAP_3D = false;
  107866. defines.REFLECTIONMAP_SPHERICAL = false;
  107867. defines.REFLECTIONMAP_PLANAR = false;
  107868. defines.REFLECTIONMAP_CUBIC = false;
  107869. defines.REFLECTIONMAP_PROJECTION = false;
  107870. defines.REFLECTIONMAP_SKYBOX = false;
  107871. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  107872. defines.REFLECTIONMAP_EXPLICIT = false;
  107873. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  107874. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  107875. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  107876. defines.INVERTCUBICMAP = false;
  107877. defines.REFLECTIONMAP_OPPOSITEZ = false;
  107878. defines.LODINREFLECTIONALPHA = false;
  107879. defines.GAMMAREFLECTION = false;
  107880. defines.RGBDREFLECTION = false;
  107881. }
  107882. }
  107883. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  107884. defines.USERGBCOLOR = this._useRGBColor;
  107885. defines.NOISE = this._enableNoise;
  107886. }
  107887. if (defines._areLightsDirty) {
  107888. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  107889. }
  107890. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  107891. if (!this._imageProcessingConfiguration.isReady()) {
  107892. return false;
  107893. }
  107894. this._imageProcessingConfiguration.prepareDefines(defines);
  107895. }
  107896. // Misc.
  107897. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  107898. // Values that need to be evaluated on every frame
  107899. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  107900. // Attribs
  107901. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  107902. if (mesh) {
  107903. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  107904. mesh.createNormals(true);
  107905. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  107906. }
  107907. }
  107908. }
  107909. // Get correct effect
  107910. if (defines.isDirty) {
  107911. defines.markAsProcessed();
  107912. scene.resetCachedMaterial();
  107913. // Fallbacks
  107914. var fallbacks = new BABYLON.EffectFallbacks();
  107915. if (defines.FOG) {
  107916. fallbacks.addFallback(0, "FOG");
  107917. }
  107918. if (defines.POINTSIZE) {
  107919. fallbacks.addFallback(1, "POINTSIZE");
  107920. }
  107921. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  107922. if (defines.NUM_BONE_INFLUENCERS > 0) {
  107923. fallbacks.addCPUSkinningFallback(0, mesh);
  107924. }
  107925. //Attributes
  107926. var attribs = [BABYLON.VertexBuffer.PositionKind];
  107927. if (defines.NORMAL) {
  107928. attribs.push(BABYLON.VertexBuffer.NormalKind);
  107929. }
  107930. if (defines.UV1) {
  107931. attribs.push(BABYLON.VertexBuffer.UVKind);
  107932. }
  107933. if (defines.UV2) {
  107934. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  107935. }
  107936. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  107937. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  107938. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  107939. "vFogInfos", "vFogColor", "pointSize",
  107940. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  107941. "vPrimaryColor", "vPrimaryColorShadow",
  107942. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  107943. "shadowLevel", "alpha",
  107944. "vBackgroundCenter", "vReflectionControl",
  107945. "vDiffuseInfos", "diffuseMatrix",
  107946. ];
  107947. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  107948. var uniformBuffers = ["Material", "Scene"];
  107949. if (BABYLON.ImageProcessingConfiguration) {
  107950. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  107951. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  107952. }
  107953. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  107954. uniformsNames: uniforms,
  107955. uniformBuffersNames: uniformBuffers,
  107956. samplers: samplers,
  107957. defines: defines,
  107958. maxSimultaneousLights: this._maxSimultaneousLights
  107959. });
  107960. var onCompiled = function (effect) {
  107961. if (_this.onCompiled) {
  107962. _this.onCompiled(effect);
  107963. }
  107964. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  107965. };
  107966. var join = defines.toString();
  107967. subMesh.setEffect(scene.getEngine().createEffect("background", {
  107968. attributes: attribs,
  107969. uniformsNames: uniforms,
  107970. uniformBuffersNames: uniformBuffers,
  107971. samplers: samplers,
  107972. defines: join,
  107973. fallbacks: fallbacks,
  107974. onCompiled: onCompiled,
  107975. onError: this.onError,
  107976. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  107977. }, engine), defines);
  107978. this.buildUniformLayout();
  107979. }
  107980. if (!subMesh.effect || !subMesh.effect.isReady()) {
  107981. return false;
  107982. }
  107983. defines._renderId = scene.getRenderId();
  107984. this._wasPreviouslyReady = true;
  107985. return true;
  107986. };
  107987. /**
  107988. * Compute the primary color according to the chosen perceptual color.
  107989. */
  107990. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  107991. if (!this.__perceptualColor) {
  107992. return;
  107993. }
  107994. this._primaryColor.copyFrom(this.__perceptualColor);
  107995. // Revert gamma space.
  107996. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  107997. // Revert image processing configuration.
  107998. if (this._imageProcessingConfiguration) {
  107999. // Revert Exposure.
  108000. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  108001. }
  108002. this._computePrimaryColors();
  108003. };
  108004. /**
  108005. * Compute the highlights and shadow colors according to their chosen levels.
  108006. */
  108007. BackgroundMaterial.prototype._computePrimaryColors = function () {
  108008. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  108009. return;
  108010. }
  108011. // Find the highlight color based on the configuration.
  108012. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  108013. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  108014. // Find the shadow color based on the configuration.
  108015. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  108016. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  108017. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  108018. };
  108019. /**
  108020. * Build the uniform buffer used in the material.
  108021. */
  108022. BackgroundMaterial.prototype.buildUniformLayout = function () {
  108023. // Order is important !
  108024. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  108025. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  108026. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  108027. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  108028. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  108029. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  108030. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  108031. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  108032. this._uniformBuffer.addUniform("pointSize", 1);
  108033. this._uniformBuffer.addUniform("shadowLevel", 1);
  108034. this._uniformBuffer.addUniform("alpha", 1);
  108035. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  108036. this._uniformBuffer.addUniform("vReflectionControl", 4);
  108037. this._uniformBuffer.create();
  108038. };
  108039. /**
  108040. * Unbind the material.
  108041. */
  108042. BackgroundMaterial.prototype.unbind = function () {
  108043. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  108044. this._uniformBuffer.setTexture("diffuseSampler", null);
  108045. }
  108046. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  108047. this._uniformBuffer.setTexture("reflectionSampler", null);
  108048. }
  108049. _super.prototype.unbind.call(this);
  108050. };
  108051. /**
  108052. * Bind only the world matrix to the material.
  108053. * @param world The world matrix to bind.
  108054. */
  108055. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  108056. this._activeEffect.setMatrix("world", world);
  108057. };
  108058. /**
  108059. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  108060. * @param world The world matrix to bind.
  108061. * @param subMesh The submesh to bind for.
  108062. */
  108063. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  108064. var scene = this.getScene();
  108065. var defines = subMesh._materialDefines;
  108066. if (!defines) {
  108067. return;
  108068. }
  108069. var effect = subMesh.effect;
  108070. if (!effect) {
  108071. return;
  108072. }
  108073. this._activeEffect = effect;
  108074. // Matrices
  108075. this.bindOnlyWorldMatrix(world);
  108076. // Bones
  108077. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  108078. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  108079. if (mustRebind) {
  108080. this._uniformBuffer.bindToEffect(effect, "Material");
  108081. this.bindViewProjection(effect);
  108082. var reflectionTexture = this._reflectionTexture;
  108083. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  108084. // Texture uniforms
  108085. if (scene.texturesEnabled) {
  108086. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  108087. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  108088. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  108089. }
  108090. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  108091. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  108092. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  108093. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  108094. }
  108095. }
  108096. if (this.shadowLevel > 0) {
  108097. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  108098. }
  108099. this._uniformBuffer.updateFloat("alpha", this.alpha);
  108100. // Point size
  108101. if (this.pointsCloud) {
  108102. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  108103. }
  108104. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  108105. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  108106. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  108107. }
  108108. else {
  108109. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  108110. }
  108111. }
  108112. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  108113. // Textures
  108114. if (scene.texturesEnabled) {
  108115. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  108116. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  108117. }
  108118. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  108119. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  108120. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  108121. }
  108122. else if (!defines.REFLECTIONBLUR) {
  108123. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  108124. }
  108125. else {
  108126. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  108127. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  108128. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  108129. }
  108130. if (defines.REFLECTIONFRESNEL) {
  108131. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  108132. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  108133. }
  108134. }
  108135. }
  108136. // Clip plane
  108137. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  108138. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  108139. }
  108140. if (mustRebind || !this.isFrozen) {
  108141. if (scene.lightsEnabled) {
  108142. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  108143. }
  108144. // View
  108145. this.bindView(effect);
  108146. // Fog
  108147. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  108148. // image processing
  108149. if (this._imageProcessingConfiguration) {
  108150. this._imageProcessingConfiguration.bind(this._activeEffect);
  108151. }
  108152. }
  108153. this._uniformBuffer.update();
  108154. this._afterBind(mesh, this._activeEffect);
  108155. };
  108156. /**
  108157. * Dispose the material.
  108158. * @param forceDisposeEffect Force disposal of the associated effect.
  108159. * @param forceDisposeTextures Force disposal of the associated textures.
  108160. */
  108161. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  108162. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  108163. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  108164. if (forceDisposeTextures) {
  108165. if (this.diffuseTexture) {
  108166. this.diffuseTexture.dispose();
  108167. }
  108168. if (this.reflectionTexture) {
  108169. this.reflectionTexture.dispose();
  108170. }
  108171. }
  108172. this._renderTargets.dispose();
  108173. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  108174. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  108175. }
  108176. _super.prototype.dispose.call(this, forceDisposeEffect);
  108177. };
  108178. /**
  108179. * Clones the material.
  108180. * @param name The cloned name.
  108181. * @returns The cloned material.
  108182. */
  108183. BackgroundMaterial.prototype.clone = function (name) {
  108184. var _this = this;
  108185. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  108186. };
  108187. /**
  108188. * Serializes the current material to its JSON representation.
  108189. * @returns The JSON representation.
  108190. */
  108191. BackgroundMaterial.prototype.serialize = function () {
  108192. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  108193. serializationObject.customType = "BABYLON.BackgroundMaterial";
  108194. return serializationObject;
  108195. };
  108196. /**
  108197. * Gets the class name of the material
  108198. * @returns "BackgroundMaterial"
  108199. */
  108200. BackgroundMaterial.prototype.getClassName = function () {
  108201. return "BackgroundMaterial";
  108202. };
  108203. /**
  108204. * Parse a JSON input to create back a background material.
  108205. * @param source The JSON data to parse
  108206. * @param scene The scene to create the parsed material in
  108207. * @param rootUrl The root url of the assets the material depends upon
  108208. * @returns the instantiated BackgroundMaterial.
  108209. */
  108210. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  108211. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  108212. };
  108213. /**
  108214. * Standard reflectance value at parallel view angle.
  108215. */
  108216. BackgroundMaterial.StandardReflectance0 = 0.05;
  108217. /**
  108218. * Standard reflectance value at grazing angle.
  108219. */
  108220. BackgroundMaterial.StandardReflectance90 = 0.5;
  108221. __decorate([
  108222. BABYLON.serializeAsColor3()
  108223. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  108224. __decorate([
  108225. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  108226. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  108227. __decorate([
  108228. BABYLON.serializeAsColor3()
  108229. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  108230. __decorate([
  108231. BABYLON.serialize()
  108232. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  108233. __decorate([
  108234. BABYLON.serialize()
  108235. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  108236. __decorate([
  108237. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  108238. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  108239. __decorate([
  108240. BABYLON.serializeAsTexture()
  108241. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  108242. __decorate([
  108243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108244. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  108245. __decorate([
  108246. BABYLON.serialize()
  108247. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  108248. __decorate([
  108249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108250. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  108251. __decorate([
  108252. BABYLON.serializeAsTexture()
  108253. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  108254. __decorate([
  108255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108256. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  108257. __decorate([
  108258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108259. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  108260. __decorate([
  108261. BABYLON.serialize()
  108262. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  108263. __decorate([
  108264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108265. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  108266. __decorate([
  108267. BABYLON.serializeAsVector3()
  108268. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  108269. __decorate([
  108270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108271. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  108272. __decorate([
  108273. BABYLON.serialize()
  108274. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  108275. __decorate([
  108276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108277. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  108278. __decorate([
  108279. BABYLON.serialize()
  108280. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  108281. __decorate([
  108282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108283. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  108284. __decorate([
  108285. BABYLON.serialize()
  108286. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  108287. __decorate([
  108288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108289. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  108290. __decorate([
  108291. BABYLON.serialize()
  108292. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  108293. __decorate([
  108294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108295. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  108296. __decorate([
  108297. BABYLON.serialize()
  108298. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  108299. __decorate([
  108300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108301. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  108302. __decorate([
  108303. BABYLON.serialize()
  108304. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  108305. __decorate([
  108306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108307. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  108308. __decorate([
  108309. BABYLON.serialize()
  108310. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  108311. __decorate([
  108312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108313. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  108314. __decorate([
  108315. BABYLON.serialize()
  108316. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  108317. __decorate([
  108318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108319. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  108320. __decorate([
  108321. BABYLON.serialize()
  108322. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  108323. __decorate([
  108324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108325. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  108326. __decorate([
  108327. BABYLON.serializeAsImageProcessingConfiguration()
  108328. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  108329. return BackgroundMaterial;
  108330. }(BABYLON.PushMaterial));
  108331. BABYLON.BackgroundMaterial = BackgroundMaterial;
  108332. })(BABYLON || (BABYLON = {}));
  108333. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  108334. var __assign = (this && this.__assign) || function () {
  108335. __assign = Object.assign || function(t) {
  108336. for (var s, i = 1, n = arguments.length; i < n; i++) {
  108337. s = arguments[i];
  108338. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  108339. t[p] = s[p];
  108340. }
  108341. return t;
  108342. };
  108343. return __assign.apply(this, arguments);
  108344. };
  108345. var BABYLON;
  108346. (function (BABYLON) {
  108347. /**
  108348. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  108349. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  108350. * It also helps with the default setup of your imageProcessing configuration.
  108351. */
  108352. var EnvironmentHelper = /** @class */ (function () {
  108353. /**
  108354. * constructor
  108355. * @param options
  108356. * @param scene The scene to add the material to
  108357. */
  108358. function EnvironmentHelper(options, scene) {
  108359. var _this = this;
  108360. this._errorHandler = function (message, exception) {
  108361. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  108362. };
  108363. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  108364. this._scene = scene;
  108365. this.onErrorObservable = new BABYLON.Observable();
  108366. this._setupBackground();
  108367. this._setupImageProcessing();
  108368. }
  108369. /**
  108370. * Creates the default options for the helper.
  108371. */
  108372. EnvironmentHelper._getDefaultOptions = function () {
  108373. return {
  108374. createGround: true,
  108375. groundSize: 15,
  108376. groundTexture: this._groundTextureCDNUrl,
  108377. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  108378. groundOpacity: 0.9,
  108379. enableGroundShadow: true,
  108380. groundShadowLevel: 0.5,
  108381. enableGroundMirror: false,
  108382. groundMirrorSizeRatio: 0.3,
  108383. groundMirrorBlurKernel: 64,
  108384. groundMirrorAmount: 1,
  108385. groundMirrorFresnelWeight: 1,
  108386. groundMirrorFallOffDistance: 0,
  108387. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  108388. groundYBias: 0.00001,
  108389. createSkybox: true,
  108390. skyboxSize: 20,
  108391. skyboxTexture: this._skyboxTextureCDNUrl,
  108392. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  108393. backgroundYRotation: 0,
  108394. sizeAuto: true,
  108395. rootPosition: BABYLON.Vector3.Zero(),
  108396. setupImageProcessing: true,
  108397. environmentTexture: this._environmentTextureCDNUrl,
  108398. cameraExposure: 0.8,
  108399. cameraContrast: 1.2,
  108400. toneMappingEnabled: true,
  108401. };
  108402. };
  108403. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  108404. /**
  108405. * Gets the root mesh created by the helper.
  108406. */
  108407. get: function () {
  108408. return this._rootMesh;
  108409. },
  108410. enumerable: true,
  108411. configurable: true
  108412. });
  108413. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  108414. /**
  108415. * Gets the skybox created by the helper.
  108416. */
  108417. get: function () {
  108418. return this._skybox;
  108419. },
  108420. enumerable: true,
  108421. configurable: true
  108422. });
  108423. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  108424. /**
  108425. * Gets the skybox texture created by the helper.
  108426. */
  108427. get: function () {
  108428. return this._skyboxTexture;
  108429. },
  108430. enumerable: true,
  108431. configurable: true
  108432. });
  108433. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  108434. /**
  108435. * Gets the skybox material created by the helper.
  108436. */
  108437. get: function () {
  108438. return this._skyboxMaterial;
  108439. },
  108440. enumerable: true,
  108441. configurable: true
  108442. });
  108443. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  108444. /**
  108445. * Gets the ground mesh created by the helper.
  108446. */
  108447. get: function () {
  108448. return this._ground;
  108449. },
  108450. enumerable: true,
  108451. configurable: true
  108452. });
  108453. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  108454. /**
  108455. * Gets the ground texture created by the helper.
  108456. */
  108457. get: function () {
  108458. return this._groundTexture;
  108459. },
  108460. enumerable: true,
  108461. configurable: true
  108462. });
  108463. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  108464. /**
  108465. * Gets the ground mirror created by the helper.
  108466. */
  108467. get: function () {
  108468. return this._groundMirror;
  108469. },
  108470. enumerable: true,
  108471. configurable: true
  108472. });
  108473. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  108474. /**
  108475. * Gets the ground mirror render list to helps pushing the meshes
  108476. * you wish in the ground reflection.
  108477. */
  108478. get: function () {
  108479. if (this._groundMirror) {
  108480. return this._groundMirror.renderList;
  108481. }
  108482. return null;
  108483. },
  108484. enumerable: true,
  108485. configurable: true
  108486. });
  108487. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  108488. /**
  108489. * Gets the ground material created by the helper.
  108490. */
  108491. get: function () {
  108492. return this._groundMaterial;
  108493. },
  108494. enumerable: true,
  108495. configurable: true
  108496. });
  108497. /**
  108498. * Updates the background according to the new options
  108499. * @param options
  108500. */
  108501. EnvironmentHelper.prototype.updateOptions = function (options) {
  108502. var newOptions = __assign({}, this._options, options);
  108503. if (this._ground && !newOptions.createGround) {
  108504. this._ground.dispose();
  108505. this._ground = null;
  108506. }
  108507. if (this._groundMaterial && !newOptions.createGround) {
  108508. this._groundMaterial.dispose();
  108509. this._groundMaterial = null;
  108510. }
  108511. if (this._groundTexture) {
  108512. if (this._options.groundTexture != newOptions.groundTexture) {
  108513. this._groundTexture.dispose();
  108514. this._groundTexture = null;
  108515. }
  108516. }
  108517. if (this._skybox && !newOptions.createSkybox) {
  108518. this._skybox.dispose();
  108519. this._skybox = null;
  108520. }
  108521. if (this._skyboxMaterial && !newOptions.createSkybox) {
  108522. this._skyboxMaterial.dispose();
  108523. this._skyboxMaterial = null;
  108524. }
  108525. if (this._skyboxTexture) {
  108526. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  108527. this._skyboxTexture.dispose();
  108528. this._skyboxTexture = null;
  108529. }
  108530. }
  108531. if (this._groundMirror && !newOptions.enableGroundMirror) {
  108532. this._groundMirror.dispose();
  108533. this._groundMirror = null;
  108534. }
  108535. if (this._scene.environmentTexture) {
  108536. if (this._options.environmentTexture != newOptions.environmentTexture) {
  108537. this._scene.environmentTexture.dispose();
  108538. }
  108539. }
  108540. this._options = newOptions;
  108541. this._setupBackground();
  108542. this._setupImageProcessing();
  108543. };
  108544. /**
  108545. * Sets the primary color of all the available elements.
  108546. * @param color the main color to affect to the ground and the background
  108547. */
  108548. EnvironmentHelper.prototype.setMainColor = function (color) {
  108549. if (this.groundMaterial) {
  108550. this.groundMaterial.primaryColor = color;
  108551. }
  108552. if (this.skyboxMaterial) {
  108553. this.skyboxMaterial.primaryColor = color;
  108554. }
  108555. if (this.groundMirror) {
  108556. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  108557. }
  108558. };
  108559. /**
  108560. * Setup the image processing according to the specified options.
  108561. */
  108562. EnvironmentHelper.prototype._setupImageProcessing = function () {
  108563. if (this._options.setupImageProcessing) {
  108564. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  108565. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  108566. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  108567. this._setupEnvironmentTexture();
  108568. }
  108569. };
  108570. /**
  108571. * Setup the environment texture according to the specified options.
  108572. */
  108573. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  108574. if (this._scene.environmentTexture) {
  108575. return;
  108576. }
  108577. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  108578. this._scene.environmentTexture = this._options.environmentTexture;
  108579. return;
  108580. }
  108581. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  108582. this._scene.environmentTexture = environmentTexture;
  108583. };
  108584. /**
  108585. * Setup the background according to the specified options.
  108586. */
  108587. EnvironmentHelper.prototype._setupBackground = function () {
  108588. if (!this._rootMesh) {
  108589. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  108590. }
  108591. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  108592. var sceneSize = this._getSceneSize();
  108593. if (this._options.createGround) {
  108594. this._setupGround(sceneSize);
  108595. this._setupGroundMaterial();
  108596. this._setupGroundDiffuseTexture();
  108597. if (this._options.enableGroundMirror) {
  108598. this._setupGroundMirrorTexture(sceneSize);
  108599. }
  108600. this._setupMirrorInGroundMaterial();
  108601. }
  108602. if (this._options.createSkybox) {
  108603. this._setupSkybox(sceneSize);
  108604. this._setupSkyboxMaterial();
  108605. this._setupSkyboxReflectionTexture();
  108606. }
  108607. this._rootMesh.position.x = sceneSize.rootPosition.x;
  108608. this._rootMesh.position.z = sceneSize.rootPosition.z;
  108609. this._rootMesh.position.y = sceneSize.rootPosition.y;
  108610. };
  108611. /**
  108612. * Get the scene sizes according to the setup.
  108613. */
  108614. EnvironmentHelper.prototype._getSceneSize = function () {
  108615. var _this = this;
  108616. var groundSize = this._options.groundSize;
  108617. var skyboxSize = this._options.skyboxSize;
  108618. var rootPosition = this._options.rootPosition;
  108619. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  108620. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  108621. }
  108622. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  108623. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  108624. });
  108625. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  108626. if (this._options.sizeAuto) {
  108627. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  108628. this._scene.activeCamera.upperRadiusLimit) {
  108629. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  108630. skyboxSize = groundSize;
  108631. }
  108632. var sceneDiagonalLenght = sceneDiagonal.length();
  108633. if (sceneDiagonalLenght > groundSize) {
  108634. groundSize = sceneDiagonalLenght * 2;
  108635. skyboxSize = groundSize;
  108636. }
  108637. // 10 % bigger.
  108638. groundSize *= 1.1;
  108639. skyboxSize *= 1.5;
  108640. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  108641. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  108642. }
  108643. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  108644. };
  108645. /**
  108646. * Setup the ground according to the specified options.
  108647. */
  108648. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  108649. var _this = this;
  108650. if (!this._ground || this._ground.isDisposed()) {
  108651. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  108652. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  108653. this._ground.parent = this._rootMesh;
  108654. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  108655. }
  108656. this._ground.receiveShadows = this._options.enableGroundShadow;
  108657. };
  108658. /**
  108659. * Setup the ground material according to the specified options.
  108660. */
  108661. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  108662. if (!this._groundMaterial) {
  108663. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  108664. }
  108665. this._groundMaterial.alpha = this._options.groundOpacity;
  108666. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  108667. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  108668. this._groundMaterial.primaryColor = this._options.groundColor;
  108669. this._groundMaterial.useRGBColor = false;
  108670. this._groundMaterial.enableNoise = true;
  108671. if (this._ground) {
  108672. this._ground.material = this._groundMaterial;
  108673. }
  108674. };
  108675. /**
  108676. * Setup the ground diffuse texture according to the specified options.
  108677. */
  108678. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  108679. if (!this._groundMaterial) {
  108680. return;
  108681. }
  108682. if (this._groundTexture) {
  108683. return;
  108684. }
  108685. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  108686. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  108687. return;
  108688. }
  108689. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  108690. diffuseTexture.gammaSpace = false;
  108691. diffuseTexture.hasAlpha = true;
  108692. this._groundMaterial.diffuseTexture = diffuseTexture;
  108693. };
  108694. /**
  108695. * Setup the ground mirror texture according to the specified options.
  108696. */
  108697. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  108698. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108699. if (!this._groundMirror) {
  108700. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  108701. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  108702. this._groundMirror.anisotropicFilteringLevel = 1;
  108703. this._groundMirror.wrapU = wrapping;
  108704. this._groundMirror.wrapV = wrapping;
  108705. this._groundMirror.gammaSpace = false;
  108706. if (this._groundMirror.renderList) {
  108707. for (var i = 0; i < this._scene.meshes.length; i++) {
  108708. var mesh = this._scene.meshes[i];
  108709. if (mesh !== this._ground &&
  108710. mesh !== this._skybox &&
  108711. mesh !== this._rootMesh) {
  108712. this._groundMirror.renderList.push(mesh);
  108713. }
  108714. }
  108715. }
  108716. }
  108717. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  108718. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  108719. };
  108720. /**
  108721. * Setup the ground to receive the mirror texture.
  108722. */
  108723. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  108724. if (this._groundMaterial) {
  108725. this._groundMaterial.reflectionTexture = this._groundMirror;
  108726. this._groundMaterial.reflectionFresnel = true;
  108727. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  108728. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  108729. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  108730. }
  108731. };
  108732. /**
  108733. * Setup the skybox according to the specified options.
  108734. */
  108735. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  108736. var _this = this;
  108737. if (!this._skybox || this._skybox.isDisposed()) {
  108738. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  108739. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  108740. }
  108741. this._skybox.parent = this._rootMesh;
  108742. };
  108743. /**
  108744. * Setup the skybox material according to the specified options.
  108745. */
  108746. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  108747. if (!this._skybox) {
  108748. return;
  108749. }
  108750. if (!this._skyboxMaterial) {
  108751. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  108752. }
  108753. this._skyboxMaterial.useRGBColor = false;
  108754. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  108755. this._skyboxMaterial.enableNoise = true;
  108756. this._skybox.material = this._skyboxMaterial;
  108757. };
  108758. /**
  108759. * Setup the skybox reflection texture according to the specified options.
  108760. */
  108761. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  108762. if (!this._skyboxMaterial) {
  108763. return;
  108764. }
  108765. if (this._skyboxTexture) {
  108766. return;
  108767. }
  108768. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  108769. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  108770. return;
  108771. }
  108772. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  108773. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  108774. this._skyboxTexture.gammaSpace = false;
  108775. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  108776. };
  108777. /**
  108778. * Dispose all the elements created by the Helper.
  108779. */
  108780. EnvironmentHelper.prototype.dispose = function () {
  108781. if (this._groundMaterial) {
  108782. this._groundMaterial.dispose(true, true);
  108783. }
  108784. if (this._skyboxMaterial) {
  108785. this._skyboxMaterial.dispose(true, true);
  108786. }
  108787. this._rootMesh.dispose(false);
  108788. };
  108789. /**
  108790. * Default ground texture URL.
  108791. */
  108792. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  108793. /**
  108794. * Default skybox texture URL.
  108795. */
  108796. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  108797. /**
  108798. * Default environment texture URL.
  108799. */
  108800. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  108801. return EnvironmentHelper;
  108802. }());
  108803. BABYLON.EnvironmentHelper = EnvironmentHelper;
  108804. })(BABYLON || (BABYLON = {}));
  108805. //# sourceMappingURL=babylon.environmentHelper.js.map
  108806. var BABYLON;
  108807. (function (BABYLON) {
  108808. /** Internal class used to store shapes for emitters */
  108809. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  108810. function ParticleSystemSetEmitterCreationOptions() {
  108811. }
  108812. return ParticleSystemSetEmitterCreationOptions;
  108813. }());
  108814. /**
  108815. * Represents a set of particle systems working together to create a specific effect
  108816. */
  108817. var ParticleSystemSet = /** @class */ (function () {
  108818. function ParticleSystemSet() {
  108819. /**
  108820. * Gets the particle system list
  108821. */
  108822. this.systems = new Array();
  108823. }
  108824. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  108825. /**
  108826. * Gets the emitter node used with this set
  108827. */
  108828. get: function () {
  108829. return this._emitterNode;
  108830. },
  108831. enumerable: true,
  108832. configurable: true
  108833. });
  108834. /**
  108835. * Creates a new emitter mesh as a sphere
  108836. * @param options defines the options used to create the sphere
  108837. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  108838. * @param scene defines the hosting scene
  108839. */
  108840. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  108841. if (this._emitterNode) {
  108842. this._emitterNode.dispose();
  108843. }
  108844. this._emitterCreationOptions = {
  108845. kind: "Sphere",
  108846. options: options,
  108847. renderingGroupId: renderingGroupId
  108848. };
  108849. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  108850. emitterMesh.renderingGroupId = renderingGroupId;
  108851. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  108852. material.emissiveColor = options.color;
  108853. emitterMesh.material = material;
  108854. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108855. var system = _a[_i];
  108856. system.emitter = emitterMesh;
  108857. }
  108858. this._emitterNode = emitterMesh;
  108859. };
  108860. /**
  108861. * Starts all particle systems of the set
  108862. * @param emitter defines an optional mesh to use as emitter for the particle systems
  108863. */
  108864. ParticleSystemSet.prototype.start = function (emitter) {
  108865. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108866. var system = _a[_i];
  108867. if (emitter) {
  108868. system.emitter = emitter;
  108869. }
  108870. system.start();
  108871. }
  108872. };
  108873. /**
  108874. * Release all associated resources
  108875. */
  108876. ParticleSystemSet.prototype.dispose = function () {
  108877. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108878. var system = _a[_i];
  108879. system.dispose();
  108880. }
  108881. this.systems = [];
  108882. if (this._emitterNode) {
  108883. this._emitterNode.dispose();
  108884. this._emitterNode = null;
  108885. }
  108886. };
  108887. /**
  108888. * Serialize the set into a JSON compatible object
  108889. * @returns a JSON compatible representation of the set
  108890. */
  108891. ParticleSystemSet.prototype.serialize = function () {
  108892. var result = {};
  108893. result.systems = [];
  108894. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108895. var system = _a[_i];
  108896. result.systems.push(system.serialize());
  108897. }
  108898. if (this._emitterNode) {
  108899. result.emitter = this._emitterCreationOptions;
  108900. }
  108901. return result;
  108902. };
  108903. /**
  108904. * Parse a new ParticleSystemSet from a serialized source
  108905. * @param data defines a JSON compatible representation of the set
  108906. * @param scene defines the hosting scene
  108907. * @param gpu defines if we want GPU particles or CPU particles
  108908. * @returns a new ParticleSystemSet
  108909. */
  108910. ParticleSystemSet.Parse = function (data, scene, gpu) {
  108911. if (gpu === void 0) { gpu = false; }
  108912. var result = new ParticleSystemSet();
  108913. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  108914. scene = scene || BABYLON.Engine.LastCreatedScene;
  108915. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  108916. var system = _a[_i];
  108917. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  108918. }
  108919. if (data.emitter) {
  108920. var options = data.emitter.options;
  108921. switch (data.emitter.kind) {
  108922. case "Sphere":
  108923. result.setEmitterAsSphere({
  108924. diameter: options.diameter,
  108925. segments: options.segments,
  108926. color: BABYLON.Color3.FromArray(options.color)
  108927. }, data.emitter.renderingGroupId, scene);
  108928. break;
  108929. }
  108930. }
  108931. return result;
  108932. };
  108933. return ParticleSystemSet;
  108934. }());
  108935. BABYLON.ParticleSystemSet = ParticleSystemSet;
  108936. })(BABYLON || (BABYLON = {}));
  108937. //# sourceMappingURL=babylon.particleSystemSet.js.map
  108938. var BABYLON;
  108939. (function (BABYLON) {
  108940. /**
  108941. * This class is made for on one-liner static method to help creating particle system set.
  108942. */
  108943. var ParticleHelper = /** @class */ (function () {
  108944. function ParticleHelper() {
  108945. }
  108946. /**
  108947. * Create a default particle system that you can tweak
  108948. * @param emitter defines the emitter to use
  108949. * @param capacity defines the system capacity (default is 500 particles)
  108950. * @param scene defines the hosting scene
  108951. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  108952. * @returns the new Particle system
  108953. */
  108954. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  108955. if (capacity === void 0) { capacity = 500; }
  108956. if (useGPU === void 0) { useGPU = false; }
  108957. var system;
  108958. if (useGPU) {
  108959. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  108960. }
  108961. else {
  108962. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  108963. }
  108964. system.emitter = emitter;
  108965. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  108966. system.createConeEmitter(0.1, Math.PI / 4);
  108967. // Particle color
  108968. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  108969. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  108970. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  108971. // Particle Size
  108972. system.minSize = 0.1;
  108973. system.maxSize = 0.1;
  108974. // Emission speed
  108975. system.minEmitPower = 2;
  108976. system.maxEmitPower = 2;
  108977. // Update speed
  108978. system.updateSpeed = 1 / 60;
  108979. system.emitRate = 30;
  108980. return system;
  108981. };
  108982. /**
  108983. * This is the main static method (one-liner) of this helper to create different particle systems
  108984. * @param type This string represents the type to the particle system to create
  108985. * @param scene The scene where the particle system should live
  108986. * @param gpu If the system will use gpu
  108987. * @returns the ParticleSystemSet created
  108988. */
  108989. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  108990. if (gpu === void 0) { gpu = false; }
  108991. if (!scene) {
  108992. scene = BABYLON.Engine.LastCreatedScene;
  108993. ;
  108994. }
  108995. var token = {};
  108996. scene._addPendingData(token);
  108997. return new Promise(function (resolve, reject) {
  108998. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  108999. scene._removePendingData(token);
  109000. return reject("Particle system with GPU is not supported.");
  109001. }
  109002. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  109003. scene._removePendingData(token);
  109004. var newData = JSON.parse(data.toString());
  109005. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  109006. }, undefined, undefined, undefined, function (req, exception) {
  109007. scene._removePendingData(token);
  109008. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  109009. });
  109010. });
  109011. };
  109012. /**
  109013. * Static function used to export a particle system to a ParticleSystemSet variable.
  109014. * Please note that the emitter shape is not exported
  109015. * @param system defines the particle systems to export
  109016. */
  109017. ParticleHelper.ExportSet = function (systems) {
  109018. var set = new BABYLON.ParticleSystemSet();
  109019. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  109020. var system = systems_1[_i];
  109021. set.systems.push(system);
  109022. }
  109023. return set;
  109024. };
  109025. /**
  109026. * Gets or sets base Assets URL
  109027. */
  109028. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  109029. return ParticleHelper;
  109030. }());
  109031. BABYLON.ParticleHelper = ParticleHelper;
  109032. })(BABYLON || (BABYLON = {}));
  109033. //# sourceMappingURL=babylon.particleHelper.js.map
  109034. var BABYLON;
  109035. (function (BABYLON) {
  109036. /**
  109037. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  109038. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  109039. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  109040. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  109041. */
  109042. var VideoDome = /** @class */ (function (_super) {
  109043. __extends(VideoDome, _super);
  109044. /**
  109045. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  109046. * @param name Element's name, child elements will append suffixes for their own names.
  109047. * @param urlsOrVideo defines the url(s) or the video element to use
  109048. * @param options An object containing optional or exposed sub element properties
  109049. */
  109050. function VideoDome(name, urlsOrVideo, options, scene) {
  109051. var _this = _super.call(this, name, scene) || this;
  109052. _this._useDirectMapping = false;
  109053. // set defaults and manage values
  109054. name = name || "videoDome";
  109055. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  109056. options.clickToPlay = Boolean(options.clickToPlay);
  109057. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  109058. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  109059. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  109060. if (options.useDirectMapping === undefined) {
  109061. _this._useDirectMapping = true;
  109062. }
  109063. else {
  109064. _this._useDirectMapping = options.useDirectMapping;
  109065. }
  109066. _this._setReady(false);
  109067. // create
  109068. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  109069. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  109070. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  109071. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  109072. texture.onLoadObservable.addOnce(function () {
  109073. _this._setReady(true);
  109074. });
  109075. // configure material
  109076. material.useEquirectangularFOV = true;
  109077. material.fovMultiplier = 1.0;
  109078. material.opacityFresnel = false;
  109079. if (_this._useDirectMapping) {
  109080. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109081. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109082. material.diffuseTexture = texture;
  109083. }
  109084. else {
  109085. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  109086. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109087. material.reflectionTexture = texture;
  109088. }
  109089. // configure mesh
  109090. _this._mesh.material = material;
  109091. _this._mesh.parent = _this;
  109092. // optional configuration
  109093. if (options.clickToPlay) {
  109094. scene.onPointerUp = function () {
  109095. _this._videoTexture.video.play();
  109096. };
  109097. }
  109098. return _this;
  109099. }
  109100. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  109101. /**
  109102. * Gets the video texture being displayed on the sphere
  109103. */
  109104. get: function () {
  109105. return this._videoTexture;
  109106. },
  109107. enumerable: true,
  109108. configurable: true
  109109. });
  109110. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  109111. /**
  109112. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  109113. * Also see the options.resolution property.
  109114. */
  109115. get: function () {
  109116. return this._material.fovMultiplier;
  109117. },
  109118. set: function (value) {
  109119. this._material.fovMultiplier = value;
  109120. },
  109121. enumerable: true,
  109122. configurable: true
  109123. });
  109124. /**
  109125. * Releases resources associated with this node.
  109126. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  109127. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  109128. */
  109129. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  109130. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  109131. this._videoTexture.dispose();
  109132. this._mesh.dispose();
  109133. this._material.dispose();
  109134. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  109135. };
  109136. return VideoDome;
  109137. }(BABYLON.TransformNode));
  109138. BABYLON.VideoDome = VideoDome;
  109139. })(BABYLON || (BABYLON = {}));
  109140. //# sourceMappingURL=babylon.videoDome.js.map
  109141. var BABYLON;
  109142. (function (BABYLON) {
  109143. /**
  109144. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  109145. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  109146. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  109147. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  109148. */
  109149. var PhotoDome = /** @class */ (function (_super) {
  109150. __extends(PhotoDome, _super);
  109151. /**
  109152. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  109153. * @param name Element's name, child elements will append suffixes for their own names.
  109154. * @param urlsOfPhoto defines the url of the photo to display
  109155. * @param options defines an object containing optional or exposed sub element properties
  109156. * @param onError defines a callback called when an error occured while loading the texture
  109157. */
  109158. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  109159. if (onError === void 0) { onError = null; }
  109160. var _this = _super.call(this, name, scene) || this;
  109161. _this._useDirectMapping = false;
  109162. /**
  109163. * Observable raised when an error occured while loading the 360 image
  109164. */
  109165. _this.onLoadErrorObservable = new BABYLON.Observable();
  109166. // set defaults and manage values
  109167. name = name || "photoDome";
  109168. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  109169. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  109170. if (options.useDirectMapping === undefined) {
  109171. _this._useDirectMapping = true;
  109172. }
  109173. else {
  109174. _this._useDirectMapping = options.useDirectMapping;
  109175. }
  109176. _this._setReady(false);
  109177. // create
  109178. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  109179. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  109180. // configure material
  109181. material.opacityFresnel = false;
  109182. material.useEquirectangularFOV = true;
  109183. material.fovMultiplier = 1.0;
  109184. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  109185. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  109186. if (onError) {
  109187. onError(message, exception);
  109188. }
  109189. });
  109190. _this.photoTexture.onLoadObservable.addOnce(function () {
  109191. _this._setReady(true);
  109192. });
  109193. // configure mesh
  109194. _this._mesh.material = material;
  109195. _this._mesh.parent = _this;
  109196. return _this;
  109197. }
  109198. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  109199. /**
  109200. * Gets or sets the texture being displayed on the sphere
  109201. */
  109202. get: function () {
  109203. return this._photoTexture;
  109204. },
  109205. set: function (value) {
  109206. if (this._photoTexture === value) {
  109207. return;
  109208. }
  109209. this._photoTexture = value;
  109210. if (this._useDirectMapping) {
  109211. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109212. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109213. this._material.diffuseTexture = this._photoTexture;
  109214. }
  109215. else {
  109216. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  109217. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109218. this._material.reflectionTexture = this._photoTexture;
  109219. }
  109220. },
  109221. enumerable: true,
  109222. configurable: true
  109223. });
  109224. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  109225. /**
  109226. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  109227. * Also see the options.resolution property.
  109228. */
  109229. get: function () {
  109230. return this._material.fovMultiplier;
  109231. },
  109232. set: function (value) {
  109233. this._material.fovMultiplier = value;
  109234. },
  109235. enumerable: true,
  109236. configurable: true
  109237. });
  109238. /**
  109239. * Releases resources associated with this node.
  109240. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  109241. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  109242. */
  109243. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  109244. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  109245. this._photoTexture.dispose();
  109246. this._mesh.dispose();
  109247. this._material.dispose();
  109248. this.onLoadErrorObservable.clear();
  109249. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  109250. };
  109251. return PhotoDome;
  109252. }(BABYLON.TransformNode));
  109253. BABYLON.PhotoDome = PhotoDome;
  109254. })(BABYLON || (BABYLON = {}));
  109255. //# sourceMappingURL=babylon.photoDome.js.map
  109256. var BABYLON;
  109257. (function (BABYLON) {
  109258. BABYLON.Engine.prototype.createQuery = function () {
  109259. return this._gl.createQuery();
  109260. };
  109261. BABYLON.Engine.prototype.deleteQuery = function (query) {
  109262. this._gl.deleteQuery(query);
  109263. return this;
  109264. };
  109265. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  109266. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  109267. };
  109268. BABYLON.Engine.prototype.getQueryResult = function (query) {
  109269. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  109270. };
  109271. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  109272. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  109273. this._gl.beginQuery(glAlgorithm, query);
  109274. return this;
  109275. };
  109276. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  109277. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  109278. this._gl.endQuery(glAlgorithm);
  109279. return this;
  109280. };
  109281. BABYLON.Engine.prototype._createTimeQuery = function () {
  109282. var timerQuery = this.getCaps().timerQuery;
  109283. if (timerQuery.createQueryEXT) {
  109284. return timerQuery.createQueryEXT();
  109285. }
  109286. return this.createQuery();
  109287. };
  109288. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  109289. var timerQuery = this.getCaps().timerQuery;
  109290. if (timerQuery.deleteQueryEXT) {
  109291. timerQuery.deleteQueryEXT(query);
  109292. return;
  109293. }
  109294. this.deleteQuery(query);
  109295. };
  109296. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  109297. var timerQuery = this.getCaps().timerQuery;
  109298. if (timerQuery.getQueryObjectEXT) {
  109299. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  109300. }
  109301. return this.getQueryResult(query);
  109302. };
  109303. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  109304. var timerQuery = this.getCaps().timerQuery;
  109305. if (timerQuery.getQueryObjectEXT) {
  109306. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  109307. }
  109308. return this.isQueryResultAvailable(query);
  109309. };
  109310. BABYLON.Engine.prototype.startTimeQuery = function () {
  109311. var caps = this.getCaps();
  109312. var timerQuery = caps.timerQuery;
  109313. if (!timerQuery) {
  109314. return null;
  109315. }
  109316. var token = new BABYLON._TimeToken();
  109317. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  109318. if (caps.canUseTimestampForTimerQuery) {
  109319. token._startTimeQuery = this._createTimeQuery();
  109320. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  109321. }
  109322. else {
  109323. if (this._currentNonTimestampToken) {
  109324. return this._currentNonTimestampToken;
  109325. }
  109326. token._timeElapsedQuery = this._createTimeQuery();
  109327. if (timerQuery.beginQueryEXT) {
  109328. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  109329. }
  109330. else {
  109331. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  109332. }
  109333. this._currentNonTimestampToken = token;
  109334. }
  109335. return token;
  109336. };
  109337. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  109338. var caps = this.getCaps();
  109339. var timerQuery = caps.timerQuery;
  109340. if (!timerQuery || !token) {
  109341. return -1;
  109342. }
  109343. if (caps.canUseTimestampForTimerQuery) {
  109344. if (!token._startTimeQuery) {
  109345. return -1;
  109346. }
  109347. if (!token._endTimeQuery) {
  109348. token._endTimeQuery = this._createTimeQuery();
  109349. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  109350. }
  109351. }
  109352. else if (!token._timeElapsedQueryEnded) {
  109353. if (!token._timeElapsedQuery) {
  109354. return -1;
  109355. }
  109356. if (timerQuery.endQueryEXT) {
  109357. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  109358. }
  109359. else {
  109360. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  109361. }
  109362. token._timeElapsedQueryEnded = true;
  109363. }
  109364. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  109365. var available = false;
  109366. if (token._endTimeQuery) {
  109367. available = this._getTimeQueryAvailability(token._endTimeQuery);
  109368. }
  109369. else if (token._timeElapsedQuery) {
  109370. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  109371. }
  109372. if (available && !disjoint) {
  109373. var result = 0;
  109374. if (caps.canUseTimestampForTimerQuery) {
  109375. if (!token._startTimeQuery || !token._endTimeQuery) {
  109376. return -1;
  109377. }
  109378. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  109379. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  109380. result = timeEnd - timeStart;
  109381. this._deleteTimeQuery(token._startTimeQuery);
  109382. this._deleteTimeQuery(token._endTimeQuery);
  109383. token._startTimeQuery = null;
  109384. token._endTimeQuery = null;
  109385. }
  109386. else {
  109387. if (!token._timeElapsedQuery) {
  109388. return -1;
  109389. }
  109390. result = this._getTimeQueryResult(token._timeElapsedQuery);
  109391. this._deleteTimeQuery(token._timeElapsedQuery);
  109392. token._timeElapsedQuery = null;
  109393. token._timeElapsedQueryEnded = false;
  109394. this._currentNonTimestampToken = null;
  109395. }
  109396. return result;
  109397. }
  109398. return -1;
  109399. };
  109400. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  109401. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  109402. };
  109403. // We also need to update AbstractMesh as there is a portion of the code there
  109404. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  109405. if (this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  109406. this._isOccluded = false;
  109407. return;
  109408. }
  109409. var engine = this.getEngine();
  109410. if (engine.webGLVersion < 2) {
  109411. this._isOccluded = false;
  109412. return;
  109413. }
  109414. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  109415. this._isOccluded = false;
  109416. return;
  109417. }
  109418. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  109419. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  109420. if (isOcclusionQueryAvailable) {
  109421. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  109422. this._isOcclusionQueryInProgress = false;
  109423. this._occlusionInternalRetryCounter = 0;
  109424. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  109425. }
  109426. else {
  109427. this._occlusionInternalRetryCounter++;
  109428. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  109429. this._isOcclusionQueryInProgress = false;
  109430. this._occlusionInternalRetryCounter = 0;
  109431. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  109432. // if strict continue the last state of the object.
  109433. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  109434. }
  109435. else {
  109436. return;
  109437. }
  109438. }
  109439. }
  109440. var scene = this.getScene();
  109441. if (scene.getBoundingBoxRenderer) {
  109442. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  109443. if (!this._occlusionQuery) {
  109444. this._occlusionQuery = engine.createQuery();
  109445. }
  109446. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  109447. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  109448. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  109449. this._isOcclusionQueryInProgress = true;
  109450. }
  109451. };
  109452. })(BABYLON || (BABYLON = {}));
  109453. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  109454. var BABYLON;
  109455. (function (BABYLON) {
  109456. /**
  109457. * Class used to generate noise procedural textures
  109458. */
  109459. var NoiseProceduralTexture = /** @class */ (function (_super) {
  109460. __extends(NoiseProceduralTexture, _super);
  109461. /**
  109462. * Creates a new NoiseProceduralTexture
  109463. * @param name defines the name fo the texture
  109464. * @param size defines the size of the texture (default is 256)
  109465. * @param scene defines the hosting scene
  109466. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  109467. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  109468. */
  109469. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  109470. if (size === void 0) { size = 256; }
  109471. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  109472. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  109473. _this._time = 0;
  109474. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  109475. _this.brightness = 0.2;
  109476. /** Defines the number of octaves to process */
  109477. _this.octaves = 3;
  109478. /** Defines the level of persistence (0.8 by default) */
  109479. _this.persistence = 0.8;
  109480. /** Gets or sets animation speed factor (default is 1) */
  109481. _this.animationSpeedFactor = 1;
  109482. _this._updateShaderUniforms();
  109483. return _this;
  109484. }
  109485. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  109486. var scene = this.getScene();
  109487. if (!scene) {
  109488. return;
  109489. }
  109490. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  109491. this.setFloat("brightness", this.brightness);
  109492. this.setFloat("persistence", this.persistence);
  109493. this.setFloat("timeScale", this._time);
  109494. };
  109495. NoiseProceduralTexture.prototype._getDefines = function () {
  109496. return "#define OCTAVES " + (this.octaves | 0);
  109497. };
  109498. /** Generate the current state of the procedural texture */
  109499. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  109500. this._updateShaderUniforms();
  109501. _super.prototype.render.call(this, useCameraPostProcess);
  109502. };
  109503. /**
  109504. * Serializes this noise procedural texture
  109505. * @returns a serialized noise procedural texture object
  109506. */
  109507. NoiseProceduralTexture.prototype.serialize = function () {
  109508. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  109509. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  109510. return serializationObject;
  109511. };
  109512. /**
  109513. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  109514. * @param parsedTexture defines parsed texture data
  109515. * @param scene defines the current scene
  109516. * @param rootUrl defines the root URL containing noise procedural texture information
  109517. * @returns a parsed NoiseProceduralTexture
  109518. */
  109519. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  109520. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  109521. return texture;
  109522. };
  109523. return NoiseProceduralTexture;
  109524. }(BABYLON.ProceduralTexture));
  109525. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  109526. })(BABYLON || (BABYLON = {}));
  109527. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  109528. var __assign = (this && this.__assign) || function () {
  109529. __assign = Object.assign || function(t) {
  109530. for (var s, i = 1, n = arguments.length; i < n; i++) {
  109531. s = arguments[i];
  109532. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  109533. t[p] = s[p];
  109534. }
  109535. return t;
  109536. };
  109537. return __assign.apply(this, arguments);
  109538. };
  109539. var BABYLON;
  109540. (function (BABYLON) {
  109541. /**
  109542. * This can helps recording videos from BabylonJS.
  109543. * This is based on the available WebRTC functionalities of the browser.
  109544. *
  109545. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  109546. */
  109547. var VideoRecorder = /** @class */ (function () {
  109548. /**
  109549. * Create a new VideoCapture object which can help converting what you see in Babylon to
  109550. * a video file.
  109551. * @param engine Defines the BabylonJS Engine you wish to record
  109552. * @param options Defines options that can be used to customized the capture
  109553. */
  109554. function VideoRecorder(engine, options) {
  109555. if (options === void 0) { options = null; }
  109556. if (!VideoRecorder.IsSupported(engine)) {
  109557. throw "Your browser does not support recording so far.";
  109558. }
  109559. var canvas = engine.getRenderingCanvas();
  109560. if (!canvas) {
  109561. throw "The babylon engine must have a canvas to be recorded";
  109562. }
  109563. this._canvas = canvas;
  109564. this._canvas.isRecording = false;
  109565. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  109566. var stream = this._canvas.captureStream(this._options.fps);
  109567. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  109568. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  109569. this._mediaRecorder.onerror = this._handleError.bind(this);
  109570. this._mediaRecorder.onstop = this._handleStop.bind(this);
  109571. }
  109572. /**
  109573. * Returns wehther or not the VideoRecorder is available in your browser.
  109574. * @param engine Defines the Babylon Engine to check the support for
  109575. * @returns true if supported otherwise false
  109576. */
  109577. VideoRecorder.IsSupported = function (engine) {
  109578. var canvas = engine.getRenderingCanvas();
  109579. return (!!canvas && typeof canvas.captureStream === "function");
  109580. };
  109581. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  109582. /**
  109583. * True wether a recording is already in progress.
  109584. */
  109585. get: function () {
  109586. return !!this._canvas && this._canvas.isRecording;
  109587. },
  109588. enumerable: true,
  109589. configurable: true
  109590. });
  109591. /**
  109592. * Stops the current recording before the default capture timeout passed in the startRecording
  109593. * functions.
  109594. */
  109595. VideoRecorder.prototype.stopRecording = function () {
  109596. if (!this._canvas || !this._mediaRecorder) {
  109597. return;
  109598. }
  109599. if (!this.isRecording) {
  109600. return;
  109601. }
  109602. this._canvas.isRecording = false;
  109603. this._mediaRecorder.stop();
  109604. };
  109605. /**
  109606. * Starts recording the canvas for a max duration specified in parameters.
  109607. * @param fileName Defines the name of the file to be downloaded when the recording stop. If null no automatic download will start and you can rely on the promise to get the data back.
  109608. * @param maxDuration Defines the maximum recording time in seconds.
  109609. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  109610. * @return a promise callback at the end of the recording with the video data in Blob.
  109611. */
  109612. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  109613. var _this = this;
  109614. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  109615. if (maxDuration === void 0) { maxDuration = 7; }
  109616. if (!this._canvas || !this._mediaRecorder) {
  109617. throw "Recorder has already been disposed";
  109618. }
  109619. if (this.isRecording) {
  109620. throw "Recording already in progress";
  109621. }
  109622. if (maxDuration > 0) {
  109623. setTimeout(function () {
  109624. _this.stopRecording();
  109625. }, maxDuration * 1000);
  109626. }
  109627. this._fileName = fileName;
  109628. this._recordedChunks = [];
  109629. this._resolve = null;
  109630. this._reject = null;
  109631. this._canvas.isRecording = true;
  109632. this._mediaRecorder.start(this._options.recordChunckSize);
  109633. return new Promise(function (resolve, reject) {
  109634. _this._resolve = resolve;
  109635. _this._reject = reject;
  109636. });
  109637. };
  109638. /**
  109639. * Releases internal resources used during the recording.
  109640. */
  109641. VideoRecorder.prototype.dispose = function () {
  109642. this._canvas = null;
  109643. this._mediaRecorder = null;
  109644. this._recordedChunks = [];
  109645. this._fileName = null;
  109646. this._resolve = null;
  109647. this._reject = null;
  109648. };
  109649. VideoRecorder.prototype._handleDataAvailable = function (event) {
  109650. if (event.data.size > 0) {
  109651. this._recordedChunks.push(event.data);
  109652. }
  109653. };
  109654. VideoRecorder.prototype._handleError = function (event) {
  109655. this.stopRecording();
  109656. if (this._reject) {
  109657. this._reject(event.error);
  109658. }
  109659. else {
  109660. throw new event.error;
  109661. }
  109662. };
  109663. VideoRecorder.prototype._handleStop = function () {
  109664. this.stopRecording();
  109665. var superBuffer = new Blob(this._recordedChunks);
  109666. if (this._resolve) {
  109667. this._resolve(superBuffer);
  109668. }
  109669. window.URL.createObjectURL(superBuffer);
  109670. if (this._fileName) {
  109671. BABYLON.Tools.Download(superBuffer, this._fileName);
  109672. }
  109673. };
  109674. VideoRecorder._defaultOptions = {
  109675. mimeType: "video/webm",
  109676. fps: 25,
  109677. recordChunckSize: 3000
  109678. };
  109679. return VideoRecorder;
  109680. }());
  109681. BABYLON.VideoRecorder = VideoRecorder;
  109682. })(BABYLON || (BABYLON = {}));
  109683. //# sourceMappingURL=babylon.videoRecorder.js.map
  109684. var BABYLON;
  109685. (function (BABYLON) {
  109686. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  109687. if (replace === void 0) { replace = false; }
  109688. // Dispose existing light in replace mode.
  109689. if (replace) {
  109690. if (this.lights) {
  109691. for (var i = 0; i < this.lights.length; i++) {
  109692. this.lights[i].dispose();
  109693. }
  109694. }
  109695. }
  109696. // Light
  109697. if (this.lights.length === 0) {
  109698. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  109699. }
  109700. };
  109701. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  109702. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  109703. if (replace === void 0) { replace = false; }
  109704. if (attachCameraControls === void 0) { attachCameraControls = false; }
  109705. // Dispose existing camera in replace mode.
  109706. if (replace) {
  109707. if (this.activeCamera) {
  109708. this.activeCamera.dispose();
  109709. this.activeCamera = null;
  109710. }
  109711. }
  109712. // Camera
  109713. if (!this.activeCamera) {
  109714. var worldExtends = this.getWorldExtends();
  109715. var worldSize = worldExtends.max.subtract(worldExtends.min);
  109716. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  109717. var camera;
  109718. var radius = worldSize.length() * 1.5;
  109719. // empty scene scenario!
  109720. if (!isFinite(radius)) {
  109721. radius = 1;
  109722. worldCenter.copyFromFloats(0, 0, 0);
  109723. }
  109724. if (createArcRotateCamera) {
  109725. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  109726. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  109727. arcRotateCamera.wheelPrecision = 100 / radius;
  109728. camera = arcRotateCamera;
  109729. }
  109730. else {
  109731. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  109732. freeCamera.setTarget(worldCenter);
  109733. camera = freeCamera;
  109734. }
  109735. camera.minZ = radius * 0.01;
  109736. camera.maxZ = radius * 1000;
  109737. camera.speed = radius * 0.2;
  109738. this.activeCamera = camera;
  109739. var canvas = this.getEngine().getRenderingCanvas();
  109740. if (attachCameraControls && canvas) {
  109741. camera.attachControl(canvas);
  109742. }
  109743. }
  109744. };
  109745. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  109746. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  109747. if (replace === void 0) { replace = false; }
  109748. if (attachCameraControls === void 0) { attachCameraControls = false; }
  109749. this.createDefaultLight(replace);
  109750. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  109751. };
  109752. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  109753. if (pbr === void 0) { pbr = false; }
  109754. if (scale === void 0) { scale = 1000; }
  109755. if (blur === void 0) { blur = 0; }
  109756. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  109757. if (!environmentTexture) {
  109758. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  109759. return null;
  109760. }
  109761. if (setGlobalEnvTexture) {
  109762. if (environmentTexture) {
  109763. this.environmentTexture = environmentTexture;
  109764. }
  109765. }
  109766. // Skybox
  109767. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  109768. if (pbr) {
  109769. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  109770. hdrSkyboxMaterial.backFaceCulling = false;
  109771. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  109772. if (hdrSkyboxMaterial.reflectionTexture) {
  109773. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  109774. }
  109775. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  109776. hdrSkyboxMaterial.disableLighting = true;
  109777. hdrSkyboxMaterial.twoSidedLighting = true;
  109778. hdrSkybox.infiniteDistance = true;
  109779. hdrSkybox.material = hdrSkyboxMaterial;
  109780. }
  109781. else {
  109782. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  109783. skyboxMaterial.backFaceCulling = false;
  109784. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  109785. if (skyboxMaterial.reflectionTexture) {
  109786. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  109787. }
  109788. skyboxMaterial.disableLighting = true;
  109789. hdrSkybox.infiniteDistance = true;
  109790. hdrSkybox.material = skyboxMaterial;
  109791. }
  109792. return hdrSkybox;
  109793. };
  109794. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  109795. if (BABYLON.EnvironmentHelper) {
  109796. return new BABYLON.EnvironmentHelper(options, this);
  109797. }
  109798. return null;
  109799. };
  109800. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  109801. if (webVROptions === void 0) { webVROptions = {}; }
  109802. return new BABYLON.VRExperienceHelper(this, webVROptions);
  109803. };
  109804. })(BABYLON || (BABYLON = {}));
  109805. //# sourceMappingURL=babylon.sceneHelpers.js.map
  109806. 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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\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#ifdef ALPHATEST\nuniform float alphaCutOff;\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<alphaCutOff)\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) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\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;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\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;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\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;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\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) || defined(SPECULARAA)\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#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\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#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,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);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=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.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=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;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\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(-viewDirectionW,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.rgb*=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.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\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#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*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}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\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 float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \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#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\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}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,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() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*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(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-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;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\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}","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}","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;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\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;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\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\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\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;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\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);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\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}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\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}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \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{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\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\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{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\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;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,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}","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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\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\nvec4 reflectionColor=vec4(1.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=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.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\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.rgb,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","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  109807. 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\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\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\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\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}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\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};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(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;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(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 REFLECTION\nuniform mat4 reflectionMatrix;\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=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=clamp(color,0.0,1.0);\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\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\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\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\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\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>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}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,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#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif 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 vec4 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 vec4 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 vec4 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,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\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#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\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 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\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};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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*info.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,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.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*info.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,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\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,float geometricRoughnessFactor,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,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\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;\nreturn toLinearSpace(textureColor);\n}","clipPlaneVertexDeclaration2":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif","clipPlaneFragmentDeclaration2":"#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \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\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\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 vPrimaryColorShadow;\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);
  109808. globalObject["BABYLON"] = BABYLON;
  109809. 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 serializeAsCameraReference = BABYLON.serializeAsCameraReference;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 ColorGradient = BABYLON.ColorGradient;var Color3Gradient = BABYLON.Color3Gradient;var FactorGradient = BABYLON.FactorGradient;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 SceneComponentConstants = BABYLON.SceneComponentConstants;var Stage = BABYLON.Stage;var AbstractScene = BABYLON.AbstractScene;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 PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;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 SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var SpriteSceneComponent = BABYLON.SpriteSceneComponent;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 BaseParticleSystem = BABYLON.BaseParticleSystem;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var CylinderParticleEmitter = BABYLON.CylinderParticleEmitter;var CylinderDirectedParticleEmitter = BABYLON.CylinderDirectedParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var HemisphericParticleEmitter = BABYLON.HemisphericParticleEmitter;var PointParticleEmitter = BABYLON.PointParticleEmitter;var SubEmitter = BABYLON.SubEmitter;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var StringDictionary = BABYLON.StringDictionary;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;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 WeightedSound = BABYLON.WeightedSound;var AudioSceneComponent = BABYLON.AudioSceneComponent;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var CubeTexture = BABYLON.CubeTexture;var RawCubeTexture = BABYLON.RawCubeTexture;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 RawTexture3D = BABYLON.RawTexture3D;var PostProcessManager = BABYLON.PostProcessManager;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var ShadowGeneratorSceneComponent = BABYLON.ShadowGeneratorSceneComponent;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;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 ProceduralTextureSceneComponent = BABYLON.ProceduralTextureSceneComponent;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 GamepadSystemSceneComponent = BABYLON.GamepadSystemSceneComponent;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderPipelineManagerSceneComponent = BABYLON.PostProcessRenderPipelineManagerSceneComponent;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var DepthRendererSceneComponent = BABYLON.DepthRendererSceneComponent;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var GeometryBufferRendererSceneComponent = BABYLON.GeometryBufferRendererSceneComponent;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 ImageProcessingConfigurationDefines = BABYLON.ImageProcessingConfigurationDefines;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;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 HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystemSceneComponent = BABYLON.LensFlareSystemSceneComponent;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 PhysicsEngineSceneComponent = BABYLON.PhysicsEngineSceneComponent;var DDSTools = BABYLON.DDSTools;var TGATools = BABYLON.TGATools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var EnvironmentTextureTools = BABYLON.EnvironmentTextureTools;var UtilityLayerRenderer = BABYLON.UtilityLayerRenderer;var PointerDragBehavior = BABYLON.PointerDragBehavior;var MultiPointerScaleBehavior = BABYLON.MultiPointerScaleBehavior;var SixDofDragBehavior = BABYLON.SixDofDragBehavior;var AttachToBoxBehavior = BABYLON.AttachToBoxBehavior;var FadeInOutBehavior = BABYLON.FadeInOutBehavior;var Gizmo = BABYLON.Gizmo;var AxisDragGizmo = BABYLON.AxisDragGizmo;var AxisScaleGizmo = BABYLON.AxisScaleGizmo;var PlaneRotationGizmo = BABYLON.PlaneRotationGizmo;var PositionGizmo = BABYLON.PositionGizmo;var RotationGizmo = BABYLON.RotationGizmo;var ScaleGizmo = BABYLON.ScaleGizmo;var BoundingBoxGizmo = BABYLON.BoundingBoxGizmo;var GizmoManager = BABYLON.GizmoManager;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var OctreeSceneComponent = BABYLON.OctreeSceneComponent;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;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 VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;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 SimplicationQueueSceneComponent = BABYLON.SimplicationQueueSceneComponent;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 LineEdgesRenderer = BABYLON.LineEdgesRenderer;var EffectLayerSceneComponent = BABYLON.EffectLayerSceneComponent;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 LayerSceneComponent = BABYLON.LayerSceneComponent;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 ParticleSystemSet = BABYLON.ParticleSystemSet;var ParticleHelper = BABYLON.ParticleHelper;var VideoDome = BABYLON.VideoDome;var PhotoDome = BABYLON.PhotoDome;var NoiseProceduralTexture = BABYLON.NoiseProceduralTexture;var VideoRecorder = BABYLON.VideoRecorder;var Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;var SubEmitterType = BABYLON.SubEmitterType ;var Debug = BABYLON.Debug ;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 ;
  109810. 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,serializeAsCameraReference,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,ColorGradient,Color3Gradient,FactorGradient,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,SceneComponentConstants,Stage,AbstractScene,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,PerformanceMonitor,RollingAverage,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,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,SpriteManager,Sprite,SpriteSceneComponent,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,BaseParticleSystem,ParticleSystem,BoxParticleEmitter,CylinderParticleEmitter,CylinderDirectedParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,HemisphericParticleEmitter,PointParticleEmitter,SubEmitter,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,StringDictionary,RayHelper,DebugLayer,BoundingBoxRenderer,GPUParticleSystem,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,MeshBuilder,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,WeightedSound,AudioSceneComponent,PlaySoundAction,StopSoundAction,CubeTexture,RawCubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,RawTexture3D,PostProcessManager,PostProcess,PassPostProcess,ShadowGenerator,ShadowGeneratorSceneComponent,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,ProceduralTextureSceneComponent,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,DaydreamController,GamepadSystemSceneComponent,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderPipelineManagerSceneComponent,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,DepthRendererSceneComponent,GeometryBufferRenderer,GeometryBufferRendererSceneComponent,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,ChromaticAberrationPostProcess,GrainPostProcess,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcessOptions,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,BloomMergePostProcess,ExtractHighlightsPostProcess,BloomEffect,DefaultRenderingPipeline,ImageProcessingConfigurationDefines,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,HDRTools,HDRCubeTexture,PanoramaToCubeMapTools,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystemSceneComponent,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,PhysicsEngineSceneComponent,DDSTools,TGATools,KhronosTextureContainer,EnvironmentTextureTools,UtilityLayerRenderer,PointerDragBehavior,MultiPointerScaleBehavior,SixDofDragBehavior,AttachToBoxBehavior,FadeInOutBehavior,Gizmo,AxisDragGizmo,AxisScaleGizmo,PlaneRotationGizmo,PositionGizmo,RotationGizmo,ScaleGizmo,BoundingBoxGizmo,GizmoManager,MorphTarget,MorphTargetManager,Octree,OctreeBlock,OctreeSceneComponent,AnaglyphPostProcess,AnaglyphArcRotateCamera,AnaglyphFreeCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicInterlacePostProcess,StereoscopicArcRotateCamera,StereoscopicFreeCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRDistortionCorrectionPostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationArcRotateCamera,VRDeviceOrientationGamepadCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,SimplicationQueueSceneComponent,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,LineEdgesRenderer,EffectLayerSceneComponent,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,LayerSceneComponent,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,ParticleSystemSet,ParticleHelper,VideoDome,PhotoDome,NoiseProceduralTexture,VideoRecorder,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,SubEmitterType ,Debug ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,JoystickAxis ,SimplificationType ,AssetTaskState };